idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
30,500
public void clear ( int startIndex , int endIndex ) { if ( endIndex <= startIndex ) return ; int startWord = ( startIndex >> 6 ) ; if ( startWord >= wlen ) return ; int endWord = ( ( endIndex - 1 ) >> 6 ) ; long startmask = - 1L << startIndex ; long endmask = - 1L >>> - endIndex ; startmask = ~ startmask ; endmask = ~ endmask ; if ( startWord == endWord ) { bits [ startWord ] &= ( startmask | endmask ) ; return ; } bits [ startWord ] &= startmask ; int middle = Math . min ( wlen , endWord ) ; Arrays . fill ( bits , startWord + 1 , middle , 0L ) ; if ( endWord < wlen ) { bits [ endWord ] &= endmask ; } }
Clears a range of bits . Clearing past the end does not change the size of the set .
30,501
public boolean getAndSet ( int index ) { int wordNum = index >> 6 ; int bit = index & 0x3f ; long bitmask = 1L << bit ; boolean val = ( bits [ wordNum ] & bitmask ) != 0 ; bits [ wordNum ] |= bitmask ; return val ; }
Sets a bit and returns the previous value . The index should be less than the BitSet size .
30,502
public boolean flipAndGet ( long index ) { int wordNum = ( int ) ( index >> 6 ) ; int bit = ( int ) index & 0x3f ; long bitmask = 1L << bit ; bits [ wordNum ] ^= bitmask ; return ( bits [ wordNum ] & bitmask ) != 0 ; }
flips a bit and returns the resulting bit value . The index should be less than the BitSet size .
30,503
public void flip ( long startIndex , long endIndex ) { if ( endIndex <= startIndex ) return ; int startWord = ( int ) ( startIndex >> 6 ) ; int endWord = expandingWordNum ( endIndex - 1 ) ; long startmask = - 1L << startIndex ; long endmask = - 1L >>> - endIndex ; if ( startWord == endWord ) { bits [ startWord ] ^= ( startmask & endmask ) ; return ; } bits [ startWord ] ^= startmask ; for ( int i = startWord + 1 ; i < endWord ; i ++ ) { bits [ i ] = ~ bits [ i ] ; } bits [ endWord ] ^= endmask ; }
Flips a range of bits expanding the set size if necessary
30,504
private void shift ( ) { if ( ( int ) word == 0 ) { wordShift += 32 ; word = word >>> 32 ; } if ( ( word & 0x0000FFFF ) == 0 ) { wordShift += 16 ; word >>>= 16 ; } if ( ( word & 0x000000FF ) == 0 ) { wordShift += 8 ; word >>>= 8 ; } indexArray = bitlist [ ( int ) word & 0xff ] ; }
64 bit shifts
30,505
public void push ( KType e1 , KType e2 ) { ensureBufferSpace ( 2 ) ; buffer [ elementsCount ++ ] = e1 ; buffer [ elementsCount ++ ] = e2 ; }
Adds two KTypes to the stack .
30,506
public void push ( KType [ ] elements , int start , int len ) { assert start >= 0 && len >= 0 ; ensureBufferSpace ( len ) ; System . arraycopy ( elements , start , buffer , elementsCount , len ) ; elementsCount += len ; }
Add a range of array elements to the stack .
30,507
public void discard ( int count ) { assert elementsCount >= count ; elementsCount -= count ; Arrays . fill ( buffer , elementsCount , elementsCount + count , null ) ; }
Discard an arbitrary number of elements from the top of the stack .
30,508
public KType pop ( ) { assert elementsCount > 0 ; final KType v = Intrinsics . < KType > cast ( buffer [ -- elementsCount ] ) ; buffer [ elementsCount ] = null ; return v ; }
Remove the top element from the stack and return it .
30,509
@ SuppressWarnings ( "unchecked" ) public static < T > T add ( T op1 , T op2 ) { if ( op1 . getClass ( ) != op2 . getClass ( ) ) { throw new RuntimeException ( "Arguments of different classes: " + op1 + " " + op2 ) ; } if ( Byte . class . isInstance ( op1 ) ) { return ( T ) ( Byte ) ( byte ) ( ( ( Byte ) op1 ) . byteValue ( ) + ( ( Byte ) op2 ) . byteValue ( ) ) ; } if ( Short . class . isInstance ( op1 ) ) { return ( T ) ( Short ) ( short ) ( ( ( Short ) op1 ) . shortValue ( ) + ( ( Short ) op2 ) . shortValue ( ) ) ; } if ( Character . class . isInstance ( op1 ) ) { return ( T ) ( Character ) ( char ) ( ( ( Character ) op1 ) . charValue ( ) + ( ( Character ) op2 ) . charValue ( ) ) ; } if ( Integer . class . isInstance ( op1 ) ) { return ( T ) ( Integer ) ( ( ( Integer ) op1 ) . intValue ( ) + ( ( Integer ) op2 ) . intValue ( ) ) ; } if ( Float . class . isInstance ( op1 ) ) { return ( T ) ( Float ) ( ( ( Float ) op1 ) . floatValue ( ) + ( ( Float ) op2 ) . floatValue ( ) ) ; } if ( Long . class . isInstance ( op1 ) ) { return ( T ) ( Long ) ( ( ( Long ) op1 ) . longValue ( ) + ( ( Long ) op2 ) . longValue ( ) ) ; } if ( Double . class . isInstance ( op1 ) ) { return ( T ) ( Double ) ( ( ( Double ) op1 ) . doubleValue ( ) + ( ( Double ) op2 ) . doubleValue ( ) ) ; } throw new UnsupportedOperationException ( "Invalid for arbitrary types: " + op1 + " " + op2 ) ; }
An intrinsic that is replaced with plain addition of arguments for primitive template types . Invalid for non - number generic types .
30,510
public int removeAll ( final KTypeLookupContainer < ? super KType > c ) { return this . removeAll ( new KTypePredicate < KType > ( ) { public boolean apply ( KType k ) { return c . contains ( k ) ; } } ) ; }
Default implementation uses a predicate for removal .
30,511
public Object [ ] toArray ( ) { KType [ ] array = Intrinsics . < KType > newArray ( size ( ) ) ; int i = 0 ; for ( KTypeCursor < KType > c : this ) { array [ i ++ ] = c . value ; } return array ; }
Default implementation of copying to an array .
30,512
public static < KType , VType > KTypeVTypeHashMap < KType , VType > from ( KType [ ] keys , VType [ ] values ) { if ( keys . length != values . length ) { throw new IllegalArgumentException ( "Arrays of keys and values must have an identical length." ) ; } KTypeVTypeHashMap < KType , VType > map = new KTypeVTypeHashMap < > ( keys . length ) ; for ( int i = 0 ; i < keys . length ; i ++ ) { map . put ( keys [ i ] , values [ i ] ) ; } return map ; }
Creates a hash map from two index - aligned arrays of key - value pairs .
30,513
private String processComment ( String text , TemplateOptions options ) { if ( options . hasKType ( ) ) { text = text . replaceAll ( "(KType)(?=\\p{Lu})" , options . getKType ( ) . getBoxedType ( ) ) ; text = text . replace ( "KType" , options . getKType ( ) . getType ( ) ) ; } if ( options . hasVType ( ) ) { text = text . replaceAll ( "(VType)(?=\\p{Lu})" , options . getVType ( ) . getBoxedType ( ) ) ; text = text . replace ( "VType" , options . getVType ( ) . getType ( ) ) ; } return text ; }
Process references inside comment blocks javadocs etc .
30,514
public int addAll ( Iterable < ? extends KTypeCursor < ? extends KType > > iterable ) { int count = 0 ; for ( KTypeCursor < ? extends KType > cursor : iterable ) { if ( add ( cursor . value ) ) { count ++ ; } } return count ; }
Adds all elements from the given iterable to this set .
30,515
public KType indexGet ( int index ) { assert index >= 0 : "The index must point at an existing key." ; assert index <= mask || ( index == mask + 1 && hasEmptyKey ) ; return Intrinsics . < KType > cast ( keys [ index ] ) ; }
Returns the exact value of the existing key . This method makes sense for sets of objects which define custom key - equality relationship .
30,516
public KType indexReplace ( int index , KType equivalentKey ) { assert index >= 0 : "The index must point at an existing key." ; assert index <= mask || ( index == mask + 1 && hasEmptyKey ) ; assert Intrinsics . equals ( this , keys [ index ] , equivalentKey ) ; KType previousValue = Intrinsics . < KType > cast ( keys [ index ] ) ; keys [ index ] = equivalentKey ; return previousValue ; }
Replaces the existing equivalent key with the given one and returns any previous value stored for that key .
30,517
public void indexInsert ( int index , KType key ) { assert index < 0 : "The index must not point at an existing key." ; index = ~ index ; if ( Intrinsics . isEmpty ( key ) ) { assert index == mask + 1 ; assert Intrinsics . isEmpty ( keys [ index ] ) ; hasEmptyKey = true ; } else { assert Intrinsics . isEmpty ( keys [ index ] ) ; if ( assigned == resizeAt ) { allocateThenInsertThenRehash ( index , key ) ; } else { keys [ index ] = key ; } assigned ++ ; } }
Inserts a key for an index that is not present in the set . This method may help in avoiding double recalculation of the key s hash .
30,518
private static void topDownMergeSort ( int [ ] src , int [ ] dst , int fromIndex , int toIndex , IndirectComparator comp ) { if ( toIndex - fromIndex <= MIN_LENGTH_FOR_INSERTION_SORT ) { insertionSort ( fromIndex , toIndex - fromIndex , dst , comp ) ; return ; } final int mid = ( fromIndex + toIndex ) >>> 1 ; topDownMergeSort ( dst , src , fromIndex , mid , comp ) ; topDownMergeSort ( dst , src , mid , toIndex , comp ) ; if ( comp . compare ( src [ mid - 1 ] , src [ mid ] ) <= 0 ) { System . arraycopy ( src , fromIndex , dst , fromIndex , toIndex - fromIndex ) ; } else { for ( int i = fromIndex , j = mid , k = fromIndex ; k < toIndex ; k ++ ) { if ( j == toIndex || ( i < mid && comp . compare ( src [ i ] , src [ j ] ) <= 0 ) ) { dst [ k ] = src [ i ++ ] ; } else { dst [ k ] = src [ j ++ ] ; } } } }
Perform a recursive descending merge sort .
30,519
private static int [ ] createOrderArray ( final int start , final int length ) { final int [ ] order = new int [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { order [ i ] = start + i ; } return order ; }
Creates the initial order array .
30,520
public void add ( KType [ ] elements , int start , int length ) { assert length >= 0 : "Length must be >= 0" ; ensureBufferSpace ( length ) ; System . arraycopy ( elements , start , buffer , elementsCount , length ) ; elementsCount += length ; }
Add all elements from a range of given array to the list .
30,521
public int addAll ( KTypeContainer < ? extends KType > container ) { final int size = container . size ( ) ; ensureBufferSpace ( size ) ; for ( KTypeCursor < ? extends KType > cursor : container ) { add ( cursor . value ) ; } return size ; }
Adds all elements from another container .
30,522
public int addAll ( Iterable < ? extends KTypeCursor < ? extends KType > > iterable ) { int size = 0 ; for ( KTypeCursor < ? extends KType > cursor : iterable ) { add ( cursor . value ) ; size ++ ; } return size ; }
Adds all elements from another iterable .
30,523
public int addFirst ( Iterable < ? extends KTypeCursor < ? extends KType > > iterable ) { int size = 0 ; for ( KTypeCursor < ? extends KType > cursor : iterable ) { addFirst ( cursor . value ) ; size ++ ; } return size ; }
Inserts all elements from the given iterable to the front of this deque .
30,524
public int addLast ( KTypeContainer < ? extends KType > container ) { int size = container . size ( ) ; ensureBufferSpace ( size ) ; for ( KTypeCursor < ? extends KType > cursor : container ) { addLast ( cursor . value ) ; } return size ; }
Inserts all elements from the given container to the end of this deque .
30,525
public int addLast ( Iterable < ? extends KTypeCursor < ? extends KType > > iterable ) { int size = 0 ; for ( KTypeCursor < ? extends KType > cursor : iterable ) { addLast ( cursor . value ) ; size ++ ; } return size ; }
Inserts all elements from the given iterable to the end of this deque .
30,526
public static long pop_array ( long [ ] arr , int wordOffset , int numWords ) { long popCount = 0 ; for ( int i = wordOffset , end = wordOffset + numWords ; i < end ; ++ i ) { popCount += Long . bitCount ( arr [ i ] ) ; } return popCount ; }
Returns the number of set bits in an array of longs .
30,527
public static long pop_intersect ( long [ ] arr1 , long [ ] arr2 , int wordOffset , int numWords ) { long popCount = 0 ; for ( int i = wordOffset , end = wordOffset + numWords ; i < end ; ++ i ) { popCount += Long . bitCount ( arr1 [ i ] & arr2 [ i ] ) ; } return popCount ; }
Returns the popcount or cardinality of the two sets after an intersection . Neither array is modified .
30,528
public static int mix32 ( int k ) { k = ( k ^ ( k >>> 16 ) ) * 0x85ebca6b ; k = ( k ^ ( k >>> 13 ) ) * 0xc2b2ae35 ; return k ^ ( k >>> 16 ) ; }
MH3 s plain finalization step .
30,529
private void generate ( TemplateFile input , List < OutputFile > outputs , TemplateOptions templateOptions ) throws IOException { final String targetFileName = targetFileName ( templatesPath . relativize ( input . path ) . toString ( ) , templateOptions ) ; final OutputFile output = new OutputFile ( outputPath . resolve ( targetFileName ) . toAbsolutePath ( ) . normalize ( ) ) ; if ( incremental && Files . exists ( output . path ) && Files . getLastModifiedTime ( output . path ) . toMillis ( ) >= Files . getLastModifiedTime ( input . path ) . toMillis ( ) ) { output . upToDate = true ; outputs . add ( output ) ; return ; } String template = new String ( Files . readAllBytes ( input . path ) , StandardCharsets . UTF_8 ) ; timeVelocity . start ( ) ; template = filterVelocity ( input , template , templateOptions ) ; timeVelocity . stop ( ) ; if ( templateOptions . isIgnored ( ) ) { return ; } getLog ( ) . debug ( "Processing: " + input . getFileName ( ) + " => " + output . path ) ; try { timeIntrinsics . start ( ) ; template = filterIntrinsics ( template , templateOptions ) ; timeIntrinsics . stop ( ) ; timeComments . start ( ) ; template = filterComments ( template ) ; timeComments . stop ( ) ; timeTypeClassRefs . start ( ) ; template = filterTypeClassRefs ( template , templateOptions ) ; template = filterStaticTokens ( template , templateOptions ) ; timeTypeClassRefs . stop ( ) ; } catch ( RuntimeException e ) { getLog ( ) . error ( "Error processing: " + input . getFileName ( ) + " => " + output . path + ":\n\t" + e . getMessage ( ) ) ; throw e ; } Files . createDirectories ( output . path . getParent ( ) ) ; Files . write ( output . path , template . getBytes ( StandardCharsets . UTF_8 ) ) ; outputs . add ( output ) ; }
Apply templates .
30,530
private String filterVelocity ( TemplateFile f , String template , TemplateOptions options ) { final VelocityContext ctx = new VelocityContext ( ) ; ctx . put ( "TemplateOptions" , options ) ; ctx . put ( "true" , true ) ; ctx . put ( "templateOnly" , false ) ; ctx . put ( "false" , false ) ; StringWriter sw = new StringWriter ( ) ; velocity . evaluate ( ctx , sw , f . getFileName ( ) , template ) ; return sw . toString ( ) ; }
Apply velocity to the input .
30,531
private List < TemplateFile > collectTemplateFiles ( Path dir ) throws IOException { final List < TemplateFile > paths = new ArrayList < > ( ) ; for ( Path path : scanFilesMatching ( dir , "glob:**.java" ) ) { paths . add ( new TemplateFile ( path ) ) ; } return paths ; }
Collect all template files from this and subdirectories .
30,532
public static ToastCompat makeText ( Context context , CharSequence text , int duration ) { @ SuppressLint ( "ShowToast" ) Toast toast = Toast . makeText ( context , text , duration ) ; setContextCompat ( toast . getView ( ) , new SafeToastContext ( context , toast ) ) ; return new ToastCompat ( context , toast ) ; }
Make a standard toast that just contains a text view .
30,533
void switchTwoColumns ( int columnIndex , int columnToIndex ) { checkForInit ( ) ; int cellData = mColumnWidths [ columnToIndex ] ; mColumnWidths [ columnToIndex ] = mColumnWidths [ columnIndex ] ; mColumnWidths [ columnIndex ] = cellData ; }
Switch 2 items in array with columns data
30,534
void switchTwoRows ( int rowIndex , int rowToIndex ) { checkForInit ( ) ; int cellData = mRowHeights [ rowToIndex ] ; mRowHeights [ rowToIndex ] = mRowHeights [ rowIndex ] ; mRowHeights [ rowIndex ] = cellData ; }
Switch 2 items in array with rows data
30,535
void remove ( int row , int column ) { SparseArrayCompat < TObj > array = mData . get ( row ) ; if ( array != null ) { array . remove ( column ) ; } }
Remove item in row column position int the matrix
30,536
private void refreshViewHolders ( ) { if ( mAdapter != null ) { for ( ViewHolder holder : mViewHolders . getAll ( ) ) { if ( holder != null ) { refreshItemViewHolder ( holder , mState . isRowDragging ( ) , mState . isColumnDragging ( ) ) ; } } if ( mState . isColumnDragging ( ) ) { refreshAllColumnHeadersHolders ( ) ; refreshAllRowHeadersHolders ( ) ; } else { refreshAllRowHeadersHolders ( ) ; refreshAllColumnHeadersHolders ( ) ; } if ( mLeftTopViewHolder != null ) { refreshLeftTopHeaderViewHolder ( mLeftTopViewHolder ) ; mLeftTopViewHolder . getItemView ( ) . bringToFront ( ) ; } } }
Refresh all view holders
30,537
private void refreshHeaderColumnViewHolder ( ViewHolder holder ) { int left = getEmptySpace ( ) + mManager . getColumnsWidth ( 0 , Math . max ( 0 , holder . getColumnIndex ( ) ) ) ; if ( ! isRTL ( ) ) { left += mManager . getHeaderRowWidth ( ) ; } int top = mSettings . isHeaderFixed ( ) ? 0 : - mState . getScrollY ( ) ; View view = holder . getItemView ( ) ; int leftMargin = holder . getColumnIndex ( ) * mSettings . getCellMargin ( ) + mSettings . getCellMargin ( ) ; int topMargin = holder . getRowIndex ( ) * mSettings . getCellMargin ( ) + mSettings . getCellMargin ( ) ; if ( holder . isDragging ( ) && mDragAndDropPoints . getOffset ( ) . x > 0 ) { left = mState . getScrollX ( ) + mDragAndDropPoints . getOffset ( ) . x - view . getWidth ( ) / 2 ; view . bringToFront ( ) ; } if ( holder . isDragging ( ) ) { View leftShadow = mShadowHelper . getLeftShadow ( ) ; View rightShadow = mShadowHelper . getRightShadow ( ) ; if ( leftShadow != null ) { int shadowLeft = left - mState . getScrollX ( ) ; leftShadow . layout ( Math . max ( mManager . getHeaderRowWidth ( ) - mState . getScrollX ( ) , shadowLeft - SHADOW_THICK ) + leftMargin , 0 , shadowLeft + leftMargin , mSettings . getLayoutHeight ( ) ) ; leftShadow . bringToFront ( ) ; } if ( rightShadow != null ) { int shadowLeft = left + mManager . getColumnWidth ( holder . getColumnIndex ( ) ) - mState . getScrollX ( ) ; rightShadow . layout ( Math . max ( mManager . getHeaderRowWidth ( ) - mState . getScrollX ( ) , shadowLeft ) + leftMargin , 0 , shadowLeft + SHADOW_THICK + leftMargin , mSettings . getLayoutHeight ( ) ) ; rightShadow . bringToFront ( ) ; } } int viewPosLeft = left - mState . getScrollX ( ) + leftMargin ; int viewPosRight = viewPosLeft + mManager . getColumnWidth ( holder . getColumnIndex ( ) ) ; int viewPosTop = top + topMargin ; int viewPosBottom = viewPosTop + mManager . getHeaderColumnHeight ( ) ; view . layout ( viewPosLeft , viewPosTop , viewPosRight , viewPosBottom ) ; if ( mState . isRowDragging ( ) ) { view . bringToFront ( ) ; } if ( ! mState . isColumnDragging ( ) ) { View shadow = mShadowHelper . getColumnsHeadersShadow ( ) ; if ( shadow == null ) { shadow = mShadowHelper . addColumnsHeadersShadow ( this ) ; } shadow . layout ( mState . isRowDragging ( ) ? 0 : mSettings . isHeaderFixed ( ) ? 0 : - mState . getScrollX ( ) , top + mManager . getHeaderColumnHeight ( ) , mSettings . getLayoutWidth ( ) , top + mManager . getHeaderColumnHeight ( ) + SHADOW_HEADERS_THICK ) ; shadow . bringToFront ( ) ; } }
Refresh current column header view holder .
30,538
private void recycleViewHolders ( boolean isRecycleAll ) { if ( mAdapter == null ) { return ; } final List < Integer > headerKeysToRemove = new ArrayList < > ( ) ; for ( ViewHolder holder : mViewHolders . getAll ( ) ) { if ( holder != null && ! holder . isDragging ( ) ) { View view = holder . getItemView ( ) ; if ( isRecycleAll || ( view . getRight ( ) < 0 || view . getLeft ( ) > mSettings . getLayoutWidth ( ) || view . getBottom ( ) < 0 || view . getTop ( ) > mSettings . getLayoutHeight ( ) ) ) { mViewHolders . remove ( holder . getRowIndex ( ) , holder . getColumnIndex ( ) ) ; recycleViewHolder ( holder ) ; } } } if ( ! headerKeysToRemove . isEmpty ( ) ) { headerKeysToRemove . clear ( ) ; } for ( int count = mHeaderColumnViewHolders . size ( ) , i = 0 ; i < count ; i ++ ) { int key = mHeaderColumnViewHolders . keyAt ( i ) ; ViewHolder holder = mHeaderColumnViewHolders . get ( key ) ; if ( holder != null ) { View view = holder . getItemView ( ) ; if ( isRecycleAll || view . getRight ( ) < 0 || view . getLeft ( ) > mSettings . getLayoutWidth ( ) ) { headerKeysToRemove . add ( key ) ; recycleViewHolder ( holder ) ; } } } removeKeys ( headerKeysToRemove , mHeaderColumnViewHolders ) ; if ( ! headerKeysToRemove . isEmpty ( ) ) { headerKeysToRemove . clear ( ) ; } for ( int count = mHeaderRowViewHolders . size ( ) , i = 0 ; i < count ; i ++ ) { int key = mHeaderRowViewHolders . keyAt ( i ) ; ViewHolder holder = mHeaderRowViewHolders . get ( key ) ; if ( holder != null && ! holder . isDragging ( ) ) { View view = holder . getItemView ( ) ; if ( isRecycleAll || view . getBottom ( ) < 0 || view . getTop ( ) > mSettings . getLayoutHeight ( ) ) { headerKeysToRemove . add ( key ) ; recycleViewHolder ( holder ) ; } } } removeKeys ( headerKeysToRemove , mHeaderRowViewHolders ) ; }
Recycle view holders outside screen
30,539
private void removeKeys ( List < Integer > keysToRemove , SparseArrayCompat < ViewHolder > headers ) { for ( Integer key : keysToRemove ) { headers . remove ( key ) ; } }
Remove recycled viewholders from sparseArray
30,540
private void recycleViewHolder ( ViewHolder holder ) { mRecycler . pushRecycledView ( holder ) ; removeView ( holder . getItemView ( ) ) ; mAdapter . onViewHolderRecycled ( holder ) ; }
Recycle view holder and remove view from layout .
30,541
private void addViewHolders ( Rect filledArea ) { int leftColumn = mManager . getColumnByXWithShift ( filledArea . left , mSettings . getCellMargin ( ) ) ; int rightColumn = mManager . getColumnByXWithShift ( filledArea . right , mSettings . getCellMargin ( ) ) ; int topRow = mManager . getRowByYWithShift ( filledArea . top , mSettings . getCellMargin ( ) ) ; int bottomRow = mManager . getRowByYWithShift ( filledArea . bottom , mSettings . getCellMargin ( ) ) ; for ( int i = topRow ; i <= bottomRow ; i ++ ) { for ( int j = leftColumn ; j <= rightColumn ; j ++ ) { ViewHolder viewHolder = mViewHolders . get ( i , j ) ; if ( viewHolder == null && mAdapter != null ) { addViewHolder ( i , j , ViewHolderType . ITEM ) ; } } ViewHolder viewHolder = mHeaderRowViewHolders . get ( i ) ; if ( viewHolder == null && mAdapter != null ) { addViewHolder ( i , isRTL ( ) ? mManager . getColumnCount ( ) : 0 , ViewHolderType . ROW_HEADER ) ; } else if ( viewHolder != null && mAdapter != null ) { refreshHeaderRowViewHolder ( viewHolder ) ; } } for ( int i = leftColumn ; i <= rightColumn ; i ++ ) { ViewHolder viewHolder = mHeaderColumnViewHolders . get ( i ) ; if ( viewHolder == null && mAdapter != null ) { addViewHolder ( 0 , i , ViewHolderType . COLUMN_HEADER ) ; } else if ( viewHolder != null && mAdapter != null ) { refreshHeaderColumnViewHolder ( viewHolder ) ; } } if ( mLeftTopViewHolder == null && mAdapter != null ) { mLeftTopViewHolder = mAdapter . onCreateLeftTopHeaderViewHolder ( AdaptiveTableLayout . this ) ; mLeftTopViewHolder . setItemType ( ViewHolderType . FIRST_HEADER ) ; View view = mLeftTopViewHolder . getItemView ( ) ; view . setTag ( R . id . tag_view_holder , mLeftTopViewHolder ) ; addView ( view , 0 ) ; mAdapter . onBindLeftTopHeaderViewHolder ( mLeftTopViewHolder ) ; view . measure ( MeasureSpec . makeMeasureSpec ( mManager . getHeaderRowWidth ( ) , MeasureSpec . EXACTLY ) , MeasureSpec . makeMeasureSpec ( mManager . getHeaderColumnHeight ( ) , MeasureSpec . EXACTLY ) ) ; int viewPosLeft = mSettings . getCellMargin ( ) ; if ( isRTL ( ) ) { viewPosLeft += getRowHeaderStartX ( ) ; } int viewPosRight = viewPosLeft + mManager . getHeaderRowWidth ( ) ; int viewPosTop = mSettings . getCellMargin ( ) ; int viewPosBottom = viewPosTop + mManager . getHeaderColumnHeight ( ) ; view . layout ( viewPosLeft , viewPosTop , viewPosRight , viewPosBottom ) ; } else if ( mLeftTopViewHolder != null && mAdapter != null ) { refreshLeftTopHeaderViewHolder ( mLeftTopViewHolder ) ; } }
Create and add view holders with views to the layout .
30,542
private ViewHolder createViewHolder ( int itemType ) { if ( itemType == ViewHolderType . ITEM ) { return mAdapter . onCreateItemViewHolder ( AdaptiveTableLayout . this ) ; } else if ( itemType == ViewHolderType . ROW_HEADER ) { return mAdapter . onCreateRowHeaderViewHolder ( AdaptiveTableLayout . this ) ; } else if ( itemType == ViewHolderType . COLUMN_HEADER ) { return mAdapter . onCreateColumnHeaderViewHolder ( AdaptiveTableLayout . this ) ; } return null ; }
Create view holder by type
30,543
private void shiftColumnsViews ( final int fromColumn , final int toColumn ) { if ( mAdapter != null ) { mAdapter . changeColumns ( getBindColumn ( fromColumn ) , getBindColumn ( toColumn ) ) ; switchHeaders ( mHeaderColumnViewHolders , fromColumn , toColumn , ViewHolderType . COLUMN_HEADER ) ; mManager . switchTwoColumns ( fromColumn , toColumn ) ; Collection < ViewHolder > fromHolders = mViewHolders . getColumnItems ( fromColumn ) ; Collection < ViewHolder > toHolders = mViewHolders . getColumnItems ( toColumn ) ; removeViewHolders ( fromHolders ) ; removeViewHolders ( toHolders ) ; for ( ViewHolder holder : fromHolders ) { holder . setColumnIndex ( toColumn ) ; mViewHolders . put ( holder . getRowIndex ( ) , holder . getColumnIndex ( ) , holder ) ; } for ( ViewHolder holder : toHolders ) { holder . setColumnIndex ( fromColumn ) ; mViewHolders . put ( holder . getRowIndex ( ) , holder . getColumnIndex ( ) , holder ) ; } } }
Method change columns . Change view holders indexes kay in map init changing items in adapter .
30,544
private void shiftRowsViews ( final int fromRow , final int toRow ) { if ( mAdapter != null ) { mAdapter . changeRows ( fromRow , toRow , mSettings . isSolidRowHeader ( ) ) ; switchHeaders ( mHeaderRowViewHolders , fromRow , toRow , ViewHolderType . ROW_HEADER ) ; mManager . switchTwoRows ( fromRow , toRow ) ; Collection < ViewHolder > fromHolders = mViewHolders . getRowItems ( fromRow ) ; Collection < ViewHolder > toHolders = mViewHolders . getRowItems ( toRow ) ; removeViewHolders ( fromHolders ) ; removeViewHolders ( toHolders ) ; for ( ViewHolder holder : fromHolders ) { holder . setRowIndex ( toRow ) ; mViewHolders . put ( holder . getRowIndex ( ) , holder . getColumnIndex ( ) , holder ) ; } for ( ViewHolder holder : toHolders ) { holder . setRowIndex ( fromRow ) ; mViewHolders . put ( holder . getRowIndex ( ) , holder . getColumnIndex ( ) , holder ) ; } if ( ! mSettings . isSolidRowHeader ( ) ) { ViewHolder fromViewHolder = mHeaderRowViewHolders . get ( fromRow ) ; ViewHolder toViewHolder = mHeaderRowViewHolders . get ( toRow ) ; if ( fromViewHolder != null ) { mAdapter . onBindHeaderRowViewHolder ( fromViewHolder , fromRow ) ; } if ( toViewHolder != null ) { mAdapter . onBindHeaderRowViewHolder ( toViewHolder , toRow ) ; } } } }
Method change rows . Change view holders indexes kay in map init changing items in adapter .
30,545
@ SuppressWarnings ( "unused" ) private void setDraggingToColumn ( int column , boolean isDragging ) { Collection < ViewHolder > holders = mViewHolders . getColumnItems ( column ) ; for ( ViewHolder holder : holders ) { holder . setIsDragging ( isDragging ) ; } ViewHolder holder = mHeaderColumnViewHolders . get ( column ) ; if ( holder != null ) { holder . setIsDragging ( isDragging ) ; } }
Method set dragging flag to all view holders in the specific column
30,546
@ SuppressWarnings ( "unused" ) private void setDraggingToRow ( int row , boolean isDragging ) { Collection < ViewHolder > holders = mViewHolders . getRowItems ( row ) ; for ( ViewHolder holder : holders ) { holder . setIsDragging ( isDragging ) ; } ViewHolder holder = mHeaderRowViewHolders . get ( row ) ; if ( holder != null ) { holder . setIsDragging ( isDragging ) ; } }
Method set dragging flag to all view holders in the specific row
30,547
void switchTwoColumns ( int columnIndex , int columnToIndex ) { for ( int i = 0 ; i < getRowCount ( ) - 1 ; i ++ ) { Object cellData = getItems ( ) [ i ] [ columnToIndex ] ; getItems ( ) [ i ] [ columnToIndex ] = getItems ( ) [ i ] [ columnIndex ] ; getItems ( ) [ i ] [ columnIndex ] = cellData ; } }
Switch 2 columns with data
30,548
void switchTwoColumnHeaders ( int columnIndex , int columnToIndex ) { Object cellData = getColumnHeaders ( ) [ columnToIndex ] ; getColumnHeaders ( ) [ columnToIndex ] = getColumnHeaders ( ) [ columnIndex ] ; getColumnHeaders ( ) [ columnIndex ] = cellData ; }
Switch 2 columns headers with data
30,549
void switchTwoRows ( int rowIndex , int rowToIndex ) { for ( int i = 0 ; i < getItems ( ) . length ; i ++ ) { Object cellData = getItems ( ) [ rowToIndex ] [ i ] ; getItems ( ) [ rowToIndex ] [ i ] = getItems ( ) [ rowIndex ] [ i ] ; getItems ( ) [ rowIndex ] [ i ] = cellData ; } }
Switch 2 rows with data
30,550
void switchTwoRowHeaders ( int rowIndex , int rowToIndex ) { Object cellData = getRowHeaders ( ) [ rowToIndex ] ; getRowHeaders ( ) [ rowToIndex ] = getRowHeaders ( ) [ rowIndex ] ; getRowHeaders ( ) [ rowIndex ] = cellData ; }
Switch 2 rows headers with data
30,551
public static DB newEmbeddedDB ( DBConfiguration config ) throws ManagedProcessException { DB db = new DB ( config ) ; db . prepareDirectories ( ) ; db . unpackEmbeddedDb ( ) ; db . install ( ) ; return db ; }
This factory method is the mechanism for constructing a new embedded database for use . This method automatically installs the database and prepares it for use .
30,552
public static DB newEmbeddedDB ( int port ) throws ManagedProcessException { DBConfigurationBuilder config = new DBConfigurationBuilder ( ) ; config . setPort ( port ) ; return newEmbeddedDB ( config . build ( ) ) ; }
This factory method is the mechanism for constructing a new embedded database for use . This method automatically installs the database and prepares it for use with default configuration allowing only for specifying port .
30,553
synchronized protected void install ( ) throws ManagedProcessException { try { ManagedProcess mysqlInstallProcess = installPreparation ( ) ; mysqlInstallProcess . start ( ) ; mysqlInstallProcess . waitForExit ( ) ; } catch ( Exception e ) { throw new ManagedProcessException ( "An error occurred while installing the database" , e ) ; } logger . info ( "Installation complete." ) ; }
Installs the database to the location specified in the configuration .
30,554
public synchronized void start ( ) throws ManagedProcessException { logger . info ( "Starting up the database..." ) ; boolean ready = false ; try { mysqldProcess = startPreparation ( ) ; ready = mysqldProcess . startAndWaitForConsoleMessageMaxMs ( getReadyForConnectionsTag ( ) , dbStartMaxWaitInMS ) ; } catch ( Exception e ) { logger . error ( "failed to start mysqld" , e ) ; throw new ManagedProcessException ( "An error occurred while starting the database" , e ) ; } if ( ! ready ) { if ( mysqldProcess . isAlive ( ) ) mysqldProcess . destroy ( ) ; throw new ManagedProcessException ( "Database does not seem to have started up correctly? Magic string not seen in " + dbStartMaxWaitInMS + "ms: " + getReadyForConnectionsTag ( ) + mysqldProcess . getLastConsoleLines ( ) ) ; } logger . info ( "Database startup complete." ) ; }
Starts up the database using the data directory and port specified in the configuration .
30,555
public void source ( String resource , String username , String password , String dbName ) throws ManagedProcessException { InputStream from = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( resource ) ; if ( from == null ) throw new IllegalArgumentException ( "Could not find script file on the classpath at: " + resource ) ; run ( "script file sourced from the classpath at: " + resource , from , username , password , dbName ) ; }
Takes in a string that represents a resource on the classpath and sources it via the mysql command line tool .
30,556
public synchronized void stop ( ) throws ManagedProcessException { if ( mysqldProcess . isAlive ( ) ) { logger . debug ( "Stopping the database..." ) ; mysqldProcess . destroy ( ) ; logger . info ( "Database stopped." ) ; } else { logger . debug ( "Database was already stopped." ) ; } }
Stops the database .
30,557
protected void unpackEmbeddedDb ( ) { if ( configuration . getBinariesClassPathLocation ( ) == null ) { logger . info ( "Not unpacking any embedded database (as BinariesClassPathLocation configuration is null)" ) ; return ; } try { Util . extractFromClasspathToFile ( configuration . getBinariesClassPathLocation ( ) , baseDir ) ; if ( ! configuration . isWindows ( ) ) { Util . forceExecutable ( newExecutableFile ( "bin" , "my_print_defaults" ) ) ; Util . forceExecutable ( newExecutableFile ( "bin" , "mysql_install_db" ) ) ; Util . forceExecutable ( newExecutableFile ( "scripts" , "mysql_install_db" ) ) ; Util . forceExecutable ( newExecutableFile ( "bin" , "mysqld" ) ) ; Util . forceExecutable ( newExecutableFile ( "bin" , "mysqldump" ) ) ; Util . forceExecutable ( newExecutableFile ( "bin" , "mysql" ) ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Error unpacking embedded DB" , e ) ; } }
Based on the current OS unpacks the appropriate version of MariaDB to the file system based on the configuration .
30,558
protected void prepareDirectories ( ) throws ManagedProcessException { baseDir = Util . getDirectory ( configuration . getBaseDir ( ) ) ; libDir = Util . getDirectory ( configuration . getLibDir ( ) ) ; try { String dataDirPath = configuration . getDataDir ( ) ; if ( Util . isTemporaryDirectory ( dataDirPath ) ) { FileUtils . deleteDirectory ( new File ( dataDirPath ) ) ; } dataDir = Util . getDirectory ( dataDirPath ) ; } catch ( Exception e ) { throw new ManagedProcessException ( "An error occurred while preparing the data directory" , e ) ; } }
If the data directory specified in the configuration is a temporary directory this deletes any previous version . It also makes sure that the directory exists .
30,559
protected void cleanupOnExit ( ) { String threadName = "Shutdown Hook Deletion Thread for Temporary DB " + dataDir . toString ( ) ; final DB db = this ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( threadName ) { public void run ( ) { try { if ( mysqldProcess != null && mysqldProcess . isAlive ( ) ) { logger . info ( "cleanupOnExit() ShutdownHook now stopping database" ) ; db . stop ( ) ; } } catch ( ManagedProcessException e ) { logger . warn ( "cleanupOnExit() ShutdownHook: An error occurred while stopping the database" , e ) ; } if ( dataDir . exists ( ) && ( configuration . isDeletingTemporaryBaseAndDataDirsOnShutdown ( ) && Util . isTemporaryDirectory ( dataDir . getAbsolutePath ( ) ) ) ) { logger . info ( "cleanupOnExit() ShutdownHook quietly deleting temporary DB data directory: " + dataDir ) ; FileUtils . deleteQuietly ( dataDir ) ; } if ( baseDir . exists ( ) && ( configuration . isDeletingTemporaryBaseAndDataDirsOnShutdown ( ) && Util . isTemporaryDirectory ( dataDir . getAbsolutePath ( ) ) ) ) { logger . info ( "cleanupOnExit() ShutdownHook quietly deleting temporary DB base directory: " + baseDir ) ; FileUtils . deleteQuietly ( baseDir ) ; } } } ) ; }
Adds a shutdown hook to ensure that when the JVM exits the database is stopped and any temporary data directories are cleaned up .
30,560
public ManagedProcess dumpXML ( File outputFile , String dbName , String user , String password ) throws IOException , ManagedProcessException { return dump ( outputFile , Arrays . asList ( dbName ) , true , true , true , user , password ) ; }
unexpected deadlock ) .
30,561
public static int extractFromClasspathToFile ( String packagePath , File toDir ) throws IOException { String locationPattern = "classpath*:" + packagePath + "/**" ; ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver ( ) ; Resource [ ] resources = resourcePatternResolver . getResources ( locationPattern ) ; if ( resources . length == 0 ) { throw new IOException ( "Nothing found at " + locationPattern ) ; } int counter = 0 ; for ( Resource resource : resources ) { if ( resource . isReadable ( ) ) { final URL url = resource . getURL ( ) ; String path = url . toString ( ) ; if ( ! path . endsWith ( "/" ) ) { int p = path . lastIndexOf ( packagePath ) + packagePath . length ( ) ; path = path . substring ( p ) ; final File targetFile = new File ( toDir , path ) ; long len = resource . contentLength ( ) ; if ( ! targetFile . exists ( ) || targetFile . length ( ) != len ) { tryN ( 5 , 500 , new Procedure < IOException > ( ) { public void apply ( ) throws IOException { FileUtils . copyURLToFile ( url , targetFile ) ; } } ) ; counter ++ ; } } } } if ( counter > 0 ) { Object [ ] info = new Object [ ] { counter , locationPattern , toDir } ; logger . info ( "Unpacked {} files from {} to {}" , info ) ; } return counter ; }
Extract files from a package on the classpath into a directory .
30,562
private OkHttpConnector connector ( GitHubServerConfig config ) { OkHttpClient client = new OkHttpClient ( ) . setProxy ( getProxy ( defaultIfBlank ( config . getApiUrl ( ) , GITHUB_URL ) ) ) ; if ( config . getClientCacheSize ( ) > 0 ) { Cache cache = toCacheDir ( ) . apply ( config ) ; client . setCache ( cache ) ; } return new OkHttpConnector ( new OkUrlFactory ( client ) ) ; }
okHttp connector to be used as backend for GitHub client . Uses proxy of jenkins If cache size > 0 uses cache
30,563
public static < ITEM extends Item > Predicate < ITEM > isBuildable ( ) { return new Predicate < ITEM > ( ) { public boolean apply ( ITEM item ) { return item instanceof Job ? ( ( Job < ? , ? > ) item ) . isBuildable ( ) : item instanceof BuildableItem ; } } ; }
Can be useful to ignore disabled jobs on reregistering hooks
30,564
public static < ITEM extends Item > Predicate < ITEM > isAlive ( ) { return new Predicate < ITEM > ( ) { public boolean apply ( ITEM item ) { return ! from ( GHEventsSubscriber . all ( ) ) . filter ( isApplicableFor ( item ) ) . toList ( ) . isEmpty ( ) ; } } ; }
If any of event subscriber interested in hook for item then return true By default push hook subscriber is interested in job with gh - push - trigger
30,565
public static String asValidHref ( String urlString ) { try { return new URL ( urlString ) . toExternalForm ( ) ; } catch ( MalformedURLException e ) { LOG . debug ( "Malformed url - {}, empty string will be returned" , urlString ) ; return "" ; } }
Method to filter invalid url for XSS . This url can be inserted to href safely
30,566
public HttpResponse doAct ( StaplerRequest req ) throws IOException { if ( req . hasParameter ( "no" ) ) { disable ( true ) ; return HttpResponses . redirectViaContextPath ( "/manage" ) ; } else { return new HttpRedirect ( "." ) ; } }
Depending on whether the user said yes or no send them to the right place .
30,567
public void unregisterFor ( GitHubRepositoryName name , List < GitHubRepositoryName > aliveRepos ) { try { GHRepository repo = checkNotNull ( from ( name . resolve ( allowedToManageHooks ( ) ) ) . firstMatch ( withAdminAccess ( ) ) . orNull ( ) , "There are no credentials with admin access to manage hooks on %s" , name ) ; LOGGER . debug ( "Check {} for redundant hooks..." , repo ) ; Predicate < GHHook > predicate = aliveRepos . contains ( name ) ? serviceWebhookFor ( endpoint ) : or ( serviceWebhookFor ( endpoint ) , webhookFor ( endpoint ) ) ; from ( fetchHooks ( ) . apply ( repo ) ) . filter ( predicate ) . filter ( deleteWebhook ( ) ) . filter ( log ( "Deleted hook" ) ) . toList ( ) ; } catch ( Throwable t ) { LOGGER . warn ( "Failed to remove hook from {}" , name , t ) ; GitHubHookRegisterProblemMonitor . get ( ) . registerProblem ( name , t ) ; } }
Used to cleanup old hooks in case of removed or reconfigured trigger since JENKINS - 28138 this method permanently removes service hooks
30,568
public static BetterThanOrEqualBuildResult betterThanOrEqualTo ( Result result , GHCommitState state , String msg ) { BetterThanOrEqualBuildResult conditional = new BetterThanOrEqualBuildResult ( ) ; conditional . setResult ( result . toString ( ) ) ; conditional . setState ( state . name ( ) ) ; conditional . setMessage ( msg ) ; return conditional ; }
Convenient way to reuse logic of checking for the build status
30,569
public static BuildData calculateBuildData ( String parentName , String parentFullName , List < BuildData > buildDataList ) { if ( buildDataList == null ) { return null ; } if ( buildDataList . size ( ) == 1 ) { return buildDataList . get ( 0 ) ; } String projectName = parentFullName . replace ( parentName , "" ) ; if ( projectName . endsWith ( "/" ) ) { projectName = projectName . substring ( 0 , projectName . lastIndexOf ( '/' ) ) ; } for ( BuildData buildData : buildDataList ) { Set < String > remoteUrls = buildData . getRemoteUrls ( ) ; for ( String remoteUrl : remoteUrls ) { if ( remoteUrl . contains ( projectName ) ) { return buildData ; } } } return null ; }
Calculate build data from downstream builds that could be a shared library which is loaded first in a pipeline . For that reason this method compares all remote URLs for each build data with the real project name to determine the proper build data . This way the SHA returned in the build data will relate to the project
30,570
public Iterable < GitHub > findGithubConfig ( Predicate < GitHubServerConfig > match ) { Function < GitHubServerConfig , GitHub > loginFunction = loginToGithub ( ) ; if ( Objects . isNull ( loginFunction ) ) { return Collections . emptyList ( ) ; } return from ( getConfigs ( ) ) . filter ( match ) . transform ( loginFunction ) . filter ( Predicates . notNull ( ) ) ; }
Filters all stored configs against given predicate then logs in as the given user and returns the non null connection objects
30,571
public String commitId ( final String id ) { return new StringBuilder ( ) . append ( baseUrl ) . append ( "commit/" ) . append ( id ) . toString ( ) ; }
Returns the URL to a particular commit .
30,572
public String expandAll ( Run < ? , ? > run , TaskListener listener ) throws IOException , InterruptedException { if ( run instanceof AbstractBuild ) { try { return TokenMacro . expandAll ( ( AbstractBuild ) run , listener , content , false , Collections . < TokenMacro > emptyList ( ) ) ; } catch ( MacroEvaluationException e ) { LOGGER . error ( "Can't process token content {} in {} ({})" , content , run . getParent ( ) . getFullName ( ) , e . getMessage ( ) ) ; LOGGER . trace ( e . getMessage ( ) , e ) ; return content ; } } else { return run . getEnvironment ( listener ) . expand ( trimToEmpty ( content ) ) ; } }
Expands all env vars . In case of AbstractBuild also expands token macro and build vars
30,573
@ SuppressWarnings ( "deprecation" ) public String get ( Run < ? , ? > run , TaskListener listener ) { return DisplayURLProvider . get ( ) . getRunURL ( run ) ; }
Returns absolute URL of the Run
30,574
protected void onEvent ( GHEvent event , String payload ) { GHEventPayload . Ping ping ; try { ping = GitHub . offline ( ) . parseEventPayload ( new StringReader ( payload ) , GHEventPayload . Ping . class ) ; } catch ( IOException e ) { LOGGER . warn ( "Received malformed PingEvent: " + payload , e ) ; return ; } GHRepository repository = ping . getRepository ( ) ; if ( repository != null ) { LOGGER . info ( "{} webhook received from repo <{}>!" , event , repository . getHtmlUrl ( ) ) ; monitor . resolveProblem ( GitHubRepositoryName . create ( repository . getHtmlUrl ( ) . toExternalForm ( ) ) ) ; } else { GHOrganization organization = ping . getOrganization ( ) ; if ( organization != null ) { LOGGER . info ( "{} webhook received from org <{}>!" , event , organization . getUrl ( ) ) ; } else { LOGGER . warn ( "{} webhook received with unexpected payload" , event ) ; } } }
Logs repo on ping event
30,575
public static DirectoryStream . Filter < Path > notInCaches ( Set < String > caches ) { checkNotNull ( caches , "set of active caches can't be null" ) ; return new NotInCachesFilter ( caches ) ; }
To accept for cleaning only not active cache dirs
30,576
public static void clearRedundantCaches ( List < GitHubServerConfig > configs ) { Path baseCacheDir = getBaseCacheDir ( ) ; if ( notExists ( baseCacheDir ) ) { return ; } final Set < String > actualNames = from ( configs ) . filter ( withEnabledCache ( ) ) . transform ( toCacheDir ( ) ) . transform ( cacheToName ( ) ) . toSet ( ) ; try ( DirectoryStream < Path > caches = newDirectoryStream ( baseCacheDir , notInCaches ( actualNames ) ) ) { deleteEveryIn ( caches ) ; } catch ( IOException e ) { LOGGER . warn ( "Can't list cache dirs in {}" , baseCacheDir , e ) ; } }
Removes all not active dirs with old caches . This method is invoked after each save of global plugin config
30,577
private static void deleteEveryIn ( DirectoryStream < Path > caches ) { for ( Path notActualCache : caches ) { LOGGER . debug ( "Deleting redundant cache dir {}" , notActualCache ) ; try { FileUtils . deleteDirectory ( notActualCache . toFile ( ) ) ; } catch ( IOException e ) { LOGGER . error ( "Can't delete cache dir <{}>" , notActualCache , e ) ; } } }
Removes directories with caches
30,578
@ Initializer ( after = InitMilestone . EXTENSIONS_AUGMENTED , before = InitMilestone . JOB_LOADED ) public static void runMigrator ( ) throws Exception { new Migrator ( ) . migrate ( ) ; }
Launches migration after all extensions have been augmented as we need to ensure that the credentials plugin has been initialized . We need ensure that migrator will run after xstream aliases will be added .
30,579
protected Function < Credential , GitHubServerConfig > toGHServerConfig ( ) { return new Function < Credential , GitHubServerConfig > ( ) { public GitHubServerConfig apply ( Credential input ) { LOGGER . info ( "Migrate GitHub Plugin creds for {} {}" , input . getUsername ( ) , input . getApiUrl ( ) ) ; GitHubTokenCredentialsCreator creator = Jenkins . getInstance ( ) . getDescriptorByType ( GitHubTokenCredentialsCreator . class ) ; StandardCredentials credentials = creator . createCredentials ( input . getApiUrl ( ) , input . getOauthAccessToken ( ) , input . getUsername ( ) ) ; GitHubServerConfig gitHubServerConfig = new GitHubServerConfig ( credentials . getId ( ) ) ; gitHubServerConfig . setApiUrl ( input . getApiUrl ( ) ) ; return gitHubServerConfig ; } } ; }
Creates new string credentials from token
30,580
public void focus ( ) { requestFocus ( ) ; InputMethodManager inputMethodManager = ( InputMethodManager ) getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; inputMethodManager . showSoftInput ( this , 0 ) ; }
Request focus on this PinEntryEditText
30,581
public void openSettingsScreen ( ) { Intent intent = new Intent ( ) ; intent . setAction ( Settings . ACTION_APPLICATION_DETAILS_SETTINGS ) ; Uri uri = Uri . parse ( "package:" + context . getContext ( ) . getPackageName ( ) ) ; intent . setData ( uri ) ; context . startActivity ( intent ) ; }
open android settings screen for the specific package name
30,582
protected void requestPermission ( final PermissionModel model ) { new AlertDialog . Builder ( this ) . setTitle ( model . getTitle ( ) ) . setMessage ( model . getExplanationMessage ( ) ) . setPositiveButton ( "Request" , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { if ( model . getPermissionName ( ) . equalsIgnoreCase ( Manifest . permission . SYSTEM_ALERT_WINDOW ) ) { permissionHelper . requestSystemAlertPermission ( ) ; } else { permissionHelper . requestAfterExplanation ( model . getPermissionName ( ) ) ; } } } ) . show ( ) ; }
internal usage to show dialog with explanation you provided and a button to ask the user to request the permission
30,583
void performFlush ( ) { if ( ! shouldFlush ( ) ) { return ; } logger . verbose ( "Uploading payloads in queue to Segment." ) ; int payloadsUploaded = 0 ; Client . Connection connection = null ; try { connection = client . upload ( ) ; BatchPayloadWriter writer = new BatchPayloadWriter ( connection . os ) . beginObject ( ) . beginBatchArray ( ) ; PayloadWriter payloadWriter = new PayloadWriter ( writer , crypto ) ; payloadQueue . forEach ( payloadWriter ) ; writer . endBatchArray ( ) . endObject ( ) . close ( ) ; payloadsUploaded = payloadWriter . payloadCount ; connection . close ( ) ; } catch ( Client . HTTPException e ) { if ( e . is4xx ( ) && e . responseCode != 429 ) { logger . error ( e , "Payloads were rejected by server. Marked for removal." ) ; try { payloadQueue . remove ( payloadsUploaded ) ; } catch ( IOException e1 ) { logger . error ( e , "Unable to remove " + payloadsUploaded + " payload(s) from queue." ) ; } return ; } else { logger . error ( e , "Error while uploading payloads" ) ; return ; } } catch ( IOException e ) { logger . error ( e , "Error while uploading payloads" ) ; return ; } finally { closeQuietly ( connection ) ; } try { payloadQueue . remove ( payloadsUploaded ) ; } catch ( IOException e ) { logger . error ( e , "Unable to remove " + payloadsUploaded + " payload(s) from queue." ) ; return ; } logger . verbose ( "Uploaded %s payloads. %s remain in the queue." , payloadsUploaded , payloadQueue . size ( ) ) ; stats . dispatchFlush ( payloadsUploaded ) ; if ( payloadQueue . size ( ) > 0 ) { performFlush ( ) ; } }
Upload payloads to our servers and remove them from the queue file .
30,584
public Date timestamp ( ) { String timestamp = getString ( TIMESTAMP_KEY ) ; if ( isNullOrEmpty ( timestamp ) ) { return null ; } return parseISO8601Date ( timestamp ) ; }
Set a timestamp the event occurred .
30,585
static Traits create ( ) { Traits traits = new Traits ( new NullableConcurrentHashMap < String , Object > ( ) ) ; traits . putAnonymousId ( UUID . randomUUID ( ) . toString ( ) ) ; return traits ; }
Create a new Traits instance with an anonymous ID . Analytics client can be called on any thread so this instance is thread safe .
30,586
public ValueMap putValue ( String key , Object value ) { delegate . put ( key , value ) ; return this ; }
Helper method to be able to chain put methods .
30,587
public String event ( ) { String name = name ( ) ; if ( ! isNullOrEmpty ( name ) ) { return name ; } return category ( ) ; }
Either the name or category of the screen payload .
30,588
public Options setIntegration ( String integrationKey , boolean enabled ) { if ( SegmentIntegration . SEGMENT_KEY . equals ( integrationKey ) ) { throw new IllegalArgumentException ( "Segment integration cannot be enabled or disabled." ) ; } integrations . put ( integrationKey , enabled ) ; return this ; }
Sets whether an action will be sent to the target integration .
30,589
public Options setIntegrationOptions ( String integrationKey , Map < String , Object > options ) { integrations . put ( integrationKey , options ) ; return this ; }
Attach some integration specific options for this call .
30,590
public static < T > Set < T > newSet ( T ... values ) { Set < T > set = new HashSet < > ( values . length ) ; Collections . addAll ( set , values ) ; return set ; }
Creates a mutable HashSet instance containing the given elements in unspecified order
30,591
@ SuppressLint ( "HardwareIds" ) public static String getDeviceId ( Context context ) { String androidId = getString ( context . getContentResolver ( ) , ANDROID_ID ) ; if ( ! isNullOrEmpty ( androidId ) && ! "9774d56d682e549c" . equals ( androidId ) && ! "unknown" . equals ( androidId ) && ! "000000000000000" . equals ( androidId ) ) { return androidId ; } if ( ! isNullOrEmpty ( Build . SERIAL ) ) { return Build . SERIAL ; } if ( hasPermission ( context , READ_PHONE_STATE ) && hasFeature ( context , FEATURE_TELEPHONY ) ) { TelephonyManager telephonyManager = getSystemService ( context , TELEPHONY_SERVICE ) ; @ SuppressLint ( "MissingPermission" ) String telephonyId = telephonyManager . getDeviceId ( ) ; if ( ! isNullOrEmpty ( telephonyId ) ) { return telephonyId ; } } return UUID . randomUUID ( ) . toString ( ) ; }
Creates a unique device id . Suppresses HardwareIds lint warnings as we don t use this ID for identifying specific users . This is also what is required by the Segment spec .
30,592
public static SharedPreferences getSegmentSharedPreferences ( Context context , String tag ) { return context . getSharedPreferences ( "analytics-android-" + tag , MODE_PRIVATE ) ; }
Returns a shared preferences for storing any library preferences .
30,593
public static String getResourceString ( Context context , String key ) { int id = getIdentifier ( context , "string" , key ) ; if ( id != 0 ) { return context . getResources ( ) . getString ( id ) ; } else { return null ; } }
Get the string resource for the given key . Returns null if not found .
30,594
private static int getIdentifier ( Context context , String type , String key ) { return context . getResources ( ) . getIdentifier ( key , type , context . getPackageName ( ) ) ; }
Get the identifier for the resource with a given type and key .
30,595
public static void createDirectory ( File location ) throws IOException { if ( ! ( location . exists ( ) || location . mkdirs ( ) || location . isDirectory ( ) ) ) { throw new IOException ( "Could not create directory at " + location ) ; } }
Ensures that a directory is created in the given location throws an IOException otherwise .
30,596
public void screen ( String category , String name , Properties properties ) { if ( isNullOrEmpty ( category ) && isNullOrEmpty ( name ) ) { throw new IllegalArgumentException ( "either category or name must be provided." ) ; } if ( properties == null ) { properties = new Properties ( ) ; } dispatcher . dispatchPayload ( new WearPayload ( BasePayload . Type . screen , new WearScreenPayload ( category , name , properties ) ) ) ; }
The screen methods let your record whenever a user sees a screen of your mobile app and attach a name category or properties to the screen .
30,597
private static void listToWriter ( List < ? > list , JsonWriter writer ) throws IOException { writer . beginArray ( ) ; for ( Object value : list ) { writeValue ( value , writer ) ; } writer . endArray ( ) ; }
Print the json representation of a List to the given writer .
30,598
public void verbose ( String format , Object ... extra ) { if ( shouldLog ( VERBOSE ) ) { Log . v ( tag , String . format ( format , extra ) ) ; } }
Log a verbose message .
30,599
public void info ( String format , Object ... extra ) { if ( shouldLog ( INFO ) ) { Log . i ( tag , String . format ( format , extra ) ) ; } }
Log an info message .