idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
2,300
private synchronized void onJobFailure ( final JobStatusProto jobStatusProto ) { assert jobStatusProto . getState ( ) == ReefServiceProtos . State . FAILED ; final String id = this . jobId ; final Optional < byte [ ] > data = jobStatusProto . hasException ( ) ? Optional . of ( jobStatusProto . getException ( ) . toByteArray ( ) ) : Optional . < byte [ ] > empty ( ) ; final Optional < Throwable > cause = this . exceptionCodec . fromBytes ( data ) ; final String message ; if ( cause . isPresent ( ) && cause . get ( ) . getMessage ( ) != null ) { message = cause . get ( ) . getMessage ( ) ; } else { message = "No Message sent by the Job in exception " + cause . get ( ) ; LOG . log ( Level . WARNING , message , cause . get ( ) ) ; } final Optional < String > description = Optional . of ( message ) ; final FailedJob failedJob = new FailedJob ( id , message , description , cause , data ) ; this . failedJobEventHandler . onNext ( failedJob ) ; }
Inform the client of a failed job .
2,301
public synchronized Set < String > recoverEvaluators ( ) { final Set < String > expectedContainers = new HashSet < > ( ) ; try { if ( this . fileSystem == null || this . changeLogLocation == null ) { LOG . log ( Level . WARNING , "Unable to recover evaluators due to failure to instantiate FileSystem. Returning an" + " empty set." ) ; return expectedContainers ; } try ( final CloseableIterable < String > evaluatorLogIterable = readerWriter . readFromEvaluatorLog ( ) ) { for ( final String line : evaluatorLogIterable ) { if ( line . startsWith ( ADD_FLAG ) ) { final String containerId = line . substring ( ADD_FLAG . length ( ) ) ; if ( expectedContainers . contains ( containerId ) ) { LOG . log ( Level . WARNING , "Duplicated add container record found in the change log for container " + containerId ) ; } else { expectedContainers . add ( containerId ) ; } } else if ( line . startsWith ( REMOVE_FLAG ) ) { final String containerId = line . substring ( REMOVE_FLAG . length ( ) ) ; if ( ! expectedContainers . contains ( containerId ) ) { LOG . log ( Level . WARNING , "Change log includes record that try to remove non-exist or duplicate " + "remove record for container + " + containerId ) ; } expectedContainers . remove ( containerId ) ; } } } } catch ( final Exception e ) { final String errMsg = "Cannot read from log file with Exception " + e + ", evaluators will not be recovered." ; final String fatalMsg = "Cannot read from evaluator log." ; this . handleException ( e , errMsg , fatalMsg ) ; } return expectedContainers ; }
Recovers the set of evaluators that are alive .
2,302
public synchronized void recordAllocatedEvaluator ( final String id ) { if ( this . fileSystem != null && this . changeLogLocation != null ) { final String entry = ADD_FLAG + id + System . lineSeparator ( ) ; this . logContainerChange ( entry ) ; } }
Adds the allocated evaluator entry to the evaluator log .
2,303
public synchronized void recordRemovedEvaluator ( final String id ) { if ( this . fileSystem != null && this . changeLogLocation != null ) { final String entry = REMOVE_FLAG + id + System . lineSeparator ( ) ; this . logContainerChange ( entry ) ; } }
Adds the removed evaluator entry to the evaluator log .
2,304
public synchronized void close ( ) throws Exception { if ( this . readerWriter != null && ! this . writerClosed ) { this . readerWriter . close ( ) ; this . writerClosed = true ; } }
Closes the readerWriter which in turn closes the FileSystem .
2,305
private void onCleanExit ( final String processId ) { this . onResourceStatus ( ResourceStatusEventImpl . newBuilder ( ) . setIdentifier ( processId ) . setState ( State . DONE ) . setExitCode ( 0 ) . build ( ) ) ; }
Inform REEF of a cleanly exited process .
2,306
private void onUncleanExit ( final String processId , final int exitCode ) { this . onResourceStatus ( ResourceStatusEventImpl . newBuilder ( ) . setIdentifier ( processId ) . setState ( State . FAILED ) . setExitCode ( exitCode ) . build ( ) ) ; }
Inform REEF of an unclean process exit .
2,307
@ SuppressWarnings ( "checkstyle:illegalCatch" ) public Throwable dispatch ( final StopTime stopTime ) { try { for ( final EventHandler < StopTime > handler : stopHandlers ) { handler . onNext ( stopTime ) ; } return null ; } catch ( Throwable t ) { return t ; } }
We must implement this synchronously in order to catch exceptions and forward them back via the bridge before the server shuts down after this method returns .
2,308
public void launchTask ( final ExecutorDriver driver , final TaskInfo task ) { driver . sendStatusUpdate ( TaskStatus . newBuilder ( ) . setTaskId ( TaskID . newBuilder ( ) . setValue ( this . mesosExecutorId ) . build ( ) ) . setState ( TaskState . TASK_STARTING ) . setSlaveId ( task . getSlaveId ( ) ) . setMessage ( this . mesosRemoteManager . getMyIdentifier ( ) ) . build ( ) ) ; }
We assume a long - running Mesos Task that manages a REEF Evaluator process leveraging Mesos Executor s interface .
2,309
public static void main ( final String [ ] args ) throws Exception { final Injector injector = Tang . Factory . getTang ( ) . newInjector ( parseCommandLine ( args ) ) ; final REEFExecutor reefExecutor = injector . getInstance ( REEFExecutor . class ) ; reefExecutor . onStart ( ) ; }
The starting point of the executor .
2,310
void addTokensFromFile ( final UserGroupInformation ugi ) throws IOException { LOG . log ( Level . FINE , "Reading security tokens from file: {0}" , this . securityTokensFile ) ; try ( final FileInputStream stream = new FileInputStream ( securityTokensFile ) ) { final BinaryDecoder decoder = decoderFactory . binaryDecoder ( stream , null ) ; while ( ! decoder . isEnd ( ) ) { final SecurityToken token = tokenDatumReader . read ( null , decoder ) ; final Token < TokenIdentifier > yarnToken = new Token < > ( token . getKey ( ) . array ( ) , token . getPassword ( ) . array ( ) , new Text ( token . getKind ( ) . toString ( ) ) , new Text ( token . getService ( ) . toString ( ) ) ) ; LOG . log ( Level . FINE , "addToken for {0}" , yarnToken . getKind ( ) ) ; ugi . addToken ( yarnToken ) ; } } }
Read tokens from a file and add them to the user s credentials .
2,311
LocalResource makeLocalResourceForJarFile ( final Path path ) throws IOException { final LocalResource localResource = Records . newRecord ( LocalResource . class ) ; final FileStatus status = FileContext . getFileContext ( this . fileSystem . getUri ( ) ) . getFileStatus ( path ) ; localResource . setType ( LocalResourceType . ARCHIVE ) ; localResource . setVisibility ( LocalResourceVisibility . APPLICATION ) ; localResource . setResource ( ConverterUtils . getYarnUrlFromPath ( status . getPath ( ) ) ) ; localResource . setTimestamp ( status . getModificationTime ( ) ) ; localResource . setSize ( status . getLen ( ) ) ; return localResource ; }
Creates a LocalResource instance for the JAR file referenced by the given Path .
2,312
public static ArrayList < String > getFilteredLinesFromFile ( final String fileName , final String filter , final String removeBeforeToken , final String removeAfterToken ) throws IOException { final ArrayList < String > filteredLines = new ArrayList < > ( ) ; try ( final BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( fileName ) , StandardCharsets . UTF_8 ) ) ) { String line = "" ; while ( ( line = in . readLine ( ) ) != null ) { if ( line . trim ( ) . length ( ) == 0 ) { continue ; } if ( line . contains ( filter ) ) { String trimedLine ; if ( removeBeforeToken != null ) { final String [ ] p = line . split ( removeBeforeToken ) ; if ( p . length > 1 ) { trimedLine = p [ p . length - 1 ] ; } else { trimedLine = line . trim ( ) ; } } else { trimedLine = line . trim ( ) ; } if ( removeAfterToken != null ) { final String [ ] p = trimedLine . split ( removeAfterToken ) ; if ( p . length > 1 ) { trimedLine = p [ 0 ] ; } } filteredLines . add ( trimedLine ) ; } } } return filteredLines ; }
Get lines from a given file with a specified filter trim the line by removing strings before removeBeforeToken and after removeAfterToken .
2,313
public static ArrayList < String > getFilteredLinesFromFile ( final String fileName , final String filter ) throws IOException { return getFilteredLinesFromFile ( fileName , filter , null , null ) ; }
get lines from given file with specified filter .
2,314
public static ArrayList < String > findStages ( final ArrayList < String > lines , final String [ ] stageIndicators ) { final ArrayList < String > stages = new ArrayList < > ( ) ; int i = 0 ; for ( final String line : lines ) { if ( line . contains ( stageIndicators [ i ] ) ) { stages . add ( stageIndicators [ i ] ) ; if ( i < stageIndicators . length - 1 ) { i ++ ; } } } return stages ; }
find lines that contain stage indicators . The stageIndicators must be in sequence which appear in the lines .
2,315
public static void runHelloReefWithoutClient ( final Configuration runtimeConf ) throws InjectionException { final REEF reef = Tang . Factory . getTang ( ) . newInjector ( runtimeConf ) . getInstance ( REEF . class ) ; final Configuration driverConf = getDriverConfiguration ( ) ; reef . submit ( driverConf ) ; }
Used in the HDInsight example .
2,316
@ SuppressWarnings ( "checkstyle:hiddenfield" ) public void resourceOffers ( final SchedulerDriver driver , final List < Protos . Offer > offers ) { final Map < String , NodeDescriptorEventImpl . Builder > nodeDescriptorEvents = new HashMap < > ( ) ; for ( final Offer offer : offers ) { if ( nodeDescriptorEvents . get ( offer . getSlaveId ( ) . getValue ( ) ) == null ) { nodeDescriptorEvents . put ( offer . getSlaveId ( ) . getValue ( ) , NodeDescriptorEventImpl . newBuilder ( ) . setIdentifier ( offer . getSlaveId ( ) . getValue ( ) ) . setHostName ( offer . getHostname ( ) ) . setPort ( this . mesosSlavePort ) . setMemorySize ( getMemory ( offer ) ) ) ; } else { final NodeDescriptorEventImpl . Builder builder = nodeDescriptorEvents . get ( offer . getSlaveId ( ) . getValue ( ) ) ; builder . setMemorySize ( builder . build ( ) . getMemorySize ( ) + getMemory ( offer ) ) ; } this . offers . put ( offer . getId ( ) . getValue ( ) , offer ) ; } for ( final NodeDescriptorEventImpl . Builder ndpBuilder : nodeDescriptorEvents . values ( ) ) { this . reefEventHandlers . onNodeDescriptor ( ndpBuilder . build ( ) ) ; } if ( outstandingRequests . size ( ) > 0 ) { doResourceRequest ( outstandingRequests . remove ( ) ) ; } }
All offers in each batch of offers will be either be launched or declined .
2,317
public YarnSubmissionHelper addLocalResource ( final String resourceName , final LocalResource resource ) { resources . put ( resourceName , resource ) ; return this ; }
Add a file to be localized on the driver .
2,318
public YarnSubmissionHelper setPreserveEvaluators ( final boolean preserveEvaluators ) { if ( preserveEvaluators ) { if ( YarnTypes . isAtOrAfterVersion ( YarnTypes . MIN_VERSION_KEEP_CONTAINERS_AVAILABLE ) ) { LOG . log ( Level . FINE , "Hadoop version is {0} or after with KeepContainersAcrossApplicationAttempts supported," + " will set it to true." , YarnTypes . MIN_VERSION_KEEP_CONTAINERS_AVAILABLE ) ; applicationSubmissionContext . setKeepContainersAcrossApplicationAttempts ( true ) ; } else { LOG . log ( Level . WARNING , "Hadoop version does not yet support KeepContainersAcrossApplicationAttempts. Driver restarts " + "will not support recovering evaluators." ) ; applicationSubmissionContext . setKeepContainersAcrossApplicationAttempts ( false ) ; } } else { applicationSubmissionContext . setKeepContainersAcrossApplicationAttempts ( false ) ; } return this ; }
Set whether or not the resource manager should preserve evaluators across driver restarts .
2,319
public YarnSubmissionHelper setJobSubmissionEnvMap ( final Map < String , String > map ) { for ( final Map . Entry < String , String > entry : map . entrySet ( ) ) { environmentVariablesMap . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return this ; }
Sets environment variable map .
2,320
public YarnSubmissionHelper setJobSubmissionEnvVariable ( final String key , final String value ) { environmentVariablesMap . put ( key , value ) ; return this ; }
Adds a job submission environment variable .
2,321
public void onException ( final Throwable cause , final SocketAddress remoteAddress , final T message ) { if ( LOG . isLoggable ( Level . FINEST ) ) { LOG . log ( Level . FINEST , "Error sending message " + message + " to " + remoteAddress , cause ) ; } }
Called when the sent message to remoteAddress is failed to be transferred .
2,322
static YarnClusterSubmissionFromCS fromJobSubmissionParametersFile ( final File yarnClusterAppSubmissionParametersFile , final File yarnClusterJobSubmissionParametersFile ) throws IOException { try ( final FileInputStream appFileInputStream = new FileInputStream ( yarnClusterAppSubmissionParametersFile ) ) { try ( final FileInputStream jobFileInputStream = new FileInputStream ( yarnClusterJobSubmissionParametersFile ) ) { return readYarnClusterSubmissionFromCSFromInputStream ( appFileInputStream , jobFileInputStream ) ; } } }
Takes the YARN cluster job submission configuration file deserializes it and creates submission object .
2,323
public void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { int measuredWidth = MeasureSpec . getSize ( widthMeasureSpec ) ; int widthMode = MeasureSpec . getMode ( widthMeasureSpec ) ; int measuredHeight = MeasureSpec . getSize ( heightMeasureSpec ) ; int heightMode = MeasureSpec . getMode ( heightMeasureSpec ) ; int minDimension = Math . min ( measuredWidth , measuredHeight ) ; super . onMeasure ( MeasureSpec . makeMeasureSpec ( minDimension , widthMode ) , MeasureSpec . makeMeasureSpec ( minDimension , heightMode ) ) ; }
Measure the view to end up as a square based on the minimum of the height and width .
2,324
private void setItem ( int index , int value ) { if ( index == HOUR_INDEX ) { setValueForItem ( HOUR_INDEX , value ) ; int hourDegrees = ( value % 12 ) * HOUR_VALUE_TO_DEGREES_STEP_SIZE ; mHourRadialSelectorView . setSelection ( hourDegrees , isHourInnerCircle ( value ) , false ) ; mHourRadialSelectorView . invalidate ( ) ; } else if ( index == MINUTE_INDEX ) { setValueForItem ( MINUTE_INDEX , value ) ; int minuteDegrees = value * MINUTE_VALUE_TO_DEGREES_STEP_SIZE ; mMinuteRadialSelectorView . setSelection ( minuteDegrees , false , false ) ; mMinuteRadialSelectorView . invalidate ( ) ; } }
Set either the hour or the minute . Will set the internal value and set the selection .
2,325
public void setCurrentItemShowing ( int index , boolean animate ) { if ( index != HOUR_INDEX && index != MINUTE_INDEX ) { Log . e ( TAG , "TimePicker does not support view at index " + index ) ; return ; } int lastIndex = getCurrentItemShowing ( ) ; mCurrentItemShowing = index ; if ( animate && ( index != lastIndex ) ) { ObjectAnimator [ ] anims = new ObjectAnimator [ 4 ] ; if ( index == MINUTE_INDEX ) { anims [ 0 ] = mHourRadialTextsView . getDisappearAnimator ( ) ; anims [ 1 ] = mHourRadialSelectorView . getDisappearAnimator ( ) ; anims [ 2 ] = mMinuteRadialTextsView . getReappearAnimator ( ) ; anims [ 3 ] = mMinuteRadialSelectorView . getReappearAnimator ( ) ; } else if ( index == HOUR_INDEX ) { anims [ 0 ] = mHourRadialTextsView . getReappearAnimator ( ) ; anims [ 1 ] = mHourRadialSelectorView . getReappearAnimator ( ) ; anims [ 2 ] = mMinuteRadialTextsView . getDisappearAnimator ( ) ; anims [ 3 ] = mMinuteRadialSelectorView . getDisappearAnimator ( ) ; } if ( mTransition != null && mTransition . isRunning ( ) ) { mTransition . end ( ) ; } mTransition = new AnimatorSet ( ) ; mTransition . playTogether ( anims ) ; mTransition . start ( ) ; } else { int hourAlpha = ( index == HOUR_INDEX ) ? 255 : 0 ; int minuteAlpha = ( index == MINUTE_INDEX ) ? 255 : 0 ; mHourRadialTextsView . setAlpha ( hourAlpha ) ; mHourRadialSelectorView . setAlpha ( hourAlpha ) ; mMinuteRadialTextsView . setAlpha ( minuteAlpha ) ; mMinuteRadialSelectorView . setAlpha ( minuteAlpha ) ; } }
Set either minutes or hours as showing .
2,326
public final void attach ( T object , IAddon parent ) { if ( mObject != null || object == null || mParent != null || parent == null ) { throw new IllegalStateException ( ) ; } mParent = parent ; onAttach ( mObject = object ) ; }
Only for system usage don t call it!
2,327
public void setFocusedItem ( T item ) { final int itemId = getIdForItem ( item ) ; if ( itemId == INVALID_ID ) { return ; } performAction ( itemId , AccessibilityNodeInfoCompat . ACTION_ACCESSIBILITY_FOCUS , null ) ; }
Requests accessibility focus be placed on the specified item .
2,328
public void clearFocusedItem ( ) { final int itemId = mFocusedItemId ; if ( itemId == INVALID_ID ) { return ; } performAction ( itemId , AccessibilityNodeInfoCompat . ACTION_CLEAR_ACCESSIBILITY_FOCUS , null ) ; }
Clears the current accessibility focused item .
2,329
@ TargetApi ( Build . VERSION_CODES . ICE_CREAM_SANDWICH ) public boolean sendEventForItem ( T item , int eventType ) { if ( ! mManager . isEnabled ( ) || Build . VERSION . SDK_INT < Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { return false ; } final AccessibilityEvent event = getEventForItem ( item , eventType ) ; final ViewGroup group = ( ViewGroup ) mParentView . getParent ( ) ; return group . requestSendAccessibilityEvent ( mParentView , event ) ; }
Populates an event of the specified type with information about an item and attempts to send it up through the view hierarchy .
2,330
void drawDivider ( Canvas canvas , Rect bounds , int childIndex ) { final Drawable divider = getDivider ( ) ; divider . setBounds ( bounds ) ; divider . draw ( canvas ) ; }
O_O This method doesn t override super method but super class invoke it instead of android . widget . ListView . drawDivider . It s fucking magic of dalvik?
2,331
@ SuppressLint ( "InlinedApi" ) private static Object [ ] parseFontStyle ( Context context , AttributeSet attrs , int defStyleAttr ) { final TypedArray a = context . obtainStyledAttributes ( attrs , R . styleable . TextAppearance , defStyleAttr , 0 ) ; final Object [ ] result = parseFontStyle ( a ) ; a . recycle ( ) ; return result ; }
Looks ugly? Yea i know .
2,332
private void removeItemAtInt ( int index , boolean updateChildrenOnMenuViews ) { if ( ( index < 0 ) || ( index >= mItems . size ( ) ) ) { return ; } mItems . remove ( index ) ; if ( updateChildrenOnMenuViews ) { onItemsChanged ( true ) ; } }
Remove the item at the given index and optionally forces menu views to update .
2,333
public void updateMenuView ( boolean cleared ) { final ViewGroup parent = ( ViewGroup ) mMenuView ; if ( parent == null ) { return ; } int childIndex = 0 ; if ( mMenu != null ) { mMenu . flagActionItems ( ) ; ArrayList < MenuItemImpl > visibleItems = mMenu . getVisibleItems ( ) ; final int itemCount = visibleItems . size ( ) ; for ( int i = 0 ; i < itemCount ; i ++ ) { MenuItemImpl item = visibleItems . get ( i ) ; if ( shouldIncludeItem ( childIndex , item ) ) { final View convertView = parent . getChildAt ( childIndex ) ; final MenuItemImpl oldItem = convertView instanceof MenuView . ItemView ? ( ( MenuView . ItemView ) convertView ) . getItemData ( ) : null ; final View itemView = getItemView ( item , convertView , parent ) ; if ( item != oldItem ) { itemView . setPressed ( false ) ; } if ( itemView != convertView ) { addItemView ( itemView , childIndex ) ; } childIndex ++ ; } } } while ( childIndex < parent . getChildCount ( ) ) { if ( ! filterLeftoverView ( parent , childIndex ) ) { childIndex ++ ; } } }
Reuses item views when it can
2,334
private void updateProgressBars ( int value ) { ProgressBar circularProgressBar = getCircularProgressBar ( ) ; ProgressBar horizontalProgressBar = getHorizontalProgressBar ( ) ; if ( value == Window . PROGRESS_VISIBILITY_ON ) { if ( mFeatureProgress ) { int level = horizontalProgressBar . getProgress ( ) ; int visibility = ( horizontalProgressBar . isIndeterminate ( ) || level < 10000 ) ? View . VISIBLE : View . INVISIBLE ; horizontalProgressBar . setVisibility ( visibility ) ; } if ( mFeatureIndeterminateProgress ) { circularProgressBar . setVisibility ( View . VISIBLE ) ; } } else if ( value == Window . PROGRESS_VISIBILITY_OFF ) { if ( mFeatureProgress ) { horizontalProgressBar . setVisibility ( View . GONE ) ; } if ( mFeatureIndeterminateProgress ) { circularProgressBar . setVisibility ( View . GONE ) ; } } else if ( value == Window . PROGRESS_INDETERMINATE_ON ) { horizontalProgressBar . setIndeterminate ( true ) ; } else if ( value == Window . PROGRESS_INDETERMINATE_OFF ) { horizontalProgressBar . setIndeterminate ( false ) ; } else if ( Window . PROGRESS_START <= value && value <= Window . PROGRESS_END ) { horizontalProgressBar . setProgress ( value - Window . PROGRESS_START ) ; if ( value < Window . PROGRESS_END ) { showProgressBars ( horizontalProgressBar , circularProgressBar ) ; } else { hideProgressBars ( horizontalProgressBar , circularProgressBar ) ; } } }
Progress Bar function . Mostly extracted from PhoneWindow . java
2,335
public CalendarDay getDayFromLocation ( float x , float y ) { int dayStart = mPadding ; if ( x < dayStart || x > mWidth - mPadding ) { return null ; } int row = ( int ) ( y - MONTH_HEADER_SIZE ) / mRowHeight ; int column = ( int ) ( ( x - dayStart ) * mNumDays / ( mWidth - dayStart - mPadding ) ) ; int day = column - findDayOffset ( ) + 1 ; day += row * mNumDays ; if ( day < 1 || day > mNumCells ) { return null ; } return new CalendarDay ( mYear , mMonth , day ) ; }
Calculates the day that the given x position is in accounting for week number . Returns a Time referencing that day or null if
2,336
private Drawable getDrawable ( Uri uri ) { try { String scheme = uri . getScheme ( ) ; if ( ContentResolver . SCHEME_ANDROID_RESOURCE . equals ( scheme ) ) { try { return getDrawableFromResourceUri ( uri ) ; } catch ( Resources . NotFoundException ex ) { throw new FileNotFoundException ( "Resource does not exist: " + uri ) ; } } else { InputStream stream = mProviderContext . getContentResolver ( ) . openInputStream ( uri ) ; if ( stream == null ) { throw new FileNotFoundException ( "Failed to open " + uri ) ; } try { return Drawable . createFromStream ( stream , null ) ; } finally { try { stream . close ( ) ; } catch ( IOException ex ) { Log . e ( LOG_TAG , "Error closing icon stream for " + uri , ex ) ; } } } } catch ( FileNotFoundException fnfe ) { Log . w ( LOG_TAG , "Icon not found: " + uri + ", " + fnfe . getMessage ( ) ) ; return null ; } }
Gets a drawable by URI without using the cache .
2,337
private Drawable getDefaultIcon1 ( Cursor cursor ) { Drawable drawable = getActivityIconWithCache ( mSearchable . getSearchActivity ( ) ) ; if ( drawable != null ) { return drawable ; } return mContext . getPackageManager ( ) . getDefaultActivityIcon ( ) ; }
Gets the left - hand side icon that will be used for the current suggestion if the suggestion contains an icon column but no icon or a broken icon .
2,338
public ResolveInfo getDefaultActivity ( ) { synchronized ( mInstanceLock ) { ensureConsistentState ( ) ; if ( ! mActivities . isEmpty ( ) ) { return mActivities . get ( 0 ) . resolveInfo ; } } return null ; }
Gets the default activity The default activity is defined as the one with highest rank i . e . the first one in the list of activities that can handle the intent .
2,339
public void setDefaultActivity ( int index ) { synchronized ( mInstanceLock ) { ensureConsistentState ( ) ; ActivityResolveInfo newDefaultActivity = mActivities . get ( index ) ; ActivityResolveInfo oldDefaultActivity = mActivities . get ( 0 ) ; final float weight ; if ( oldDefaultActivity != null ) { weight = oldDefaultActivity . weight - newDefaultActivity . weight + DEFAULT_ACTIVITY_INFLATION ; } else { weight = DEFAULT_HISTORICAL_RECORD_WEIGHT ; } ComponentName defaultName = new ComponentName ( newDefaultActivity . resolveInfo . activityInfo . packageName , newDefaultActivity . resolveInfo . activityInfo . name ) ; HistoricalRecord historicalRecord = new HistoricalRecord ( defaultName , System . currentTimeMillis ( ) , weight ) ; addHisoricalRecord ( historicalRecord ) ; } }
Sets the default activity . The default activity is set by adding a historical record with weight high enough that this activity will become the highest ranked . Such a strategy guarantees that the default will eventually change if not used . Also the weight of the record for setting a default is inflated with a constant amount to guarantee that it will stay as default for awhile .
2,340
public void setActivitySorter ( ActivitySorter activitySorter ) { synchronized ( mInstanceLock ) { if ( mActivitySorter == activitySorter ) { return ; } mActivitySorter = activitySorter ; if ( sortActivitiesIfNeeded ( ) ) { notifyChanged ( ) ; } } }
Sets the sorter for ordering activities based on historical data and an intent .
2,341
private boolean sortActivitiesIfNeeded ( ) { if ( mActivitySorter != null && mIntent != null && ! mActivities . isEmpty ( ) && ! mHistoricalRecords . isEmpty ( ) ) { mActivitySorter . sort ( mIntent , mActivities , Collections . unmodifiableList ( mHistoricalRecords ) ) ; return true ; } return false ; }
Sorts the activities if necessary which is if there is a sorter there are some activities to sort and there is some historical data .
2,342
private boolean loadActivitiesIfNeeded ( ) { if ( mReloadActivities && mIntent != null ) { mReloadActivities = false ; mActivities . clear ( ) ; List < ResolveInfo > resolveInfos = mContext . getPackageManager ( ) . queryIntentActivities ( mIntent , 0 ) ; final int resolveInfoCount = resolveInfos . size ( ) ; for ( int i = 0 ; i < resolveInfoCount ; i ++ ) { ResolveInfo resolveInfo = resolveInfos . get ( i ) ; mActivities . add ( new ActivityResolveInfo ( resolveInfo ) ) ; } return true ; } return false ; }
Loads the activities for the current intent if needed which is if they are not already loaded for the current intent .
2,343
private boolean readHistoricalDataIfNeeded ( ) { if ( mCanReadHistoricalData && mHistoricalRecordsChanged && ! TextUtils . isEmpty ( mHistoryFileName ) ) { mCanReadHistoricalData = false ; mReadShareHistoryCalled = true ; readHistoricalDataImpl ( ) ; return true ; } return false ; }
Reads the historical data if necessary which is it has changed there is a history file and there is not persist in progress .
2,344
private void pruneExcessiveHistoricalRecordsIfNeeded ( ) { final int pruneCount = mHistoricalRecords . size ( ) - mHistoryMaxSize ; if ( pruneCount <= 0 ) { return ; } mHistoricalRecordsChanged = true ; for ( int i = 0 ; i < pruneCount ; i ++ ) { HistoricalRecord prunedRecord = mHistoricalRecords . remove ( 0 ) ; if ( DEBUG ) { Log . i ( LOG_TAG , "Pruned: " + prunedRecord ) ; } } }
Prunes older excessive records to guarantee maxHistorySize .
2,345
private void readHistoricalDataImpl ( ) { FileInputStream fis = null ; try { fis = mContext . openFileInput ( mHistoryFileName ) ; } catch ( FileNotFoundException fnfe ) { if ( DEBUG ) { Log . i ( LOG_TAG , "Could not open historical records file: " + mHistoryFileName ) ; } return ; } try { XmlPullParser parser = Xml . newPullParser ( ) ; parser . setInput ( fis , null ) ; int type = XmlPullParser . START_DOCUMENT ; while ( type != XmlPullParser . END_DOCUMENT && type != XmlPullParser . START_TAG ) { type = parser . next ( ) ; } if ( ! TAG_HISTORICAL_RECORDS . equals ( parser . getName ( ) ) ) { throw new XmlPullParserException ( "Share records file does not start with " + TAG_HISTORICAL_RECORDS + " tag." ) ; } List < HistoricalRecord > historicalRecords = mHistoricalRecords ; historicalRecords . clear ( ) ; while ( true ) { type = parser . next ( ) ; if ( type == XmlPullParser . END_DOCUMENT ) { break ; } if ( type == XmlPullParser . END_TAG || type == XmlPullParser . TEXT ) { continue ; } String nodeName = parser . getName ( ) ; if ( ! TAG_HISTORICAL_RECORD . equals ( nodeName ) ) { throw new XmlPullParserException ( "Share records file not well-formed." ) ; } String activity = parser . getAttributeValue ( null , ATTRIBUTE_ACTIVITY ) ; final long time = Long . parseLong ( parser . getAttributeValue ( null , ATTRIBUTE_TIME ) ) ; final float weight = Float . parseFloat ( parser . getAttributeValue ( null , ATTRIBUTE_WEIGHT ) ) ; HistoricalRecord readRecord = new HistoricalRecord ( activity , time , weight ) ; historicalRecords . add ( readRecord ) ; if ( DEBUG ) { Log . i ( LOG_TAG , "Read " + readRecord . toString ( ) ) ; } } if ( DEBUG ) { Log . i ( LOG_TAG , "Read " + historicalRecords . size ( ) + " historical records." ) ; } } catch ( XmlPullParserException xppe ) { Log . e ( LOG_TAG , "Error reading historical recrod file: " + mHistoryFileName , xppe ) ; } catch ( IOException ioe ) { Log . e ( LOG_TAG , "Error reading historical recrod file: " + mHistoryFileName , ioe ) ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException ioe ) { } } } }
Command for reading the historical records from a file off the UI thread .
2,346
public static void applyTheme ( Activity activity , boolean force ) { if ( force || ThemeManager . hasSpecifiedTheme ( activity ) ) { activity . setTheme ( ThemeManager . getTheme ( activity ) ) ; } }
Apply theme from intent . Only system use don t call it!
2,347
public static void cloneTheme ( Intent sourceIntent , Intent intent , boolean force ) { final boolean hasSourceTheme = hasSpecifiedTheme ( sourceIntent ) ; if ( force || hasSourceTheme ) { intent . putExtra ( _THEME_TAG , hasSourceTheme ? getTheme ( sourceIntent ) : _DEFAULT_THEME ) ; } }
Clone theme from sourceIntent to intent if it specified for sourceIntent or set flag force
2,348
public static void setDefaultTheme ( int theme ) { ThemeManager . _DEFAULT_THEME = theme ; if ( theme < _START_RESOURCES_ID ) { ThemeManager . _DEFAULT_THEME &= ThemeManager . _THEME_MASK ; } }
Set default theme . May be theme resource instead flags but it not recommend .
2,349
public static int getTheme ( Intent intent , boolean applyModifier ) { return prepareFlags ( intent . getIntExtra ( ThemeManager . _THEME_TAG , ThemeManager . _DEFAULT_THEME ) , applyModifier ) ; }
Extract theme flags from intent
2,350
public static int getThemeResource ( int themeTag , boolean applyModifier ) { if ( themeTag >= _START_RESOURCES_ID ) { return themeTag ; } themeTag = prepareFlags ( themeTag , applyModifier ) ; if ( ThemeManager . sThemeGetters != null ) { int getterResource ; final ThemeTag tag = new ThemeTag ( themeTag ) ; for ( int i = ThemeManager . sThemeGetters . size ( ) - 1 ; i >= 0 ; i -- ) { getterResource = ThemeManager . sThemeGetters . get ( i ) . getThemeResource ( tag ) ; if ( getterResource != 0 ) { return getterResource ; } } } final int i = _THEMES_MAP . get ( themeTag , - 1 ) ; if ( i == - 1 ) { return _THEMES_MAP . get ( _DEFAULT_THEME , R . style . Holo_Theme ) ; } else { return i ; } }
Resolve theme resource id by flags
2,351
public static void modifyDefaultThemeClear ( int mod ) { mod &= ThemeManager . _THEME_MASK ; ThemeManager . _DEFAULT_THEME |= mod ; ThemeManager . _DEFAULT_THEME ^= mod ; }
Clear modifier from default theme
2,352
public static void reset ( ) { if ( ( _DEFAULT_THEME & COLOR_SCHEME_MASK ) == 0 ) { _DEFAULT_THEME = DARK ; } _THEME_MODIFIER = 0 ; _THEMES_MAP . clear ( ) ; map ( DARK , Holo_Theme ) ; map ( DARK | FULLSCREEN , Holo_Theme_Fullscreen ) ; map ( DARK | NO_ACTION_BAR , Holo_Theme_NoActionBar ) ; map ( DARK | NO_ACTION_BAR | FULLSCREEN , Holo_Theme_NoActionBar_Fullscreen ) ; map ( DARK | DIALOG , Holo_Theme_Dialog ) ; map ( DARK | DIALOG_WHEN_LARGE , Holo_Theme_DialogWhenLarge ) ; map ( DARK | DIALOG_WHEN_LARGE | NO_ACTION_BAR , Holo_Theme_DialogWhenLarge_NoActionBar ) ; map ( DARK | ALERT_DIALOG , Holo_Theme_Dialog_Alert ) ; map ( DARK | WALLPAPER , Holo_Theme_Wallpaper ) ; map ( DARK | NO_ACTION_BAR | WALLPAPER , Holo_Theme_NoActionBar_Wallpaper ) ; map ( DARK | FULLSCREEN | WALLPAPER , Holo_Theme_Fullscreen_Wallpaper ) ; map ( DARK | NO_ACTION_BAR | FULLSCREEN | WALLPAPER , Holo_Theme_NoActionBar_Fullscreen_Wallpaper ) ; map ( LIGHT , Holo_Theme_Light ) ; map ( LIGHT | FULLSCREEN , Holo_Theme_Light_Fullscreen ) ; map ( LIGHT | NO_ACTION_BAR , Holo_Theme_Light_NoActionBar ) ; map ( LIGHT | NO_ACTION_BAR | FULLSCREEN , Holo_Theme_Light_NoActionBar_Fullscreen ) ; map ( LIGHT | DIALOG , Holo_Theme_Dialog_Light ) ; map ( LIGHT | DIALOG_WHEN_LARGE , Holo_Theme_DialogWhenLarge_Light ) ; map ( LIGHT | DIALOG_WHEN_LARGE | NO_ACTION_BAR , Holo_Theme_DialogWhenLarge_Light_NoActionBar ) ; map ( LIGHT | ALERT_DIALOG , Holo_Theme_Dialog_Alert_Light ) ; map ( LIGHT | WALLPAPER , Holo_Theme_Light_Wallpaper ) ; map ( LIGHT | NO_ACTION_BAR | WALLPAPER , Holo_Theme_Light_NoActionBar_Wallpaper ) ; map ( LIGHT | FULLSCREEN | WALLPAPER , Holo_Theme_Light_Fullscreen_Wallpaper ) ; map ( LIGHT | NO_ACTION_BAR | FULLSCREEN | WALLPAPER , Holo_Theme_Light_NoActionBar_Fullscreen_Wallpaper ) ; map ( MIXED , Holo_Theme_Light_DarkActionBar ) ; map ( MIXED | FULLSCREEN , Holo_Theme_Light_DarkActionBar_Fullscreen ) ; map ( MIXED | NO_ACTION_BAR , Holo_Theme_Light_DarkActionBar_NoActionBar ) ; map ( MIXED | NO_ACTION_BAR | FULLSCREEN , Holo_Theme_Light_DarkActionBar_NoActionBar_Fullscreen ) ; map ( MIXED | DIALOG , Holo_Theme_Dialog_Light ) ; map ( MIXED | DIALOG_WHEN_LARGE , Holo_Theme_DialogWhenLarge_Light_DarkActionBar ) ; map ( MIXED | DIALOG_WHEN_LARGE | NO_ACTION_BAR , Holo_Theme_DialogWhenLarge_Light_DarkActionBar_NoActionBar ) ; map ( MIXED | ALERT_DIALOG , Holo_Theme_Dialog_Alert_Light ) ; map ( MIXED | WALLPAPER , Holo_Theme_Light_DarkActionBar_Wallpaper ) ; map ( MIXED | NO_ACTION_BAR | WALLPAPER , Holo_Theme_Light_DarkActionBar_NoActionBar_Wallpaper ) ; map ( MIXED | FULLSCREEN | WALLPAPER , Holo_Theme_Light_DarkActionBar_Fullscreen_Wallpaper ) ; map ( MIXED | NO_ACTION_BAR | FULLSCREEN | WALLPAPER , Holo_Theme_Light_DarkActionBar_NoActionBar_Fullscreen_Wallpaper ) ; if ( sThemeSetters != null ) { for ( ThemeSetter setter : sThemeSetters ) { setter . setupThemes ( ) ; } } }
Reset all themes to default
2,353
public boolean onSupportNavigateUp ( ) { Intent upIntent = getSupportParentActivityIntent ( ) ; if ( upIntent != null ) { if ( supportShouldUpRecreateTask ( upIntent ) ) { TaskStackBuilder b = TaskStackBuilder . create ( this ) ; onCreateSupportNavigateUpTaskStack ( b ) ; onPrepareSupportNavigateUpTaskStack ( b ) ; b . startActivities ( ) ; try { ActivityCompat . finishAffinity ( this ) ; } catch ( IllegalStateException e ) { finish ( ) ; } } else { supportNavigateUpTo ( upIntent ) ; } return true ; } return false ; }
This method is called whenever the user chooses to navigate Up within your application s activity hierarchy from the action bar .
2,354
private void updateSearchAutoComplete ( ) { mQueryTextView . setThreshold ( mSearchable . getSuggestThreshold ( ) ) ; mQueryTextView . setImeOptions ( mSearchable . getImeOptions ( ) ) ; int inputType = mSearchable . getInputType ( ) ; if ( ( inputType & InputType . TYPE_MASK_CLASS ) == InputType . TYPE_CLASS_TEXT ) { inputType &= ~ InputType . TYPE_TEXT_FLAG_AUTO_COMPLETE ; if ( mSearchable . getSuggestAuthority ( ) != null ) { inputType |= InputType . TYPE_TEXT_FLAG_AUTO_COMPLETE ; inputType |= InputType . TYPE_TEXT_FLAG_NO_SUGGESTIONS ; } } mQueryTextView . setInputType ( inputType ) ; if ( mSuggestionsAdapter != null ) { mSuggestionsAdapter . changeCursor ( null ) ; } if ( mSearchable . getSuggestAuthority ( ) != null ) { mSuggestionsAdapter = new SuggestionsAdapter ( getContext ( ) , this , mSearchable , mOutsideDrawablesCache ) ; mQueryTextView . setAdapter ( mSuggestionsAdapter ) ; ( ( SuggestionsAdapter ) mSuggestionsAdapter ) . setQueryRefinement ( mQueryRefinement ? SuggestionsAdapter . REFINE_ALL : SuggestionsAdapter . REFINE_BY_ENTRY ) ; } }
Updates the auto - complete text view .
2,355
private void setQuery ( CharSequence query ) { mQueryTextView . setText ( query ) ; mQueryTextView . setSelection ( TextUtils . isEmpty ( query ) ? 0 : query . length ( ) ) ; }
Sets the text in the query box without updating the suggestions .
2,356
private void parseMenu ( XmlPullParser parser , AttributeSet attrs , Menu menu ) throws XmlPullParserException , IOException { MenuState menuState = new MenuState ( menu ) ; int eventType = parser . getEventType ( ) ; String tagName ; boolean lookingForEndOfUnknownTag = false ; String unknownTagName = null ; do { if ( eventType == XmlPullParser . START_TAG ) { tagName = parser . getName ( ) ; if ( tagName . equals ( XML_MENU ) ) { eventType = parser . next ( ) ; break ; } throw new RuntimeException ( "Expecting menu, got " + tagName ) ; } eventType = parser . next ( ) ; } while ( eventType != XmlPullParser . END_DOCUMENT ) ; boolean reachedEndOfMenu = false ; while ( ! reachedEndOfMenu ) { switch ( eventType ) { case XmlPullParser . START_TAG : if ( lookingForEndOfUnknownTag ) { break ; } tagName = parser . getName ( ) ; if ( tagName . equals ( XML_GROUP ) ) { menuState . readGroup ( attrs ) ; } else if ( tagName . equals ( XML_ITEM ) ) { menuState . readItem ( attrs ) ; } else if ( tagName . equals ( XML_MENU ) ) { SubMenu subMenu = menuState . addSubMenuItem ( ) ; parseMenu ( parser , attrs , subMenu ) ; } else { lookingForEndOfUnknownTag = true ; unknownTagName = tagName ; } break ; case XmlPullParser . END_TAG : tagName = parser . getName ( ) ; if ( lookingForEndOfUnknownTag && tagName . equals ( unknownTagName ) ) { lookingForEndOfUnknownTag = false ; unknownTagName = null ; } else if ( tagName . equals ( XML_GROUP ) ) { menuState . resetGroup ( ) ; } else if ( tagName . equals ( XML_ITEM ) ) { if ( ! menuState . hasAddedItem ( ) ) { if ( menuState . itemActionProvider != null && menuState . itemActionProvider . hasSubMenu ( ) ) { menuState . addSubMenuItem ( ) ; } else { menuState . addItem ( ) ; } } } else if ( tagName . equals ( XML_MENU ) ) { reachedEndOfMenu = true ; } break ; case XmlPullParser . END_DOCUMENT : throw new RuntimeException ( "Unexpected end of document" ) ; } eventType = parser . next ( ) ; } }
Called internally to fill the given menu . If a sub menu is seen it will call this recursively .
2,357
private void tryStartingKbMode ( int keyCode ) { if ( mTimePicker . trySettingInputEnabled ( false ) && ( keyCode == - 1 || addKeyIfLegal ( keyCode ) ) ) { mInKbMode = true ; mDoneButton . setEnabled ( false ) ; updateDisplay ( false ) ; } }
Try to start keyboard mode with the specified key as long as the timepicker is not in the middle of a touch - event .
2,358
private void finishKbMode ( boolean updateDisplays ) { mInKbMode = false ; if ( ! mTypedTimes . isEmpty ( ) ) { int values [ ] = getEnteredTime ( null ) ; mTimePicker . setTime ( values [ 0 ] , values [ 1 ] ) ; if ( ! mIs24HourMode ) { mTimePicker . setAmOrPm ( values [ 2 ] ) ; } mTypedTimes . clear ( ) ; } if ( updateDisplays ) { updateDisplay ( false ) ; mTimePicker . trySettingInputEnabled ( true ) ; } }
Get out of keyboard mode . If there is nothing in typedTimes revert to TimePicker s time .
2,359
private int [ ] getEnteredTime ( Boolean [ ] enteredZeros ) { int amOrPm = - 1 ; int startIndex = 1 ; if ( ! mIs24HourMode && isTypedTimeFullyLegal ( ) ) { int keyCode = mTypedTimes . get ( mTypedTimes . size ( ) - 1 ) ; if ( keyCode == getAmOrPmKeyCode ( AM ) ) { amOrPm = AM ; } else if ( keyCode == getAmOrPmKeyCode ( PM ) ) { amOrPm = PM ; } startIndex = 2 ; } int minute = - 1 ; int hour = - 1 ; for ( int i = startIndex ; i <= mTypedTimes . size ( ) ; i ++ ) { int val = getValFromKeyCode ( mTypedTimes . get ( mTypedTimes . size ( ) - i ) ) ; if ( i == startIndex ) { minute = val ; } else if ( i == startIndex + 1 ) { minute += 10 * val ; if ( enteredZeros != null && val == 0 ) { enteredZeros [ 1 ] = true ; } } else if ( i == startIndex + 2 ) { hour = val ; } else if ( i == startIndex + 3 ) { hour += 10 * val ; if ( enteredZeros != null && val == 0 ) { enteredZeros [ 0 ] = true ; } } } int [ ] ret = { hour , minute , amOrPm } ; return ret ; }
Get the currently - entered time as integer values of the hours and minutes typed .
2,360
private int getAmOrPmKeyCode ( int amOrPm ) { if ( mAmKeyCode == - 1 || mPmKeyCode == - 1 ) { KeyCharacterMap kcm = KeyCharacterMap . load ( KeyCharacterMap . VIRTUAL_KEYBOARD ) ; char amChar ; char pmChar ; for ( int i = 0 ; i < Math . max ( mAmText . length ( ) , mPmText . length ( ) ) ; i ++ ) { amChar = mAmText . toLowerCase ( Locale . getDefault ( ) ) . charAt ( i ) ; pmChar = mPmText . toLowerCase ( Locale . getDefault ( ) ) . charAt ( i ) ; if ( amChar != pmChar ) { KeyEvent [ ] events = kcm . getEvents ( new char [ ] { amChar , pmChar } ) ; if ( events != null && events . length == 4 ) { mAmKeyCode = events [ 0 ] . getKeyCode ( ) ; mPmKeyCode = events [ 2 ] . getKeyCode ( ) ; } else { Log . e ( TAG , "Unable to find keycodes for AM and PM." ) ; } break ; } } } if ( amOrPm == AM ) { return mAmKeyCode ; } else if ( amOrPm == PM ) { return mPmKeyCode ; } return - 1 ; }
Get the keycode value for AM and PM in the current language .
2,361
public void show ( IBinder windowToken ) { final MenuBuilder menu = mMenu ; final AlertDialog . Builder builder = new AlertDialog . Builder ( menu . getContext ( ) ) ; mPresenter = new ListMenuPresenter ( builder . getContext ( ) , R . layout . abc_list_menu_item_layout ) ; mPresenter . setCallback ( this ) ; mMenu . addMenuPresenter ( mPresenter ) ; builder . setAdapter ( mPresenter . getAdapter ( ) , this ) ; final View headerView = menu . getHeaderView ( ) ; if ( headerView != null ) { builder . setCustomTitle ( headerView ) ; } else { builder . setIcon ( menu . getHeaderIcon ( ) ) . setTitle ( menu . getHeaderTitle ( ) ) ; } builder . setOnKeyListener ( this ) ; mDialog = builder . create ( ) ; mDialog . setOnDismissListener ( this ) ; WindowManager . LayoutParams lp = mDialog . getWindow ( ) . getAttributes ( ) ; lp . type = WindowManager . LayoutParams . TYPE_APPLICATION_ATTACHED_DIALOG ; if ( windowToken != null ) { lp . token = windowToken ; } lp . flags |= WindowManager . LayoutParams . FLAG_ALT_FOCUSABLE_IM ; mDialog . show ( ) ; }
Shows menu as a dialog .
2,362
public void onScroll ( AbsListView view , int firstVisibleItem , int visibleItemCount , int totalItemCount ) { SimpleMonthView child = ( SimpleMonthView ) view . getChildAt ( 0 ) ; if ( child == null ) { return ; } long currScroll = view . getFirstVisiblePosition ( ) * child . getHeight ( ) - child . getBottom ( ) ; mPreviousScrollPosition = currScroll ; mPreviousScrollState = mCurrentScrollState ; }
Updates the title and selected month if the view has moved to a new month .
2,363
public int getMostVisiblePosition ( ) { final int firstPosition = getFirstVisiblePosition ( ) ; final int height = getHeight ( ) ; int maxDisplayedHeight = 0 ; int mostVisibleIndex = 0 ; int i = 0 ; int bottom = 0 ; while ( bottom < height ) { View child = getChildAt ( i ) ; if ( child == null ) { break ; } bottom = child . getBottom ( ) ; int displayedHeight = Math . min ( bottom , height ) - Math . max ( 0 , child . getTop ( ) ) ; if ( displayedHeight > maxDisplayedHeight ) { mostVisibleIndex = i ; maxDisplayedHeight = displayedHeight ; } i ++ ; } return firstPosition + mostVisibleIndex ; }
Gets the position of the view that is most prominently displayed within the list view .
2,364
public ArticleAttachments createUploadArticle ( long articleId , File file ) throws IOException { return createUploadArticle ( articleId , file , false ) ; }
Create upload article with inline false
2,365
@ ApiModelProperty ( required = true , value = "Key-value pairs to add as custom property into alert. You can refer here for example values" ) public Map < String , String > getDetails ( ) { return details ; }
Key - value pairs to add as custom property into alert . You can refer here for example values
2,366
public Map serialize ( ) throws OpsGenieClientValidationException { validate ( ) ; try { return JsonUtils . toMap ( this ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; }
convertes request to map
2,367
public void fromJson ( String json ) throws IOException , ParseException { JsonUtils . fromJson ( this , json ) ; this . json = json ; }
Convert json data to response
2,368
public void setApiKey ( String apiKey ) { if ( this . jsonHttpClient != null ) { this . jsonHttpClient . setApiKey ( apiKey ) ; } if ( this . restApiClient != null ) { this . restApiClient . setApiKey ( apiKey ) ; } if ( this . swaggerApiClient != null ) { ApiKeyAuth genieKey = ( ApiKeyAuth ) this . swaggerApiClient . getAuthentication ( "GenieKey" ) ; genieKey . setApiKeyPrefix ( "GenieKey" ) ; genieKey . setApiKey ( apiKey ) ; } }
Sets the customer key used for authenticating API requests .
2,369
public SuccessResponse deleteAlert ( DeleteAlertRequest params ) throws ApiException { String identifier = params . getIdentifier ( ) ; String identifierType = params . getIdentifierType ( ) . getValue ( ) ; String source = params . getSource ( ) ; String user = params . getUser ( ) ; Object localVarPostBody = null ; if ( identifier == null ) { throw new ApiException ( 400 , "Missing the required parameter 'identifier' when calling deleteAlert" ) ; } String localVarPath = "/v2/alerts/{identifier}" . replaceAll ( "\\{" + "identifier" + "\\}" , apiClient . escapeString ( identifier . toString ( ) ) ) ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "identifierType" , identifierType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "source" , source ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "user" , user ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "GenieKey" } ; GenericType < SuccessResponse > localVarReturnType = new GenericType < SuccessResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "DELETE" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }
Delete Alert Deletes an alert using alert id tiny id or alias
2,370
public SuccessResponse deleteAttachment ( DeleteAlertAttachmentRequest params ) throws ApiException { String identifier = params . getIdentifier ( ) ; Long attachmentId = params . getAttachmentId ( ) ; String alertIdentifierType = params . getAlertIdentifierType ( ) . getValue ( ) ; String user = params . getUser ( ) ; Object localVarPostBody = null ; if ( identifier == null ) { throw new ApiException ( 400 , "Missing the required parameter 'identifier' when calling deleteAttachment" ) ; } if ( attachmentId == null ) { throw new ApiException ( 400 , "Missing the required parameter 'attachmentId' when calling deleteAttachment" ) ; } String localVarPath = "/v2/alerts/{identifier}/attachments/{attachmentId}" . replaceAll ( "\\{" + "identifier" + "\\}" , apiClient . escapeString ( identifier . toString ( ) ) ) . replaceAll ( "\\{" + "attachmentId" + "\\}" , apiClient . escapeString ( attachmentId . toString ( ) ) ) ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "alertIdentifierType" , alertIdentifierType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "user" , user ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "GenieKey" } ; GenericType < SuccessResponse > localVarReturnType = new GenericType < SuccessResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "DELETE" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }
Delete Alert Attachment Delete alert attachment for the given identifier
2,371
public ListAlertsResponse listAlerts ( ListAlertsRequest params ) throws ApiException { Integer limit = params . getLimit ( ) ; String sort = params . getSort ( ) . getValue ( ) ; Integer offset = params . getOffset ( ) ; String order = params . getOrder ( ) . getValue ( ) ; String query = params . getQuery ( ) ; String searchIdentifier = params . getSearchIdentifier ( ) ; String searchIdentifierType = params . getSearchIdentifierType ( ) . getValue ( ) ; Object localVarPostBody = null ; String localVarPath = "/v2/alerts" ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "limit" , limit ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "sort" , sort ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "offset" , offset ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "order" , order ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "query" , query ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "searchIdentifier" , searchIdentifier ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "searchIdentifierType" , searchIdentifierType ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "GenieKey" } ; GenericType < ListAlertsResponse > localVarReturnType = new GenericType < ListAlertsResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }
List Alerts Returns list of alerts
2,372
public ListAlertNotesResponse listNotes ( ListAlertNotesRequest params ) throws ApiException { String identifier = params . getIdentifier ( ) ; String identifierType = params . getIdentifierType ( ) . getValue ( ) ; String offset = params . getOffset ( ) ; String direction = params . getDirection ( ) . getValue ( ) ; Integer limit = params . getLimit ( ) ; String order = params . getOrder ( ) . getValue ( ) ; Object localVarPostBody = null ; if ( identifier == null ) { throw new ApiException ( 400 , "Missing the required parameter 'identifier' when calling listNotes" ) ; } String localVarPath = "/v2/alerts/{identifier}/notes" . replaceAll ( "\\{" + "identifier" + "\\}" , apiClient . escapeString ( identifier . toString ( ) ) ) ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "identifierType" , identifierType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "offset" , offset ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "direction" , direction ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "limit" , limit ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "order" , order ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "GenieKey" } ; GenericType < ListAlertNotesResponse > localVarReturnType = new GenericType < ListAlertNotesResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }
List Alert Notes List alert notes for the given alert identifier
2,373
public ListSavedSearchResponse listSavedSearches ( ) throws ApiException { Object localVarPostBody = null ; String localVarPath = "/v2/alerts/saved-searches" ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "GenieKey" } ; GenericType < ListSavedSearchResponse > localVarReturnType = new GenericType < ListSavedSearchResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }
Lists Saved Searches List all saved searches
2,374
public List < ScheduleRotation > getRotations ( ) { if ( getTimeZone ( ) != null && rotations != null ) for ( ScheduleRotation scheduleRotation : rotations ) scheduleRotation . setScheduleTimeZone ( getTimeZone ( ) ) ; return rotations ; }
Rotations of schedule
2,375
@ JsonProperty ( "participants" ) public List < String > getParticipantsNames ( ) { if ( participants == null ) return null ; List < String > participantList = new ArrayList < String > ( ) ; for ( ScheduleParticipant participant : participants ) participantList . add ( participant . getParticipant ( ) ) ; return participantList ; }
Participants of schedule rotation
2,376
public void setConnectionValues ( final Google google , final ConnectionValues values ) { final UserInfo userInfo = google . oauth2Operations ( ) . getUserinfo ( ) ; values . setProviderUserId ( userInfo . getId ( ) ) ; values . setDisplayName ( userInfo . getName ( ) ) ; values . setProfileUrl ( userInfo . getLink ( ) ) ; values . setImageUrl ( userInfo . getPicture ( ) ) ; }
Set a value on the connection .
2,377
public UserProfile fetchUserProfile ( final Google google ) { final UserInfo userInfo = google . oauth2Operations ( ) . getUserinfo ( ) ; return new UserProfileBuilder ( ) . setUsername ( userInfo . getId ( ) ) . setId ( userInfo . getId ( ) ) . setEmail ( userInfo . getEmail ( ) ) . setName ( userInfo . getName ( ) ) . setFirstName ( userInfo . getGivenName ( ) ) . setLastName ( userInfo . getFamilyName ( ) ) . build ( ) ; }
Return the current user profile .
2,378
public String getImageUrl ( ) { if ( thumbnailUrl != null ) { return thumbnailUrl ; } if ( image != null ) { return image . url ; } return null ; }
Get the image URL - uses the thumbnail if set then the main image otherwise returns null .
2,379
public String getAccountEmail ( ) { if ( emails != null ) { for ( final Entry < String , String > entry : emails . entrySet ( ) ) { if ( entry . getValue ( ) . equals ( "account" ) ) { return entry . getKey ( ) ; } } } return null ; }
Return the account email .
2,380
public static String enumToString ( final Enum < ? > value ) { if ( value == null ) { return null ; } final String underscored = value . name ( ) ; final StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < underscored . length ( ) ; i ++ ) { final char c = underscored . charAt ( i ) ; if ( c == '_' ) { sb . append ( Character . toUpperCase ( underscored . charAt ( ++ i ) ) ) ; } else { sb . append ( Character . toLowerCase ( c ) ) ; } } return sb . toString ( ) ; }
Convert an enumeration to a String representation .
2,381
public MockResponse handleCreate ( String path , String s ) { MockResponse response = new MockResponse ( ) ; AttributeSet features = AttributeSet . merge ( attributeExtractor . fromPath ( path ) , attributeExtractor . fromResource ( s ) ) ; map . put ( features , s ) ; response . setBody ( s ) ; response . setResponseCode ( 202 ) ; return response ; }
Adds the specified object to the in - memory db .
2,382
public MockResponse handlePatch ( String path , String s ) { MockResponse response = new MockResponse ( ) ; String body = doGet ( path ) ; if ( body == null ) { response . setResponseCode ( 404 ) ; } else { try { JsonNode patch = context . getMapper ( ) . readTree ( s ) ; JsonNode source = context . getMapper ( ) . readTree ( body ) ; JsonNode updated = JsonPatch . apply ( patch , source ) ; String updatedAsString = context . getMapper ( ) . writeValueAsString ( updated ) ; AttributeSet features = AttributeSet . merge ( attributeExtractor . fromPath ( path ) , attributeExtractor . fromResource ( updatedAsString ) ) ; map . put ( features , updatedAsString ) ; response . setResponseCode ( 202 ) ; response . setBody ( updatedAsString ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } return response ; }
Patches the specified object to the in - memory db .
2,383
public MockResponse handleDelete ( String path ) { MockResponse response = new MockResponse ( ) ; List < AttributeSet > items = new ArrayList < > ( ) ; AttributeSet query = attributeExtractor . extract ( path ) ; for ( Map . Entry < AttributeSet , String > entry : map . entrySet ( ) ) { if ( entry . getKey ( ) . matches ( query ) ) { items . add ( entry . getKey ( ) ) ; } } if ( ! items . isEmpty ( ) ) { for ( AttributeSet item : items ) { map . remove ( item ) ; } response . setResponseCode ( 200 ) ; } else { response . setResponseCode ( 404 ) ; } return response ; }
Performs a delete for the corresponding object from the in - memory db .
2,384
public List < ExportFormat > exportFormats ( IssueServiceConfiguration issueServiceConfiguration ) { return issueExportServiceFactory . getIssueExportServices ( ) . stream ( ) . map ( IssueExportService :: getExportFormat ) . collect ( Collectors . toList ( ) ) ; }
Export of both text and HTML by default .
2,385
public TemplateInstanceExecution templateInstanceExecution ( String sourceName , ExpressionEngine expressionEngine ) { Map < String , String > sourceNameInput = Collections . singletonMap ( "sourceName" , sourceName ) ; Map < String , String > parameterMap = Maps . transformValues ( Maps . uniqueIndex ( parameters , TemplateParameter :: getName ) , parameter -> expressionEngine . render ( parameter . getExpression ( ) , sourceNameInput ) ) ; Map < String , String > inputMap = new HashMap < > ( sourceNameInput ) ; inputMap . putAll ( parameterMap ) ; return new TemplateInstanceExecution ( value -> expressionEngine . render ( value , inputMap ) , parameterMap ) ; }
Gets the execution context for the creation of a template instance .
2,386
public Map < String , Set < String > > getGroupingSpecification ( ) { Map < String , Set < String > > result = new LinkedHashMap < > ( ) ; if ( ! StringUtils . isBlank ( grouping ) ) { String [ ] groups = split ( grouping , '|' ) ; for ( String group : groups ) { String [ ] groupSpec = split ( group . trim ( ) , '=' ) ; if ( groupSpec . length != 2 ) throw new ExportRequestGroupingFormatException ( grouping ) ; String groupName = groupSpec [ 0 ] . trim ( ) ; result . put ( groupName , Sets . newLinkedHashSet ( Arrays . asList ( split ( groupSpec [ 1 ] . trim ( ) , ',' ) ) . stream ( ) . map ( String :: trim ) . collect ( Collectors . toList ( ) ) ) ) ; } } return result ; }
Parses the specification and returns a map of groups x set of types . The map will be empty if no group is defined but never null .
2,387
public Set < String > getExcludedTypes ( ) { if ( StringUtils . isBlank ( exclude ) ) { return Collections . emptySet ( ) ; } else { return Sets . newHashSet ( Arrays . asList ( StringUtils . split ( exclude , "," ) ) . stream ( ) . map ( StringUtils :: trim ) . collect ( Collectors . toList ( ) ) ) ; } }
Parses the comma - separated list of excluded types .
2,388
@ RequestMapping ( value = "ldap-mapping" , method = RequestMethod . GET ) public Resources < LDAPMapping > getMappings ( ) { securityService . checkGlobalFunction ( AccountGroupManagement . class ) ; return Resources . of ( accountGroupMappingService . getMappings ( LDAPExtensionFeature . LDAP_GROUP_MAPPING ) . stream ( ) . map ( LDAPMapping :: of ) , uri ( on ( getClass ( ) ) . getMappings ( ) ) ) . with ( Link . CREATE , uri ( on ( getClass ( ) ) . getMappingCreationForm ( ) ) , securityService . isGlobalFunctionGranted ( AccountGroupManagement . class ) ) ; }
Gets the list of mappings
2,389
@ RequestMapping ( value = "ldap-mapping/create" , method = RequestMethod . GET ) public Form getMappingCreationForm ( ) { securityService . checkGlobalFunction ( AccountGroupManagement . class ) ; return AccountGroupMapping . form ( accountService . getAccountGroups ( ) ) ; }
Gets the form for the creation of a mapping
2,390
public boolean canEdit ( ProjectEntity entity , SecurityService securityService ) { return securityService . isProjectFunctionGranted ( entity , PromotionRunCreate . class ) ; }
If one can promote a build he can also attach a release label to a build .
2,391
@ RequestMapping ( value = "predefinedPromotionLevels" , method = RequestMethod . GET ) public Resources < PredefinedPromotionLevel > getPredefinedPromotionLevelList ( ) { return Resources . of ( predefinedPromotionLevelService . getPredefinedPromotionLevels ( ) , uri ( on ( getClass ( ) ) . getPredefinedPromotionLevelList ( ) ) ) . with ( Link . CREATE , uri ( on ( getClass ( ) ) . getPredefinedPromotionLevelCreationForm ( ) ) ) . with ( "_reorderPromotionLevels" , uri ( on ( getClass ( ) ) . reorderPromotionLevelListForBranch ( null ) ) ) ; }
Gets the list of predefined promotion levels .
2,392
@ RequestMapping ( value = "root" , method = RequestMethod . GET ) public Resources < UIEvent > getEvents ( @ RequestParam ( required = false , defaultValue = "0" ) int offset , @ RequestParam ( required = false , defaultValue = "20" ) int count ) { Resources < UIEvent > resources = Resources . of ( eventQueryService . getEvents ( offset , count ) . stream ( ) . map ( this :: toUIEvent ) . collect ( Collectors . toList ( ) ) , uri ( on ( getClass ( ) ) . getEvents ( offset , count ) ) ) . forView ( UIEvent . class ) ; Pagination pagination = Pagination . of ( offset , count , - 1 ) ; if ( offset > 0 ) { pagination = pagination . withPrev ( uri ( on ( EventController . class ) . getEvents ( Math . max ( 0 , offset - count ) , count ) ) ) ; } pagination = pagination . withNext ( uri ( on ( EventController . class ) . getEvents ( offset + count , count ) ) ) ; return resources . withPagination ( pagination ) ; }
Gets the list of events for the root .
2,393
public void store ( String key , byte [ ] payload ) throws IOException { try { Cipher sym = Cipher . getInstance ( "AES" ) ; sym . init ( Cipher . ENCRYPT_MODE , masterKey ) ; try ( FileOutputStream fos = new FileOutputStream ( getFileFor ( key ) ) ; CipherOutputStream cos = new CipherOutputStream ( fos , sym ) ) { cos . write ( payload ) ; cos . write ( MAGIC ) ; } } catch ( GeneralSecurityException e ) { throw new IOException ( "Failed to persist the key: " + key , e ) ; } }
Persists the payload of a key to the disk .
2,394
@ RequestMapping ( value = "configurations" , method = RequestMethod . GET ) public Resources < CombinedIssueServiceConfiguration > getConfigurationList ( ) { return Resources . of ( configurationService . getConfigurationList ( ) , uri ( on ( getClass ( ) ) . getConfigurationList ( ) ) ) . with ( Link . CREATE , uri ( on ( getClass ( ) ) . getConfigurationForm ( ) ) ) ; }
Gets the list of configurations
2,395
@ RequestMapping ( value = "configurations/create" , method = RequestMethod . GET ) public Form getConfigurationForm ( ) { return CombinedIssueServiceConfiguration . form ( configurationService . getAvailableIssueServiceConfigurations ( ) ) ; }
Form for a new configuration
2,396
public static void checkArgList ( DataFetchingEnvironment environment , String ... args ) { Set < String > actualArgs = getActualArguments ( environment ) . keySet ( ) ; Set < String > expectedArgs = new HashSet < > ( Arrays . asList ( args ) ) ; if ( ! Objects . equals ( actualArgs , expectedArgs ) ) { throw new IllegalStateException ( String . format ( "Expected this list of arguments: %s, but was: %s" , expectedArgs , actualArgs ) ) ; } }
Checks list of arguments
2,397
public String getCuredBranchPath ( ) { String trim = StringUtils . trim ( branchPath ) ; if ( "/" . equals ( trim ) ) { return trim ; } else { return StringUtils . stripEnd ( trim , "/" ) ; } }
Returns a path which has been cleaned from its trailing or leading components .
2,398
private void indexInTransaction ( SVNRepository repository , SVNLogEntry logEntry ) throws SVNException { long revision = logEntry . getRevision ( ) ; String author = logEntry . getAuthor ( ) ; String message = logEntry . getMessage ( ) ; Date date = logEntry . getDate ( ) ; author = Objects . toString ( author , "" ) ; message = Objects . toString ( message , "" ) ; LocalDateTime dateTime = Time . from ( date , Time . now ( ) ) ; String branch = getBranchForRevision ( repository , logEntry ) ; logger . info ( String . format ( "Indexing revision %d" , revision ) ) ; revisionDao . addRevision ( repository . getId ( ) , revision , author , dateTime , message , branch ) ; try ( Transaction ignored = transactionService . start ( true ) ) { List < Long > mergedRevisions = svnClient . getMergedRevisions ( repository , SVNUtils . toURL ( repository . getConfiguration ( ) . getUrl ( ) , branch ) , revision ) ; List < Long > uniqueMergedRevisions = mergedRevisions . stream ( ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; revisionDao . addMergedRevisions ( repository . getId ( ) , revision , uniqueMergedRevisions ) ; } indexSVNEvents ( repository , logEntry ) ; indexIssues ( repository , logEntry ) ; }
This method is executed within a transaction
2,399
protected void index ( SVNRepository repository , long from , long to , JobRunListener runListener ) { if ( from > to ) { long t = from ; from = to ; to = t ; } long min = from ; long max = to ; try ( Transaction ignored = transactionService . start ( ) ) { SVNURL url = SVNUtils . toURL ( repository . getConfiguration ( ) . getUrl ( ) ) ; long startRevision = repository . getConfiguration ( ) . getIndexationStart ( ) ; from = Math . max ( startRevision , from ) ; long repositoryRevision = svnClient . getRepositoryRevision ( repository , url ) ; to = Math . min ( to , repositoryRevision ) ; if ( from > to ) { throw new IllegalArgumentException ( String . format ( "Cannot index range from %d to %d" , from , to ) ) ; } logger . info ( "[svn-indexation] Repository={}, Range: {}-{}" , repository . getId ( ) , from , to ) ; SVNRevision fromRevision = SVNRevision . create ( from ) ; SVNRevision toRevision = SVNRevision . create ( to ) ; IndexationHandler handler = new IndexationHandler ( repository , revision -> runListener . message ( "Indexation on %s is running (%d to %d - at %d - %d%%)" , repository . getConfiguration ( ) . getName ( ) , min , max , revision , Math . round ( 100.0 * ( revision - min + 1 ) / ( max - min + 1 ) ) ) ) ; svnClient . log ( repository , url , SVNRevision . HEAD , fromRevision , toRevision , true , true , 0 , false , handler ) ; } }
Indexation of a range in a thread for one repository - since it is called by a single thread executor we can be sure that only one call of this method is running at one time for one given repository .