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 ( "more than one HintSpan" ) ; Word word = getCurrentWord ( ) ; if ( word == null ) throw new IllegalStateException ( "no word to complete" ) ; autoCompleting = true ; text . delete ( selStart , selStart + word . postCursor . length ( ) ) ; text . delete ( selStart - word . preCursor . length ( ) , selStart ) ; text . insert ( selStart - word . preCursor . length ( ) , s ) ; setSelection ( selStart - word . preCursor . length ( ) + s . length ( ) ) ; fireOnFilterEvent ( null ) ; super . setImeOptions ( prevOptions ) ; autoCompleting = false ; }
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 ) ; mClampedStartingX = cX + ( float ) ( Math . cos ( angle ) * r ) ; mClampedStartingY = cY + ( float ) ( Math . sin ( angle ) * r ) ; } else { mClampedStartingX = mStartingX ; mClampedStartingY = mStartingY ; } }
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 . bottomLeftCorner = bottomLeftCorner ; }
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 = mRecyclerView . getLayoutManager ( ) ; if ( mTmpRect == null ) { mTmpRect = new Rect ( ) ; } int scrollX = 0 ; int scrollY = 0 ; lm . calculateItemDecorationsForChild ( mSelected . itemView , mTmpRect ) ; if ( lm . canScrollHorizontally ( ) ) { int curX = ( int ) ( mSelectedStartX + mDx ) ; final int leftDiff = curX - mTmpRect . left - mRecyclerView . getPaddingLeft ( ) ; if ( mDx < 0 && leftDiff < 0 ) { scrollX = leftDiff ; } else if ( mDx > 0 ) { final int rightDiff = curX + mSelected . itemView . getWidth ( ) + mTmpRect . right - ( mRecyclerView . getWidth ( ) - mRecyclerView . getPaddingRight ( ) ) ; if ( rightDiff > 0 ) { scrollX = rightDiff ; } } } if ( lm . canScrollVertically ( ) ) { int curY = ( int ) ( mSelectedStartY + mDy ) ; final int topDiff = curY - mTmpRect . top - mRecyclerView . getPaddingTop ( ) ; if ( mDy < 0 && topDiff < 0 ) { scrollY = topDiff ; } else if ( mDy > 0 ) { final int bottomDiff = curY + mSelected . itemView . getHeight ( ) + mTmpRect . bottom - ( mRecyclerView . getHeight ( ) - mRecyclerView . getPaddingBottom ( ) ) ; if ( bottomDiff > 0 ) { scrollY = bottomDiff ; } } } if ( scrollX != 0 ) { scrollX = mCallback . interpolateOutOfBoundsScroll ( mRecyclerView , mSelected . itemView . getWidth ( ) , scrollX , mRecyclerView . getWidth ( ) , scrollDuration ) ; } if ( scrollY != 0 ) { scrollY = mCallback . interpolateOutOfBoundsScroll ( mRecyclerView , mSelected . itemView . getHeight ( ) , scrollY , mRecyclerView . getHeight ( ) , scrollDuration ) ; } if ( scrollX != 0 || scrollY != 0 ) { if ( mDragScrollStartTimeInMs == Long . MIN_VALUE ) { mDragScrollStartTimeInMs = now ; } mRecyclerView . scrollBy ( scrollX , scrollY ) ; return true ; } mDragScrollStartTimeInMs = Long . MIN_VALUE ; return false ; }
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 ; if ( ! anim . mEnded ) { anim . cancel ( ) ; } mRecoverAnimations . remove ( i ) ; return anim . mAnimationType ; } } return 0 ; }
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_STATE_DRAGGING ) { return false ; } final ViewHolder vh = findSwipedView ( motionEvent ) ; if ( vh == null ) { return false ; } final int movementFlags = mCallback . getAbsoluteMovementFlags ( mRecyclerView , vh ) ; final int swipeFlags = ( movementFlags & ACTION_MODE_SWIPE_MASK ) >> ( DIRECTION_FLAG_COUNT * ACTION_STATE_SWIPE ) ; if ( swipeFlags == 0 ) { return false ; } final float x = motionEvent . getX ( pointerIndex ) ; final float y = motionEvent . getY ( pointerIndex ) ; final float dx = x - mInitialTouchX ; final float dy = y - mInitialTouchY ; final float absDx = Math . abs ( dx ) ; final float absDy = Math . abs ( dy ) ; if ( absDx < mSlop && absDy < mSlop ) { return false ; } if ( absDx > absDy ) { if ( dx < 0 && ( swipeFlags & LEFT ) == 0 ) { return false ; } if ( dx > 0 && ( swipeFlags & RIGHT ) == 0 ) { return false ; } } else { if ( dy < 0 && ( swipeFlags & UP ) == 0 ) { return false ; } if ( dy > 0 && ( swipeFlags & DOWN ) == 0 ) { return false ; } } mDx = mDy = 0f ; mActivePointerId = motionEvent . getPointerId ( 0 ) ; select ( vh , ACTION_STATE_SWIPE ) ; return true ; }
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 ( ) ) != XmlPullParser . END_DOCUMENT && ( ( depth = parser . getDepth ( ) ) >= innerDepth || type != XmlPullParser . END_TAG ) ) { if ( type != XmlPullParser . START_TAG ) { continue ; } if ( depth > innerDepth || ! parser . getName ( ) . equals ( "item" ) ) { continue ; } final ChildDrawable layer = new ChildDrawable ( ) ; final TypedArray a = obtainAttributes ( r , theme , attrs , R . styleable . LayerDrawableItem ) ; updateLayerFromTypedArray ( layer , a ) ; a . recycle ( ) ; if ( layer . mDrawable == null && ( layer . mThemeAttrs == null || layer . mThemeAttrs [ R . styleable . LayerDrawableItem_android_drawable ] == 0 ) ) { while ( ( type = parser . next ( ) ) == XmlPullParser . TEXT ) { } if ( type != XmlPullParser . START_TAG ) { throw new XmlPullParserException ( parser . getPositionDescription ( ) + ": <item> tag requires a 'drawable' attribute or " + "child tag defining a drawable" ) ; } layer . mDrawable = LollipopDrawablesCompat . createFromXmlInner ( r , parser , attrs , theme ) ; } if ( layer . mDrawable != null ) { state . mChildrenChangingConfigurations |= layer . mDrawable . getChangingConfigurations ( ) ; layer . mDrawable . setCallback ( this ) ; } addLayer ( layer ) ; } }
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 ) ; } st . mChildren = nu ; } st . mChildren [ i ] = layer ; st . mNum ++ ; st . invalidateCache ( ) ; return 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 ) childDrawable . mDrawable . setAutoMirrored ( isAutoMirrored ( ) ) ; childDrawable . mInsetL = left ; childDrawable . mInsetT = top ; childDrawable . mInsetR = right ; childDrawable . mInsetB = bottom ; addLayer ( childDrawable ) ; mLayerState . mChildrenChangingConfigurations |= dr . getChangingConfigurations ( ) ; dr . setCallback ( this ) ; return childDrawable ; }
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 ) { final Rect bounds = childDrawable . mDrawable . getBounds ( ) ; drawable . setBounds ( bounds ) ; } childDrawable . mDrawable . setCallback ( null ) ; } if ( drawable != null ) { drawable . setCallback ( this ) ; } childDrawable . mDrawable = drawable ; mLayerState . invalidateCache ( ) ; refreshChildPadding ( index , childDrawable ) ; }
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 [ i ] = rect . left ; mPaddingT [ i ] = rect . top ; mPaddingR [ i ] = rect . right ; mPaddingB [ i ] = rect . bottom ; return true ; } } return false ; }
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 Exception { MessageProducer producer = MetaqTemplate . this . messageSessionFactory . createProducer ( ) ; producer . publish ( topic ) ; if ( ! StringUtils . isBlank ( MetaqTemplate . this . defaultTopic ) ) { producer . setDefaultTopic ( MetaqTemplate . this . defaultTopic ) ; } return producer ; } } ) ; FutureTask < MessageProducer > oldTask = this . producers . putIfAbsent ( topic , task ) ; if ( oldTask != null ) { task = oldTask ; } else { task . run ( ) ; } } try { MessageProducer producer = task . get ( ) ; return producer ; } catch ( ExecutionException e ) { throw ThreadUtils . launderThrowable ( e . getCause ( ) ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } else { if ( this . sharedProducer == null ) { synchronized ( this ) { if ( this . sharedProducer == null ) { this . sharedProducer = this . messageSessionFactory . createProducer ( ) ; if ( ! StringUtils . isBlank ( this . defaultTopic ) ) { this . sharedProducer . setDefaultTopic ( this . defaultTopic ) ; } } } } this . sharedProducer . publish ( topic ) ; return this . sharedProducer ; } throw new IllegalStateException ( "Could not create producer for topic '" + topic + "'" ) ; }
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 ( msg , timeout , unit ) ; } catch ( MetaClientException e ) { return new SendResult ( false , null , - 1 , ExceptionUtils . getFullStackTrace ( e ) ) ; } }
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 , unit ) ; }
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 . payload ; if ( payload == null && converter != null ) { try { payload = converter . toByteArray ( ( T ) this . body ) ; } catch ( MetaClientException e ) { throw new IllegalStateException ( "Convert message body failed." , e ) ; } } if ( payload == null ) { throw new IllegalArgumentException ( "Empty payload" ) ; } return new Message ( this . topic , payload , this . attribute ) ; }
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 ) ; while ( ! acquired && new Date ( ) . getTime ( ) < timeToGiveUp ) { acquired = lockDao . acquireLock ( getMongoDatabase ( ) ) ; if ( ! acquired ) { logger . info ( "Waiting for changelog lock...." ) ; try { Thread . sleep ( changeLogLockPollRate * 1000 ) ; } catch ( InterruptedException e ) { } } } } if ( ! acquired && throwExceptionIfCannotObtainLock ) { logger . info ( "Mongobee did not acquire process lock. Throwing exception." ) ; throw new MongobeeLockException ( "Could not acquire process lock" ) ; } return acquired ; }
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 < TResult > tcs = new bolts . TaskCompletionSource < > ( ) ; tcs . setResult ( value ) ; return tcs . getTask ( ) ; }
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 . TaskCompletionSource < > ( ) ; synchronized ( lock ) { completed = this . isCompleted ( ) ; if ( ! completed ) { this . continuations . add ( new Continuation < TResult , Void > ( ) { public Void then ( Task < TResult > task ) { completeAfterTask ( tcs , continuation , task , executor , ct ) ; return null ; } } ) ; } } if ( completed ) { completeAfterTask ( tcs , continuation , this , executor , ct ) ; } return tcs . getTask ( ) ; }
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" ) ; String [ ] nameComponents = name . split ( ":" ) ; if ( ! nameComponents [ 0 ] . equals ( META_TAG_PREFIX ) ) { continue ; } Map < String , Object > root = al ; for ( int j = 1 ; j < nameComponents . length ; j ++ ) { @ SuppressWarnings ( "unchecked" ) List < Map < String , Object > > children = ( List < Map < String , Object > > ) root . get ( nameComponents [ j ] ) ; if ( children == null ) { children = new ArrayList < Map < String , Object > > ( ) ; root . put ( nameComponents [ j ] , children ) ; } Map < String , Object > child = children . size ( ) > 0 ? children . get ( children . size ( ) - 1 ) : null ; if ( child == null || j == nameComponents . length - 1 ) { child = new HashMap < String , Object > ( ) ; children . add ( child ) ; } root = child ; } if ( tag . has ( "content" ) ) { if ( tag . isNull ( "content" ) ) { root . put ( KEY_AL_VALUE , null ) ; } else { root . put ( KEY_AL_VALUE , tag . getString ( "content" ) ) ; } } } return al ; }
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 ( registrations ) ; }
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 1 second .
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 , MeasurementEvent . APP_LINK_NAVIGATE_IN_EVENT_NAME , intent , null ) ; return Uri . parse ( targetString ) ; } } return null ; }
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_PACKAGE , refererAppPackage ) ; } ApplicationInfo appInfo = context . getApplicationInfo ( ) ; if ( appInfo != null ) { String refererAppName = context . getString ( appInfo . labelRes ) ; if ( refererAppName != null ) { refererAppLinkData . putString ( KEY_NAME_REFERER_APP_LINK_APP_NAME , refererAppName ) ; } } } data . putAll ( getAppLinkData ( ) ) ; data . putString ( AppLinks . KEY_NAME_TARGET , getAppLink ( ) . getSourceUrl ( ) . toString ( ) ) ; data . putString ( KEY_NAME_VERSION , VERSION ) ; data . putString ( KEY_NAME_USER_AGENT , "Bolts Android " + Bolts . VERSION ) ; data . putBundle ( KEY_NAME_REFERER_APP_LINK , refererAppLinkData ) ; data . putBundle ( AppLinks . KEY_NAME_EXTRAS , getExtras ( ) ) ; return data ; }
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 ( Intent . ACTION_VIEW ) ; if ( target . getUrl ( ) != null ) { targetIntent . setData ( target . getUrl ( ) ) ; } else { targetIntent . setData ( appLink . getSourceUrl ( ) ) ; } targetIntent . setPackage ( target . getPackageName ( ) ) ; if ( target . getClassName ( ) != null ) { targetIntent . setClassName ( target . getPackageName ( ) , target . getClassName ( ) ) ; } targetIntent . putExtra ( AppLinks . KEY_NAME_APPLINK_DATA , finalAppLinkData ) ; ResolveInfo resolved = pm . resolveActivity ( targetIntent , PackageManager . MATCH_DEFAULT_ONLY ) ; if ( resolved != null ) { eligibleTargetIntent = targetIntent ; break ; } } Intent outIntent = null ; NavigationResult result = NavigationResult . FAILED ; if ( eligibleTargetIntent != null ) { outIntent = eligibleTargetIntent ; result = NavigationResult . APP ; } else { Uri webUrl = getAppLink ( ) . getWebUrl ( ) ; if ( webUrl != null ) { JSONObject appLinkDataJson ; try { appLinkDataJson = getJSONForBundle ( finalAppLinkData ) ; } catch ( JSONException e ) { sendAppLinkNavigateEventBroadcast ( context , eligibleTargetIntent , NavigationResult . FAILED , e ) ; throw new RuntimeException ( e ) ; } webUrl = webUrl . buildUpon ( ) . appendQueryParameter ( AppLinks . KEY_NAME_APPLINK_DATA , appLinkDataJson . toString ( ) ) . build ( ) ; outIntent = new Intent ( Intent . ACTION_VIEW , webUrl ) ; result = NavigationResult . WEB ; } } sendAppLinkNavigateEventBroadcast ( context , outIntent , result , null ) ; if ( outIntent != null ) { context . startActivity ( outIntent ) ; } return result ; }
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 ( ) . getName ( ) + ")" , cause ) ; e . fillInStackTrace ( ) ; initStacktrace = e ; if ( cause != null ) { LOGGER . warn ( "Registry used with Servo's SpectatorContext has been overwritten. This could " + "result in missing metrics." , e ) ; } } }
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 . ofMillis ( delayMillis ) ) . scheduleOn ( gaugePool ( ) ) ; }
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 ( ) ) ; PolledMeter . monitorMeter ( registry , m ) ; monitorMonitonicValues ( monitor ) ; } }
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 . propagate ( e ) ; } } } } return value ; }
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 ( BasicTagList . EMPTY , identifyCountersForPush ( metrics ) ) ; final int maxAttempts = 5 ; int attempts = 1 ; while ( ! pushQueue . offer ( tasks ) && attempts <= maxAttempts ) { ++ attempts ; final UpdateTasks droppedTasks = pushQueue . remove ( ) ; LOGGER . warn ( "Removing old push task due to queue full. Dropping {} metrics." , droppedTasks . numMetrics ) ; numMetricsDroppedQueueFull . increment ( droppedTasks . numMetrics ) ; } if ( attempts >= maxAttempts ) { LOGGER . error ( "Unable to push update of {}" , tasks ) ; numMetricsDroppedQueueFull . increment ( tasks . numMetrics ) ; } else { LOGGER . debug ( "Queued push of {}" , tasks ) ; } }
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 ( ) . code ( ) , batchSize ) ; numMetricsDroppedHttpErr . increment ( batchSize ) ; } return batchSize ; } ; }
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 ( spectatorTags ) ; } monitor = monitors . putIfAbsent ( contextConfig , newMon ) ; if ( monitor == null ) { monitor = newMon ; } } return monitor ; }
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 ( buf , 'W' , week , time ) ; time = append ( buf , 'D' , day , time ) ; buf . append ( 'T' ) ; time = append ( buf , 'H' , hour , time ) ; time = append ( buf , 'M' , minute , time ) ; append ( buf , 'S' , second , time ) ; return buf . toString ( ) ; }
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 uptimeMillis = ( Long ) threadCpuUsages . get ( UPTIME_MS ) ; final long uptimeNanos = TimeUnit . NANOSECONDS . convert ( uptimeMillis , TimeUnit . MILLISECONDS ) ; writer . printf ( "Uptime: %s%n%n" , toDuration ( uptimeNanos ) ) ; @ SuppressWarnings ( "unchecked" ) final Map < String , Long > jvmUsageTime = ( Map < String , Long > ) threadCpuUsages . get ( JVM_USAGE_TIME ) ; writer . println ( "JVM Usage Time: " ) ; writer . printf ( "%11s %11s %11s %11s %7s %s%n" , "1-min" , "5-min" , "15-min" , "overall" , "id" , "name" ) ; writer . printf ( "%11s %11s %11s %11s %7s %s%n" , toDuration ( jvmUsageTime . get ( ONE_MIN ) ) , toDuration ( jvmUsageTime . get ( FIVE_MIN ) ) , toDuration ( jvmUsageTime . get ( FIFTEEN_MIN ) ) , toDuration ( jvmUsageTime . get ( OVERALL ) ) , "-" , "jvm" ) ; writer . println ( ) ; @ SuppressWarnings ( "unchecked" ) final Map < String , Double > jvmUsagePerc = ( Map < String , Double > ) threadCpuUsages . get ( JVM_USAGE_PERCENT ) ; writer . println ( "JVM Usage Percent: " ) ; writer . printf ( "%11s %11s %11s %11s %7s %s%n" , "1-min" , "5-min" , "15-min" , "overall" , "id" , "name" ) ; writer . printf ( "%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7s %s%n" , jvmUsagePerc . get ( ONE_MIN ) , jvmUsagePerc . get ( FIVE_MIN ) , jvmUsagePerc . get ( FIFTEEN_MIN ) , jvmUsagePerc . get ( OVERALL ) , "-" , "jvm" ) ; writer . println ( ) ; writer . println ( "Breakdown by thread (100% = total cpu usage for jvm):" ) ; writer . printf ( "%11s %11s %11s %11s %7s %s%n" , "1-min" , "5-min" , "15-min" , "overall" , "id" , "name" ) ; @ SuppressWarnings ( "unchecked" ) List < Map < String , Object > > threads = ( List < Map < String , Object > > ) threadCpuUsages . get ( THREADS ) ; for ( Map < String , Object > thread : threads ) { writer . printf ( "%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7d %s%n" , thread . get ( ONE_MIN ) , thread . get ( FIVE_MIN ) , thread . get ( FIFTEEN_MIN ) , thread . get ( OVERALL ) , thread . get ( ID ) , thread . get ( NAME ) ) ; } writer . println ( ) ; writer . flush ( ) ; }
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 ( cpuTime != - 1 ) { totalCpuTime += cpuTime ; CpuUsage usage = threadCpuUsages . get ( id ) ; if ( usage == null ) { final ThreadInfo info = bean . getThreadInfo ( id ) ; usage = new CpuUsage ( id , info . getThreadName ( ) ) ; threadCpuUsages . put ( id , usage ) ; } usage . update ( cpuTime ) ; } } final OperatingSystemMXBean osBean = ManagementFactory . getOperatingSystemMXBean ( ) ; try { final Method m = osBean . getClass ( ) . getMethod ( "getProcessCpuTime" ) ; final long jvmCpuTime = ( Long ) m . invoke ( osBean ) ; jvmCpuUsage . update ( ( jvmCpuTime < 0 ) ? totalCpuTime : jvmCpuTime ) ; } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) { jvmCpuUsage . update ( totalCpuTime ) ; } final long now = System . currentTimeMillis ( ) ; final Iterator < Map . Entry < Long , CpuUsage > > iter = threadCpuUsages . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { final Map . Entry < Long , CpuUsage > entry = iter . next ( ) ; final long id = entry . getKey ( ) ; final CpuUsage usage = entry . getValue ( ) ; if ( now - usage . getLastUpdateTime ( ) > AGE_LIMIT ) { iter . remove ( ) ; } else if ( Arrays . binarySearch ( ids , id ) < 0 ) { usage . updateNoValue ( ) ; } } } else { LOGGER . debug ( "ThreadMXBean.isThreadCpuTimeEnabled() == false, cannot collect stats" ) ; } }
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 ) { Throwable cause = e . getCause ( ) ; if ( cause == null ) { cause = e ; } if ( cause instanceof Exception ) { throw ( Exception ) cause ; } if ( cause instanceof Error ) { throw ( Error ) cause ; } throw e ; } catch ( TimeoutException e ) { future . cancel ( true ) ; throw new UncheckedTimeoutException ( 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 exception .
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 ) ? DEFAULT_ID : id ; return new BasicCompositeMonitor ( newObjectConfig ( c , objectId , tags ) , monitors ) ; }
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 ) ; } return m ; }
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 . getClass ( ) , MonitorTags . class ) ; for ( Method method : methods ) { method . setAccessible ( true ) ; return ( TagList ) method . invoke ( obj ) ; } } catch ( Exception e ) { throw Throwables . propagate ( e ) ; } return null ; }
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 " + container . getName ( ) + " is applied to a field or method of type " + type . getName ( ) ; throw new IllegalArgumentException ( msg ) ; } }
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 . withTags ( tags ) ; } return builder . build ( ) ; }
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 . withTag ( "class" , className ( c ) ) ; builder . withTag ( anno . type ( ) ) ; builder . withTag ( anno . level ( ) ) ; if ( tags != null ) { builder . withTags ( tags ) ; } if ( id != null ) { builder . withTag ( "id" , id ) ; } return builder . build ( ) ; }
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 ] ; sumSquares += values [ i ] * values [ i ] ; } mean = ( double ) total / curSize ; if ( curSize == 1 ) { variance = 0d ; } else { variance = ( sumSquares - ( ( double ) total * total / curSize ) ) / ( curSize - 1 ) ; } stddev = Math . sqrt ( variance ) ; computePercentiles ( curSize ) ; }
Compute stats for the current set of values .