idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
27,500 | public boolean performItemClick ( View view , int position , long id ) { if ( mOnItemClickListener != null ) { playSoundEffect ( SoundEffectConstants . CLICK ) ; if ( view != null ) { view . sendAccessibilityEvent ( AccessibilityEvent . TYPE_VIEW_CLICKED ) ; } mOnItemClickListener . onItemClick ( null , view , position , id ) ; return true ; } return false ; } | Call the OnItemClickListener if it is defined . |
27,501 | public int getPositionForView ( View view ) { View listItem = view ; try { View v ; while ( ! ( v = ( View ) listItem . getParent ( ) ) . equals ( this ) ) { listItem = v ; } } catch ( ClassCastException e ) { return INVALID_POSITION ; } final int childCount = getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { if ( getChildAt ( i ) . equals ( listItem ) ) { return mFirstPosition + i ; } } return INVALID_POSITION ; } | Get the position within the adapter s data set for the view where view is a an adapter item or a descendant of an adapter item . |
27,502 | public Object getItemAtPosition ( int position ) { T adapter = getAdapter ( ) ; return ( adapter == null || position < 0 ) ? null : adapter . getItem ( position ) ; } | Gets the data associated with the specified position in the list . |
27,503 | public static int loadLogoFromManifest ( Activity activity ) { int logo = 0 ; try { final String thisPackage = activity . getClass ( ) . getName ( ) ; if ( ActionBarSherlock . DEBUG ) Log . i ( TAG , "Parsing AndroidManifest.xml for " + thisPackage ) ; final String packageName = activity . getApplicationInfo ( ) . packageName ; final AssetManager am = activity . createPackageContext ( packageName , 0 ) . getAssets ( ) ; final XmlResourceParser xml = am . openXmlResourceParser ( "AndroidManifest.xml" ) ; int eventType = xml . getEventType ( ) ; while ( eventType != XmlPullParser . END_DOCUMENT ) { if ( eventType == XmlPullParser . START_TAG ) { String name = xml . getName ( ) ; if ( "application" . equals ( name ) ) { if ( ActionBarSherlock . DEBUG ) Log . d ( TAG , "Got <application>" ) ; for ( int i = xml . getAttributeCount ( ) - 1 ; i >= 0 ; i -- ) { if ( ActionBarSherlock . DEBUG ) Log . d ( TAG , xml . getAttributeName ( i ) + ": " + xml . getAttributeValue ( i ) ) ; if ( "logo" . equals ( xml . getAttributeName ( i ) ) ) { logo = xml . getAttributeResourceValue ( i , 0 ) ; break ; } } } else if ( "activity" . equals ( name ) ) { if ( ActionBarSherlock . DEBUG ) Log . d ( TAG , "Got <activity>" ) ; Integer activityLogo = null ; String activityPackage = null ; boolean isOurActivity = false ; for ( int i = xml . getAttributeCount ( ) - 1 ; i >= 0 ; i -- ) { if ( ActionBarSherlock . DEBUG ) Log . d ( TAG , xml . getAttributeName ( i ) + ": " + xml . getAttributeValue ( i ) ) ; String attrName = xml . getAttributeName ( i ) ; if ( "logo" . equals ( attrName ) ) { activityLogo = xml . getAttributeResourceValue ( i , 0 ) ; } else if ( "name" . equals ( attrName ) ) { activityPackage = ActionBarSherlockCompat . cleanActivityName ( packageName , xml . getAttributeValue ( i ) ) ; if ( ! thisPackage . equals ( activityPackage ) ) { break ; } isOurActivity = true ; } if ( ( activityLogo != null ) && ( activityPackage != null ) ) { logo = activityLogo . intValue ( ) ; } } if ( isOurActivity ) { break ; } } } eventType = xml . nextToken ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } if ( ActionBarSherlock . DEBUG ) Log . i ( TAG , "Returning " + Integer . toHexString ( logo ) ) ; return logo ; } | Attempt to programmatically load the logo from the manifest file of an activity by using an XML pull parser . This should allow us to read the logo attribute regardless of the platform it is being run on . |
27,504 | private void setActivityChooserPolicyIfNeeded ( ) { if ( mOnShareTargetSelectedListener == null ) { return ; } if ( mOnChooseActivityListener == null ) { mOnChooseActivityListener = new ShareAcitivityChooserModelPolicy ( ) ; } ActivityChooserModel dataModel = ActivityChooserModel . get ( mContext , mShareHistoryFileName ) ; dataModel . setOnChooseActivityListener ( mOnChooseActivityListener ) ; } | Set the activity chooser policy of the model backed by the current share history file if needed which is if there is a registered callback . |
27,505 | private void sortActivities ( ) { synchronized ( mInstanceLock ) { if ( mActivitySorter != null && ! mActivites . isEmpty ( ) ) { mActivitySorter . sort ( mIntent , mActivites , Collections . unmodifiableList ( mHistoricalRecords ) ) ; notifyChanged ( ) ; } } } | Sorts the activities based on history and an intent . If a sorter is not specified this a default implementation is used . |
27,506 | private void loadActivitiesLocked ( ) { mActivites . clear ( ) ; if ( mIntent != null ) { 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 ) ; mActivites . add ( new ActivityResolveInfo ( resolveInfo ) ) ; } sortActivities ( ) ; } else { notifyChanged ( ) ; } } | Loads the activities . |
27,507 | public boolean onKeyDown ( int keyCode , KeyEvent event ) { if ( mSearchable == null ) { return false ; } return super . onKeyDown ( keyCode , event ) ; } | Handles the key down event for dealing with action keys . |
27,508 | private boolean onSuggestionsKey ( View v , int keyCode , KeyEvent event ) { if ( mSearchable == null ) { return false ; } if ( mSuggestionsAdapter == null ) { return false ; } if ( event . getAction ( ) == KeyEvent . ACTION_DOWN && KeyEventCompat . hasNoModifiers ( event ) ) { if ( keyCode == KeyEvent . KEYCODE_ENTER || keyCode == KeyEvent . KEYCODE_SEARCH || keyCode == KeyEvent . KEYCODE_TAB ) { int position = mQueryTextView . getListSelection ( ) ; return onItemClicked ( position , KeyEvent . KEYCODE_UNKNOWN , null ) ; } if ( keyCode == KeyEvent . KEYCODE_DPAD_LEFT || keyCode == KeyEvent . KEYCODE_DPAD_RIGHT ) { int selPoint = ( keyCode == KeyEvent . KEYCODE_DPAD_LEFT ) ? 0 : mQueryTextView . length ( ) ; mQueryTextView . setSelection ( selPoint ) ; mQueryTextView . setListSelection ( 0 ) ; mQueryTextView . clearListSelection ( ) ; ensureImeVisible ( mQueryTextView , true ) ; return true ; } if ( keyCode == KeyEvent . KEYCODE_DPAD_UP && 0 == mQueryTextView . getListSelection ( ) ) { return false ; } } return false ; } | React to the user typing while in the suggestions list . First check for action keys . If not handled try refocusing regular characters into the EditText . |
27,509 | private void updateVoiceButton ( boolean empty ) { int visibility = GONE ; if ( mVoiceButtonEnabled && ! isIconified ( ) && empty ) { visibility = VISIBLE ; mSubmitButton . setVisibility ( GONE ) ; } mVoiceButton . setVisibility ( visibility ) ; } | Update the visibility of the voice button . There are actually two voice search modes either of which will activate the button . |
27,510 | private void rewriteQueryFromSuggestion ( int position ) { CharSequence oldQuery = mQueryTextView . getText ( ) ; Cursor c = mSuggestionsAdapter . getCursor ( ) ; if ( c == null ) { return ; } if ( c . moveToPosition ( position ) ) { CharSequence newQuery = mSuggestionsAdapter . convertToString ( c ) ; if ( newQuery != null ) { setQuery ( newQuery ) ; } else { setQuery ( oldQuery ) ; } } else { setQuery ( oldQuery ) ; } } | Query rewriting . |
27,511 | private boolean launchSuggestion ( int position , int actionKey , String actionMsg ) { Cursor c = mSuggestionsAdapter . getCursor ( ) ; if ( ( c != null ) && c . moveToPosition ( position ) ) { Intent intent = createIntentFromSuggestion ( c , actionKey , actionMsg ) ; launchIntent ( intent ) ; return true ; } return false ; } | Launches an intent based on a suggestion . |
27,512 | private void launchIntent ( Intent intent ) { if ( intent == null ) { return ; } try { getContext ( ) . startActivity ( intent ) ; } catch ( RuntimeException ex ) { Log . e ( LOG_TAG , "Failed launch activity: " + intent , ex ) ; } } | Launches an intent including any special intent handling . |
27,513 | private Intent createIntent ( String action , Uri data , String extraData , String query , int actionKey , String actionMsg ) { Intent intent = new Intent ( action ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; if ( data != null ) { intent . setData ( data ) ; } intent . putExtra ( SearchManager . USER_QUERY , mUserQuery ) ; if ( query != null ) { intent . putExtra ( SearchManager . QUERY , query ) ; } if ( extraData != null ) { intent . putExtra ( SearchManager . EXTRA_DATA_KEY , extraData ) ; } if ( mAppSearchData != null ) { intent . putExtra ( SearchManager . APP_DATA , mAppSearchData ) ; } if ( actionKey != KeyEvent . KEYCODE_UNKNOWN ) { intent . putExtra ( SearchManager . ACTION_KEY , actionKey ) ; intent . putExtra ( SearchManager . ACTION_MSG , actionMsg ) ; } intent . setComponent ( mSearchable . getSearchActivity ( ) ) ; return intent ; } | Constructs an intent from the given information and the search dialog state . |
27,514 | private Intent createVoiceWebSearchIntent ( Intent baseIntent , SearchableInfo searchable ) { Intent voiceIntent = new Intent ( baseIntent ) ; ComponentName searchActivity = searchable . getSearchActivity ( ) ; voiceIntent . putExtra ( RecognizerIntent . EXTRA_CALLING_PACKAGE , searchActivity == null ? null : searchActivity . flattenToShortString ( ) ) ; return voiceIntent ; } | Create and return an Intent that can launch the voice search activity for web search . |
27,515 | private Intent createVoiceAppSearchIntent ( Intent baseIntent , SearchableInfo searchable ) { ComponentName searchActivity = searchable . getSearchActivity ( ) ; Intent queryIntent = new Intent ( Intent . ACTION_SEARCH ) ; queryIntent . setComponent ( searchActivity ) ; PendingIntent pending = PendingIntent . getActivity ( getContext ( ) , 0 , queryIntent , PendingIntent . FLAG_ONE_SHOT ) ; Bundle queryExtras = new Bundle ( ) ; Intent voiceIntent = new Intent ( baseIntent ) ; String languageModel = RecognizerIntent . LANGUAGE_MODEL_FREE_FORM ; String prompt = null ; String language = null ; int maxResults = 1 ; Resources resources = getResources ( ) ; if ( searchable . getVoiceLanguageModeId ( ) != 0 ) { languageModel = resources . getString ( searchable . getVoiceLanguageModeId ( ) ) ; } if ( searchable . getVoicePromptTextId ( ) != 0 ) { prompt = resources . getString ( searchable . getVoicePromptTextId ( ) ) ; } if ( searchable . getVoiceLanguageId ( ) != 0 ) { language = resources . getString ( searchable . getVoiceLanguageId ( ) ) ; } if ( searchable . getVoiceMaxResults ( ) != 0 ) { maxResults = searchable . getVoiceMaxResults ( ) ; } voiceIntent . putExtra ( RecognizerIntent . EXTRA_LANGUAGE_MODEL , languageModel ) ; voiceIntent . putExtra ( RecognizerIntent . EXTRA_PROMPT , prompt ) ; voiceIntent . putExtra ( RecognizerIntent . EXTRA_LANGUAGE , language ) ; voiceIntent . putExtra ( RecognizerIntent . EXTRA_MAX_RESULTS , maxResults ) ; voiceIntent . putExtra ( RecognizerIntent . EXTRA_CALLING_PACKAGE , searchActivity == null ? null : searchActivity . flattenToShortString ( ) ) ; voiceIntent . putExtra ( RecognizerIntent . EXTRA_RESULTS_PENDINGINTENT , pending ) ; voiceIntent . putExtra ( RecognizerIntent . EXTRA_RESULTS_PENDINGINTENT_BUNDLE , queryExtras ) ; return voiceIntent ; } | Create and return an Intent that can launch the voice search activity perform a specific voice transcription and forward the results to the searchable activity . |
27,516 | void updateFragmentVisibility ( ) { FragmentTransaction ft = getSupportFragmentManager ( ) . beginTransaction ( ) ; if ( mCheckBox1 . isChecked ( ) ) ft . show ( mFragment1 ) ; else ft . hide ( mFragment1 ) ; if ( mCheckBox2 . isChecked ( ) ) ft . show ( mFragment2 ) ; else ft . hide ( mFragment2 ) ; ft . commit ( ) ; } | Update fragment visibility based on current check box state . |
27,517 | private Drawable tileifyIndeterminate ( Drawable drawable ) { if ( drawable instanceof AnimationDrawable ) { AnimationDrawable background = ( AnimationDrawable ) drawable ; final int N = background . getNumberOfFrames ( ) ; AnimationDrawable newBg = new AnimationDrawable ( ) ; newBg . setOneShot ( background . isOneShot ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { Drawable frame = tileify ( background . getFrame ( i ) , true ) ; frame . setLevel ( 10000 ) ; newBg . addFrame ( frame , background . getDuration ( i ) ) ; } newBg . setLevel ( 10000 ) ; drawable = newBg ; } return drawable ; } | Convert a AnimationDrawable for use as a barberpole animation . Each frame of the animation is wrapped in a ClipDrawable and given a tiling BitmapShader . |
27,518 | public void setGravity ( int gravity ) { if ( mGravity != gravity ) { if ( ( gravity & Gravity . HORIZONTAL_GRAVITY_MASK ) == 0 ) { gravity |= Gravity . LEFT ; } mGravity = gravity ; requestLayout ( ) ; } } | Describes how the selected item view is positioned . Currently only the horizontal component is used . The default is determined by the current theme . |
27,519 | private void setUpChild ( View child ) { ViewGroup . LayoutParams lp = child . getLayoutParams ( ) ; if ( lp == null ) { lp = generateDefaultLayoutParams ( ) ; } addViewInLayout ( child , 0 , lp ) ; child . setSelected ( hasFocus ( ) ) ; if ( mDisableChildrenWhenDisabled ) { child . setEnabled ( isEnabled ( ) ) ; } int childHeightSpec = ViewGroup . getChildMeasureSpec ( mHeightMeasureSpec , mSpinnerPadding . top + mSpinnerPadding . bottom , lp . height ) ; int childWidthSpec = ViewGroup . getChildMeasureSpec ( mWidthMeasureSpec , mSpinnerPadding . left + mSpinnerPadding . right , lp . width ) ; child . measure ( childWidthSpec , childHeightSpec ) ; int childLeft ; int childRight ; int childTop = mSpinnerPadding . top + ( ( getMeasuredHeight ( ) - mSpinnerPadding . bottom - mSpinnerPadding . top - child . getMeasuredHeight ( ) ) / 2 ) ; int childBottom = childTop + child . getMeasuredHeight ( ) ; int width = child . getMeasuredWidth ( ) ; childLeft = 0 ; childRight = childLeft + width ; child . layout ( childLeft , childTop , childRight , childBottom ) ; } | Helper for makeAndAddView to set the position of a view and fill out its layout paramters . |
27,520 | static int measureChildForCells ( View child , int cellSize , int cellsRemaining , int parentHeightMeasureSpec , int parentHeightPadding ) { final LayoutParams lp = ( LayoutParams ) child . getLayoutParams ( ) ; final int childHeightSize = MeasureSpec . getSize ( parentHeightMeasureSpec ) - parentHeightPadding ; final int childHeightMode = MeasureSpec . getMode ( parentHeightMeasureSpec ) ; final int childHeightSpec = MeasureSpec . makeMeasureSpec ( childHeightSize , childHeightMode ) ; int cellsUsed = 0 ; if ( cellsRemaining > 0 ) { final int childWidthSpec = MeasureSpec . makeMeasureSpec ( cellSize * cellsRemaining , MeasureSpec . AT_MOST ) ; child . measure ( childWidthSpec , childHeightSpec ) ; final int measuredWidth = child . getMeasuredWidth ( ) ; cellsUsed = measuredWidth / cellSize ; if ( measuredWidth % cellSize != 0 ) cellsUsed ++ ; } final ActionMenuItemView itemView = child instanceof ActionMenuItemView ? ( ActionMenuItemView ) child : null ; final boolean expandable = ! lp . isOverflowButton && itemView != null && itemView . hasText ( ) ; lp . expandable = expandable ; lp . cellsUsed = cellsUsed ; final int targetWidth = cellsUsed * cellSize ; child . measure ( MeasureSpec . makeMeasureSpec ( targetWidth , MeasureSpec . EXACTLY ) , childHeightSpec ) ; return cellsUsed ; } | Measure a child view to fit within cell - based formatting . The child s width will be measured to a whole multiple of cellSize . |
27,521 | public void setValues ( PropertyValuesHolder ... values ) { int numValues = values . length ; mValues = values ; mValuesMap = new HashMap < String , PropertyValuesHolder > ( numValues ) ; for ( int i = 0 ; i < numValues ; ++ i ) { PropertyValuesHolder valuesHolder = values [ i ] ; mValuesMap . put ( valuesHolder . getPropertyName ( ) , valuesHolder ) ; } mInitialized = false ; } | Sets the values per property being animated between . This function is called internally by the constructors of ValueAnimator that take a list of values . But an ValueAnimator can be constructed without values and this method can be called to set the values manually instead . |
27,522 | private void setupValue ( Object target , Keyframe kf ) { try { if ( mGetter == null ) { Class targetClass = target . getClass ( ) ; setupGetter ( targetClass ) ; } kf . setValue ( mGetter . invoke ( target ) ) ; } catch ( InvocationTargetException e ) { Log . e ( "PropertyValuesHolder" , e . toString ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( "PropertyValuesHolder" , e . toString ( ) ) ; } } | Utility function to set the value stored in a particular Keyframe . The value used is whatever the value is for the property name specified in the keyframe on the target object . |
27,523 | void setAnimatedValue ( Object target ) { if ( mSetter != null ) { try { mTmpValueArray [ 0 ] = getAnimatedValue ( ) ; mSetter . invoke ( target , mTmpValueArray ) ; } catch ( InvocationTargetException e ) { Log . e ( "PropertyValuesHolder" , e . toString ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( "PropertyValuesHolder" , e . toString ( ) ) ; } } } | Internal function to set the value on the target object using the setter set up earlier on this PropertyValuesHolder object . This function is called by ObjectAnimator to handle turning the value calculated by ValueAnimator into a value set on the object according to the name of the property . |
27,524 | public void removeMenuPresenter ( MenuPresenter presenter ) { for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter item = ref . get ( ) ; if ( item == null || item == presenter ) { mPresenters . remove ( ref ) ; } } } | Remove a presenter from this menu . That presenter will no longer receive notifications of updates to this menu s data . |
27,525 | final void close ( boolean allMenusAreClosing ) { if ( mIsClosing ) return ; mIsClosing = true ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else { presenter . onCloseMenu ( this , allMenusAreClosing ) ; } } mIsClosing = false ; } | Closes the visible menu . |
27,526 | void onItemsChanged ( boolean structureChanged ) { if ( ! mPreventDispatchingItemsChanged ) { if ( structureChanged ) { mIsVisibleItemsStale = true ; mIsActionItemsStale = true ; } dispatchPresenterUpdate ( structureChanged ) ; } else { mItemsChangedWhileDispatchPrevented = true ; } } | Called when an item is added or removed . |
27,527 | public static void registerImplementation ( Class < ? extends ActionBarSherlock > implementationClass ) { if ( ! implementationClass . isAnnotationPresent ( Implementation . class ) ) { throw new IllegalArgumentException ( "Class " + implementationClass . getSimpleName ( ) + " is not annotated with @Implementation" ) ; } else if ( IMPLEMENTATIONS . containsValue ( implementationClass ) ) { if ( DEBUG ) Log . w ( TAG , "Class " + implementationClass . getSimpleName ( ) + " already registered" ) ; return ; } Implementation impl = implementationClass . getAnnotation ( Implementation . class ) ; if ( DEBUG ) Log . i ( TAG , "Registering " + implementationClass . getSimpleName ( ) + " with qualifier " + impl ) ; IMPLEMENTATIONS . put ( impl , implementationClass ) ; } | Register an ActionBarSherlock implementation . |
27,528 | protected final boolean callbackCreateOptionsMenu ( Menu menu ) { if ( DEBUG ) Log . d ( TAG , "[callbackCreateOptionsMenu] menu: " + menu ) ; boolean result = true ; if ( mActivity instanceof OnCreatePanelMenuListener ) { OnCreatePanelMenuListener listener = ( OnCreatePanelMenuListener ) mActivity ; result = listener . onCreatePanelMenu ( Window . FEATURE_OPTIONS_PANEL , menu ) ; } else if ( mActivity instanceof OnCreateOptionsMenuListener ) { OnCreateOptionsMenuListener listener = ( OnCreateOptionsMenuListener ) mActivity ; result = listener . onCreateOptionsMenu ( menu ) ; } if ( DEBUG ) Log . d ( TAG , "[callbackCreateOptionsMenu] returning " + result ) ; return result ; } | Internal method to trigger the menu creation process . |
27,529 | protected final boolean callbackPrepareOptionsMenu ( Menu menu ) { if ( DEBUG ) Log . d ( TAG , "[callbackPrepareOptionsMenu] menu: " + menu ) ; boolean result = true ; if ( mActivity instanceof OnPreparePanelListener ) { OnPreparePanelListener listener = ( OnPreparePanelListener ) mActivity ; result = listener . onPreparePanel ( Window . FEATURE_OPTIONS_PANEL , null , menu ) ; } else if ( mActivity instanceof OnPrepareOptionsMenuListener ) { OnPrepareOptionsMenuListener listener = ( OnPrepareOptionsMenuListener ) mActivity ; result = listener . onPrepareOptionsMenu ( menu ) ; } if ( DEBUG ) Log . d ( TAG , "[callbackPrepareOptionsMenu] returning " + result ) ; return result ; } | Internal method to trigger the menu preparation process . |
27,530 | protected final boolean callbackOptionsItemSelected ( MenuItem item ) { if ( DEBUG ) Log . d ( TAG , "[callbackOptionsItemSelected] item: " + item . getTitleCondensed ( ) ) ; boolean result = false ; if ( mActivity instanceof OnMenuItemSelectedListener ) { OnMenuItemSelectedListener listener = ( OnMenuItemSelectedListener ) mActivity ; result = listener . onMenuItemSelected ( Window . FEATURE_OPTIONS_PANEL , item ) ; } else if ( mActivity instanceof OnOptionsItemSelectedListener ) { OnOptionsItemSelectedListener listener = ( OnOptionsItemSelectedListener ) mActivity ; result = listener . onOptionsItemSelected ( item ) ; } if ( DEBUG ) Log . d ( TAG , "[callbackOptionsItemSelected] returning " + result ) ; return result ; } | Internal method for dispatching options menu selection to the owning activity callback . |
27,531 | public void setContentView ( View view ) { if ( DEBUG ) Log . d ( TAG , "[setContentView] view: " + view ) ; setContentView ( view , new ViewGroup . LayoutParams ( MATCH_PARENT , MATCH_PARENT ) ) ; } | Set the content of the activity inside the action bar . |
27,532 | public void setTitle ( int resId ) { if ( DEBUG ) Log . d ( TAG , "[setTitle] resId: " + resId ) ; setTitle ( mActivity . getString ( resId ) ) ; } | Change the title associated with this activity . |
27,533 | public MenuInflater getMenuInflater ( ) { if ( DEBUG ) Log . d ( TAG , "[getMenuInflater]" ) ; if ( mMenuInflater == null ) { if ( getActionBar ( ) != null ) { mMenuInflater = new MenuInflater ( getThemedContext ( ) , mActivity ) ; } else { mMenuInflater = new MenuInflater ( mActivity ) ; } } return mMenuInflater ; } | Get a menu inflater instance which supports the newer menu attributes . |
27,534 | public void setAdapter ( SpinnerAdapter adapter ) { if ( null != mAdapter ) { mAdapter . unregisterDataSetObserver ( mDataSetObserver ) ; resetList ( ) ; } mAdapter = adapter ; mOldSelectedPosition = INVALID_POSITION ; mOldSelectedRowId = INVALID_ROW_ID ; if ( mAdapter != null ) { mOldItemCount = mItemCount ; mItemCount = mAdapter . getCount ( ) ; checkFocus ( ) ; mDataSetObserver = new AdapterDataSetObserver ( ) ; mAdapter . registerDataSetObserver ( mDataSetObserver ) ; int position = mItemCount > 0 ? 0 : INVALID_POSITION ; setSelectedPositionInt ( position ) ; setNextSelectedPositionInt ( position ) ; if ( mItemCount == 0 ) { checkSelectionChanged ( ) ; } } else { checkFocus ( ) ; resetList ( ) ; checkSelectionChanged ( ) ; } requestLayout ( ) ; } | The Adapter is used to provide the data which backs this Spinner . It also provides methods to transform spinner items based on their position relative to the selected item . |
27,535 | void resetList ( ) { mDataChanged = false ; mNeedSync = false ; removeAllViewsInLayout ( ) ; mOldSelectedPosition = INVALID_POSITION ; mOldSelectedRowId = INVALID_ROW_ID ; setSelectedPositionInt ( INVALID_POSITION ) ; setNextSelectedPositionInt ( INVALID_POSITION ) ; invalidate ( ) ; } | Clear out all children from the list |
27,536 | public void setSelection ( int position , boolean animate ) { boolean shouldAnimate = animate && mFirstPosition <= position && position <= mFirstPosition + getChildCount ( ) - 1 ; setSelectionInt ( position , shouldAnimate ) ; } | Jump directly to a specific item in the adapter data . |
27,537 | void setSelectionInt ( int position , boolean animate ) { if ( position != mOldSelectedPosition ) { mBlockLayoutRequests = true ; int delta = position - mSelectedPosition ; setNextSelectedPositionInt ( position ) ; layout ( delta , animate ) ; mBlockLayoutRequests = false ; } } | Makes the item at the supplied position selected . |
27,538 | public int pointToPosition ( int x , int y ) { Rect frame = mTouchFrame ; if ( frame == null ) { mTouchFrame = new Rect ( ) ; frame = mTouchFrame ; } final int count = getChildCount ( ) ; for ( int i = count - 1 ; i >= 0 ; i -- ) { View child = getChildAt ( i ) ; if ( child . getVisibility ( ) == View . VISIBLE ) { child . getHitRect ( frame ) ; if ( frame . contains ( x , y ) ) { return mFirstPosition + i ; } } } return INVALID_POSITION ; } | Maps a point to a position in the list . |
27,539 | public void setDividerDrawable ( Drawable divider ) { if ( divider == mDivider ) { return ; } if ( divider instanceof ColorDrawable && Build . VERSION . SDK_INT < Build . VERSION_CODES . HONEYCOMB ) { divider = new IcsColorDrawable ( ( ColorDrawable ) divider ) ; } mDivider = divider ; if ( divider != null ) { mDividerWidth = divider . getIntrinsicWidth ( ) ; mDividerHeight = divider . getIntrinsicHeight ( ) ; } else { mDividerWidth = 0 ; mDividerHeight = 0 ; } setWillNotDraw ( divider == null ) ; requestLayout ( ) ; } | Set a drawable to be used as a divider between items . |
27,540 | protected boolean hasDividerBeforeChildAt ( int childIndex ) { if ( childIndex == 0 ) { return ( mShowDividers & SHOW_DIVIDER_BEGINNING ) != 0 ; } else if ( childIndex == getChildCount ( ) ) { return ( mShowDividers & SHOW_DIVIDER_END ) != 0 ; } else if ( ( mShowDividers & SHOW_DIVIDER_MIDDLE ) != 0 ) { boolean hasVisibleViewBefore = false ; for ( int i = childIndex - 1 ; i >= 0 ; i -- ) { if ( getChildAt ( i ) . getVisibility ( ) != GONE ) { hasVisibleViewBefore = true ; break ; } } return hasVisibleViewBefore ; } return false ; } | Determines where to position dividers between children . |
27,541 | private void showPopupUnchecked ( int maxActivityCount ) { if ( mAdapter . getDataModel ( ) == null ) { throw new IllegalStateException ( "No data model. Did you call #setDataModel?" ) ; } getViewTreeObserver ( ) . addOnGlobalLayoutListener ( mOnGlobalLayoutListener ) ; final boolean defaultActivityButtonShown = mDefaultActivityButton . getVisibility ( ) == VISIBLE ; final int activityCount = mAdapter . getActivityCount ( ) ; final int maxActivityCountOffset = defaultActivityButtonShown ? 1 : 0 ; if ( maxActivityCount != ActivityChooserViewAdapter . MAX_ACTIVITY_COUNT_UNLIMITED && activityCount > maxActivityCount + maxActivityCountOffset ) { mAdapter . setShowFooterView ( true ) ; mAdapter . setMaxActivityCount ( maxActivityCount - 1 ) ; } else { mAdapter . setShowFooterView ( false ) ; mAdapter . setMaxActivityCount ( maxActivityCount ) ; } IcsListPopupWindow popupWindow = getListPopupWindow ( ) ; if ( ! popupWindow . isShowing ( ) ) { if ( mIsSelectingDefaultActivity || ! defaultActivityButtonShown ) { mAdapter . setShowDefaultActivity ( true , defaultActivityButtonShown ) ; } else { mAdapter . setShowDefaultActivity ( false , false ) ; } final int contentWidth = Math . min ( mAdapter . measureContentWidth ( ) , mListPopupMaxWidth ) ; popupWindow . setContentWidth ( contentWidth ) ; popupWindow . show ( ) ; if ( mProvider != null ) { mProvider . subUiVisibilityChanged ( true ) ; } popupWindow . getListView ( ) . setContentDescription ( mContext . getString ( R . string . abs__activitychooserview_choose_application ) ) ; } } | Shows the popup no matter if it was already showing . |
27,542 | public boolean dismissPopup ( ) { if ( isShowingPopup ( ) ) { getListPopupWindow ( ) . dismiss ( ) ; ViewTreeObserver viewTreeObserver = getViewTreeObserver ( ) ; if ( viewTreeObserver . isAlive ( ) ) { viewTreeObserver . removeGlobalOnLayoutListener ( mOnGlobalLayoutListener ) ; } } return true ; } | Dismisses the popup window with activities . |
27,543 | private IcsListPopupWindow getListPopupWindow ( ) { if ( mListPopupWindow == null ) { mListPopupWindow = new IcsListPopupWindow ( getContext ( ) ) ; mListPopupWindow . setAdapter ( mAdapter ) ; mListPopupWindow . setAnchorView ( ActivityChooserView . this ) ; mListPopupWindow . setModal ( true ) ; mListPopupWindow . setOnItemClickListener ( mCallbacks ) ; mListPopupWindow . setOnDismissListener ( mCallbacks ) ; } return mListPopupWindow ; } | Gets the list popup window which is lazily initialized . |
27,544 | private void updateAppearance ( ) { if ( mAdapter . getCount ( ) > 0 ) { mExpandActivityOverflowButton . setEnabled ( true ) ; } else { mExpandActivityOverflowButton . setEnabled ( false ) ; } final int activityCount = mAdapter . getActivityCount ( ) ; final int historySize = mAdapter . getHistorySize ( ) ; if ( activityCount > 0 && historySize > 0 ) { mDefaultActivityButton . setVisibility ( VISIBLE ) ; ResolveInfo activity = mAdapter . getDefaultActivity ( ) ; PackageManager packageManager = mContext . getPackageManager ( ) ; mDefaultActivityButtonImage . setImageDrawable ( activity . loadIcon ( packageManager ) ) ; if ( mDefaultActionButtonContentDescription != 0 ) { CharSequence label = activity . loadLabel ( packageManager ) ; String contentDescription = mContext . getString ( mDefaultActionButtonContentDescription , label ) ; mDefaultActivityButton . setContentDescription ( contentDescription ) ; } mAdapter . setShowDefaultActivity ( false , false ) ; } else { mDefaultActivityButton . setVisibility ( View . GONE ) ; } if ( mDefaultActivityButton . getVisibility ( ) == VISIBLE ) { mActivityChooserContent . setBackgroundDrawable ( mActivityChooserContentBackground ) ; } else { mActivityChooserContent . setBackgroundDrawable ( null ) ; mActivityChooserContent . setPadding ( 0 , 0 , 0 , 0 ) ; } } | Updates the buttons state . |
27,545 | public boolean invoke ( ) { if ( mClickListener != null && mClickListener . onMenuItemClick ( this ) ) { return true ; } if ( mMenu . dispatchMenuItemSelected ( mMenu . getRootMenu ( ) , this ) ) { return true ; } if ( mItemCallback != null ) { mItemCallback . run ( ) ; return true ; } if ( mIntent != null ) { try { mMenu . getContext ( ) . startActivity ( mIntent ) ; return true ; } catch ( ActivityNotFoundException e ) { Log . e ( TAG , "Can't find activity to handle intent; ignoring" , e ) ; } } if ( mActionProvider != null && mActionProvider . onPerformDefaultAction ( ) ) { return true ; } return false ; } | Invokes the item by calling various listeners or callbacks . |
27,546 | public String getText ( final String toTest , final int group ) { Matcher m = pattern . matcher ( toTest ) ; StringBuilder result = new StringBuilder ( ) ; while ( m . find ( ) ) { result . append ( m . group ( group ) ) ; } return result . toString ( ) ; } | Extract exact group from string |
27,547 | public List < String > getTextGroups ( final String toTest , final int group ) { List < String > groups = new ArrayList < > ( ) ; Matcher m = pattern . matcher ( toTest ) ; while ( m . find ( ) ) { groups . add ( m . group ( group ) ) ; } return groups ; } | Extract exact group from string and add it to list |
27,548 | public static Builder regex ( final Builder pBuilder ) { Builder builder = new Builder ( ) ; builder . prefixes . append ( pBuilder . prefixes ) ; builder . source . append ( pBuilder . source ) ; builder . suffixes . append ( pBuilder . suffixes ) ; builder . modifiers = pBuilder . modifiers ; return builder ; } | Creates new instance of VerbalExpression builder from cloned builder |
27,549 | public FieldConstraintsBuilder forField ( final CronFieldName field ) { switch ( field ) { case SECOND : case MINUTE : endRange = 59 ; return this ; case HOUR : endRange = 23 ; return this ; case DAY_OF_WEEK : stringMapping = daysOfWeekMapping ( ) ; endRange = 6 ; return this ; case DAY_OF_MONTH : startRange = 1 ; endRange = 31 ; return this ; case MONTH : stringMapping = monthsMapping ( ) ; startRange = 1 ; endRange = 12 ; return this ; case DAY_OF_YEAR : startRange = 1 ; endRange = 366 ; return this ; default : return this ; } } | Creates range constraints according to CronFieldName parameter . |
27,550 | private static Map < String , Integer > daysOfWeekMapping ( ) { final Map < String , Integer > stringMapping = new HashMap < > ( ) ; stringMapping . put ( "MON" , 1 ) ; stringMapping . put ( "TUE" , 2 ) ; stringMapping . put ( "WED" , 3 ) ; stringMapping . put ( "THU" , 4 ) ; stringMapping . put ( "FRI" , 5 ) ; stringMapping . put ( "SAT" , 6 ) ; stringMapping . put ( "SUN" , 7 ) ; return stringMapping ; } | Creates days of week mapping . |
27,551 | private static Map < String , Integer > monthsMapping ( ) { final Map < String , Integer > stringMapping = new HashMap < > ( ) ; stringMapping . put ( "JAN" , 1 ) ; stringMapping . put ( "FEB" , 2 ) ; stringMapping . put ( "MAR" , 3 ) ; stringMapping . put ( "APR" , 4 ) ; stringMapping . put ( "MAY" , 5 ) ; stringMapping . put ( "JUN" , 6 ) ; stringMapping . put ( "JUL" , 7 ) ; stringMapping . put ( "AUG" , 8 ) ; stringMapping . put ( "SEP" , 9 ) ; stringMapping . put ( "OCT" , 10 ) ; stringMapping . put ( "NOV" , 11 ) ; stringMapping . put ( "DEC" , 12 ) ; return stringMapping ; } | Creates months mapping . |
27,552 | public static String checkNotNullNorEmpty ( final String reference , final Object errorMessage ) { if ( reference == null ) { throw new NullPointerException ( String . valueOf ( errorMessage ) ) ; } if ( reference . isEmpty ( ) ) { throw new IllegalArgumentException ( String . valueOf ( errorMessage ) ) ; } return reference ; } | Ensures that a string reference passed as a parameter to the calling method is not null . nor empty . |
27,553 | public Cron map ( final Cron cron ) { Preconditions . checkNotNull ( cron , "Cron must not be null" ) ; final List < CronField > fields = new ArrayList < > ( ) ; for ( final CronFieldName name : CronFieldName . values ( ) ) { if ( mappings . containsKey ( name ) ) { fields . add ( mappings . get ( name ) . apply ( cron . retrieve ( name ) ) ) ; } } return cronRules . apply ( new SingleCron ( to , fields ) ) . validate ( ) ; } | Maps given cron to target cron definition . |
27,554 | public static CronMapper fromCron4jToQuartz ( ) { return new CronMapper ( CronDefinitionBuilder . instanceDefinitionFor ( CronType . CRON4J ) , CronDefinitionBuilder . instanceDefinitionFor ( CronType . QUARTZ ) , setQuestionMark ( ) ) ; } | Creates a CronMapper that maps a cron4j expression to a quartz expression . |
27,555 | private void buildMappings ( final CronDefinition from , final CronDefinition to ) { final Map < CronFieldName , FieldDefinition > sourceFieldDefinitions = getFieldDefinitions ( from ) ; final Map < CronFieldName , FieldDefinition > destFieldDefinitions = getFieldDefinitions ( to ) ; boolean startedDestMapping = false ; boolean startedSourceMapping = false ; for ( final CronFieldName name : CronFieldName . values ( ) ) { final FieldDefinition destinationFieldDefinition = destFieldDefinitions . get ( name ) ; final FieldDefinition sourceFieldDefinition = sourceFieldDefinitions . get ( name ) ; if ( destinationFieldDefinition != null ) { startedDestMapping = true ; } if ( sourceFieldDefinition != null ) { startedSourceMapping = true ; } if ( startedDestMapping && destinationFieldDefinition == null ) { break ; } if ( ! startedSourceMapping && destinationFieldDefinition != null ) { mappings . put ( name , returnOnZeroExpression ( name ) ) ; } if ( startedSourceMapping && sourceFieldDefinition == null && destinationFieldDefinition != null ) { mappings . put ( name , returnAlwaysExpression ( name ) ) ; } if ( sourceFieldDefinition == null || destinationFieldDefinition == null ) { continue ; } if ( CronFieldName . DAY_OF_WEEK . equals ( name ) ) { mappings . put ( name , dayOfWeekMapping ( ( DayOfWeekFieldDefinition ) sourceFieldDefinition , ( DayOfWeekFieldDefinition ) destinationFieldDefinition ) ) ; } else if ( CronFieldName . DAY_OF_MONTH . equals ( name ) ) { mappings . put ( name , dayOfMonthMapping ( sourceFieldDefinition , destinationFieldDefinition ) ) ; } else { mappings . put ( name , returnSameExpression ( ) ) ; } } } | Builds functions that map the fields from source CronDefinition to target . |
27,556 | static Function < CronField , CronField > returnOnZeroExpression ( final CronFieldName name ) { return field -> { final FieldConstraints constraints = FieldConstraintsBuilder . instance ( ) . forField ( name ) . createConstraintsInstance ( ) ; return new CronField ( name , new On ( new IntegerFieldValue ( 0 ) ) , constraints ) ; } ; } | Creates a Function that returns a On instance with zero value . |
27,557 | static Function < CronField , CronField > returnAlwaysExpression ( final CronFieldName name ) { return field -> new CronField ( name , always ( ) , FieldConstraintsBuilder . instance ( ) . forField ( name ) . createConstraintsInstance ( ) ) ; } | Creates a Function that returns an Always instance . |
27,558 | public static DescriptionStrategy daysOfWeekInstance ( final ResourceBundle bundle , final FieldExpression expression , final FieldDefinition definition ) { final Function < Integer , String > nominal = integer -> { final int diff = definition instanceof DayOfWeekFieldDefinition ? DayOfWeek . MONDAY . getValue ( ) - ( ( DayOfWeekFieldDefinition ) definition ) . getMondayDoWValue ( ) . getMondayDoWValue ( ) : 0 ; return DayOfWeek . of ( integer + diff < 1 ? 7 : integer + diff ) . getDisplayName ( TextStyle . FULL , bundle . getLocale ( ) ) ; } ; final NominalDescriptionStrategy dow = new NominalDescriptionStrategy ( bundle , nominal , expression ) ; dow . addDescription ( fieldExpression -> { if ( fieldExpression instanceof On ) { final On on = ( On ) fieldExpression ; switch ( on . getSpecialChar ( ) . getValue ( ) ) { case HASH : return String . format ( "%s %s %s " , nominal . apply ( on . getTime ( ) . getValue ( ) ) , on . getNth ( ) , bundle . getString ( "of_every_month" ) ) ; case L : return String . format ( "%s %s %s " , bundle . getString ( "last" ) , nominal . apply ( on . getTime ( ) . getValue ( ) ) , bundle . getString ( "of_every_month" ) ) ; default : return "" ; } } return "" ; } ) ; return dow ; } | Creates description strategy for days of week . |
27,559 | public static DescriptionStrategy daysOfMonthInstance ( final ResourceBundle bundle , final FieldExpression expression ) { final NominalDescriptionStrategy dom = new NominalDescriptionStrategy ( bundle , null , expression ) ; dom . addDescription ( fieldExpression -> { if ( fieldExpression instanceof On ) { final On on = ( On ) fieldExpression ; switch ( on . getSpecialChar ( ) . getValue ( ) ) { case W : return String . format ( "%s %s %s " , bundle . getString ( "the_nearest_weekday_to_the" ) , on . getTime ( ) . getValue ( ) , bundle . getString ( "of_the_month" ) ) ; case L : return bundle . getString ( "last_day_of_month" ) ; case LW : return bundle . getString ( "last_weekday_of_month" ) ; default : return "" ; } } return "" ; } ) ; return dom ; } | Creates description strategy for days of month . |
27,560 | public static DescriptionStrategy monthsInstance ( final ResourceBundle bundle , final FieldExpression expression ) { return new NominalDescriptionStrategy ( bundle , integer -> Month . of ( integer ) . getDisplayName ( TextStyle . FULL , bundle . getLocale ( ) ) , expression ) ; } | Creates description strategy for months . |
27,561 | public static DescriptionStrategy plainInstance ( final ResourceBundle bundle , final FieldExpression expression ) { return new NominalDescriptionStrategy ( bundle , null , expression ) ; } | Creates nominal description strategy . |
27,562 | protected String describe ( final FieldExpression fieldExpression , final boolean and ) { Preconditions . checkNotNull ( fieldExpression , "CronFieldExpression should not be null!" ) ; if ( fieldExpression instanceof Always ) { return describe ( fieldExpression , and ) ; } if ( fieldExpression instanceof And ) { return describe ( ( And ) fieldExpression ) ; } if ( fieldExpression instanceof Between ) { return describe ( fieldExpression , and ) ; } if ( fieldExpression instanceof Every ) { return describe ( ( Every ) fieldExpression , and ) ; } if ( fieldExpression instanceof On ) { return describe ( ( On ) fieldExpression , and ) ; } return StringUtils . EMPTY ; } | Given a CronFieldExpression provide a String with a human readable description . Will identify CronFieldExpression subclasses and delegate . |
27,563 | protected String describe ( final And and ) { final List < FieldExpression > expressions = new ArrayList < > ( ) ; final List < FieldExpression > onExpressions = new ArrayList < > ( ) ; for ( final FieldExpression fieldExpression : and . getExpressions ( ) ) { if ( fieldExpression instanceof On ) { onExpressions . add ( fieldExpression ) ; } else { expressions . add ( fieldExpression ) ; } } final StringBuilder builder = new StringBuilder ( ) ; if ( ! onExpressions . isEmpty ( ) ) { builder . append ( bundle . getString ( "at" ) ) ; createAndDescription ( builder , onExpressions ) ; } if ( ! expressions . isEmpty ( ) ) { createAndDescription ( builder , expressions ) ; } return builder . toString ( ) ; } | Provide a human readable description for And instance . |
27,564 | protected String describe ( final On on , final boolean and ) { if ( and ) { return nominalValue ( on . getTime ( ) ) ; } return String . format ( "%s %s " , bundle . getString ( "at" ) , nominalValue ( on . getTime ( ) ) ) + "%s" ; } | Provide a human readable description for On instance . |
27,565 | protected void isInRange ( final FieldValue < ? > fieldValue ) { if ( fieldValue instanceof IntegerFieldValue ) { final int value = ( ( IntegerFieldValue ) fieldValue ) . getValue ( ) ; if ( ! constraints . isInRange ( value ) ) { throw new IllegalArgumentException ( String . format ( OORANGE , value , constraints . getStartRange ( ) , constraints . getEndRange ( ) ) ) ; } } } | Check if given number is greater or equal to start range and minor or equal to end range . |
27,566 | public String describe ( final Cron cron ) { Preconditions . checkNotNull ( cron , "Cron must not be null" ) ; final Map < CronFieldName , CronField > expressions = cron . retrieveFieldsAsMap ( ) ; final Map < CronFieldName , FieldDefinition > fieldDefinitions = cron . getCronDefinition ( ) . retrieveFieldDefinitionsAsMap ( ) ; return new StringBuilder ( ) . append ( describeHHmmss ( expressions ) ) . append ( " " ) . append ( describeDayOfMonth ( expressions ) ) . append ( " " ) . append ( describeMonth ( expressions ) ) . append ( " " ) . append ( describeDayOfWeek ( expressions , fieldDefinitions ) ) . append ( " " ) . append ( describeYear ( expressions ) ) . toString ( ) . replaceAll ( "\\s+" , " " ) . trim ( ) ; } | Provide a description of given CronFieldParseResult list . |
27,567 | public String describeHHmmss ( final Map < CronFieldName , CronField > fields ) { return DescriptionStrategyFactory . hhMMssInstance ( resourceBundle , fields . containsKey ( CronFieldName . HOUR ) ? fields . get ( CronFieldName . HOUR ) . getExpression ( ) : null , fields . containsKey ( CronFieldName . MINUTE ) ? fields . get ( CronFieldName . MINUTE ) . getExpression ( ) : null , fields . containsKey ( CronFieldName . SECOND ) ? fields . get ( CronFieldName . SECOND ) . getExpression ( ) : null ) . describe ( ) ; } | Provide description for hours minutes and seconds . |
27,568 | public String describeDayOfMonth ( final Map < CronFieldName , CronField > fields ) { final String description = DescriptionStrategyFactory . daysOfMonthInstance ( resourceBundle , fields . containsKey ( CronFieldName . DAY_OF_MONTH ) ? fields . get ( CronFieldName . DAY_OF_MONTH ) . getExpression ( ) : null ) . describe ( ) ; return addTimeExpressions ( description , resourceBundle . getString ( "day" ) , resourceBundle . getString ( "days" ) ) ; } | Provide description for day of month . |
27,569 | public String describeMonth ( final Map < CronFieldName , CronField > fields ) { final String description = DescriptionStrategyFactory . monthsInstance ( resourceBundle , fields . containsKey ( CronFieldName . MONTH ) ? fields . get ( CronFieldName . MONTH ) . getExpression ( ) : null ) . describe ( ) ; return addTimeExpressions ( description , resourceBundle . getString ( "month" ) , resourceBundle . getString ( "months" ) ) ; } | Provide description for month . |
27,570 | public String describeDayOfWeek ( final Map < CronFieldName , CronField > fields , final Map < CronFieldName , FieldDefinition > definitions ) { final String description = DescriptionStrategyFactory . daysOfWeekInstance ( resourceBundle , fields . containsKey ( CronFieldName . DAY_OF_WEEK ) ? fields . get ( CronFieldName . DAY_OF_WEEK ) . getExpression ( ) : null , definitions . containsKey ( CronFieldName . DAY_OF_WEEK ) ? definitions . get ( CronFieldName . DAY_OF_WEEK ) : null ) . describe ( ) ; return addExpressions ( description , resourceBundle . getString ( "day" ) , resourceBundle . getString ( "days" ) ) ; } | Provide description for day of week . |
27,571 | public String describeYear ( final Map < CronFieldName , CronField > fields ) { final String description = DescriptionStrategyFactory . plainInstance ( resourceBundle , fields . containsKey ( CronFieldName . YEAR ) ? fields . get ( CronFieldName . YEAR ) . getExpression ( ) : null ) . describe ( ) ; return addExpressions ( description , resourceBundle . getString ( "year" ) , resourceBundle . getString ( "years" ) ) ; } | Provide description for a year . |
27,572 | private int generateNoneValues ( final On on , final int year , final int month , final int reference ) { final int dowForFirstDoM = LocalDate . of ( year , month , 1 ) . getDayOfWeek ( ) . getValue ( ) ; final int requiredDoW = ConstantsMapper . weekDayMapping ( mondayDoWValue , ConstantsMapper . JAVA8 , on . getTime ( ) . getValue ( ) ) ; int baseDay = 1 ; final int diff = dowForFirstDoM - requiredDoW ; if ( diff < 0 ) { baseDay = baseDay + Math . abs ( diff ) ; } if ( diff > 0 ) { baseDay = baseDay + 7 - diff ; } if ( reference < 1 ) { return baseDay ; } while ( baseDay <= reference ) { baseDay += 7 ; } return baseDay ; } | Generate valid days of the month for the days of week expression . This method requires that you pass it a - 1 for the reference value when starting to generate a sequence of day values . That allows it to handle the special case of which day of the month is the initial matching value . |
27,573 | public static CronConstraint ensureEitherDayOfYearOrMonth ( ) { return new CronConstraint ( "Both, a day-of-year AND a day-of-month or day-of-week, are not supported." ) { private static final long serialVersionUID = 520379111876897579L ; public boolean validate ( Cron cron ) { CronField dayOfYearField = cron . retrieve ( CronFieldName . DAY_OF_YEAR ) ; if ( dayOfYearField != null && ! ( dayOfYearField . getExpression ( ) instanceof QuestionMark ) ) { return cron . retrieve ( CronFieldName . DAY_OF_WEEK ) . getExpression ( ) instanceof QuestionMark && cron . retrieve ( CronFieldName . DAY_OF_MONTH ) . getExpression ( ) instanceof QuestionMark ; } return true ; } } ; } | Creates CronConstraint to ensure that either day - of - year or month is assigned a specific value . |
27,574 | public Cron validate ( ) { for ( final Map . Entry < CronFieldName , CronField > field : retrieveFieldsAsMap ( ) . entrySet ( ) ) { final CronFieldName fieldName = field . getKey ( ) ; field . getValue ( ) . getExpression ( ) . accept ( new ValidationFieldExpressionVisitor ( getCronDefinition ( ) . getFieldDefinition ( fieldName ) . getConstraints ( ) , cronDefinition . isStrictRanges ( ) ) ) ; } for ( final CronConstraint constraint : getCronDefinition ( ) . getCronConstraints ( ) ) { if ( ! constraint . validate ( this ) ) { throw new IllegalArgumentException ( String . format ( "Invalid cron expression: %s. %s" , asString ( ) , constraint . getDescription ( ) ) ) ; } } return this ; } | Validates this Cron instance by validating its cron expression . |
27,575 | public boolean equivalent ( final CronMapper cronMapper , final Cron cron ) { return asString ( ) . equals ( cronMapper . map ( cron ) . asString ( ) ) ; } | Provides means to compare if two cron expressions are equivalent . |
27,576 | private FieldExpression ensureInstance ( final FieldExpression expression , final FieldExpression defaultExpression ) { Preconditions . checkNotNull ( defaultExpression , "Default expression must not be null" ) ; if ( expression != null ) { return expression ; } else { return defaultExpression ; } } | Give an expression instance will return it if is not null . Otherwise will return the defaultExpression ; |
27,577 | public void register ( final FieldDefinition definition ) { boolean hasOptionalField = false ; for ( final FieldDefinition fieldDefinition : fields . values ( ) ) { if ( fieldDefinition . isOptional ( ) ) { hasOptionalField = true ; break ; } } if ( ! definition . isOptional ( ) && hasOptionalField ) { throw new IllegalArgumentException ( "Can't register mandatory definition after a optional definition." ) ; } fields . put ( definition . getFieldName ( ) , definition ) ; } | Registers a certain FieldDefinition . |
27,578 | public CronDefinition instance ( ) { final Set < CronConstraint > validations = new HashSet < > ( ) ; validations . addAll ( cronConstraints ) ; final List < FieldDefinition > values = new ArrayList < > ( fields . values ( ) ) ; values . sort ( FieldDefinition . createFieldDefinitionComparator ( ) ) ; return new CronDefinition ( values , validations , enforceStrictRanges , matchDayOfWeekAndDayOfMonth ) ; } | Creates a new CronDefinition instance with provided field definitions . |
27,579 | private static CronDefinition cron4j ( ) { return CronDefinitionBuilder . defineCron ( ) . withMinutes ( ) . and ( ) . withHours ( ) . and ( ) . withDayOfMonth ( ) . supportsL ( ) . and ( ) . withMonth ( ) . and ( ) . withDayOfWeek ( ) . withValidRange ( 0 , 6 ) . withMondayDoWValue ( 1 ) . and ( ) . enforceStrictRanges ( ) . matchDayOfWeekAndDayOfMonth ( ) . instance ( ) ; } | Creates CronDefinition instance matching cron4j specification . |
27,580 | private static CronDefinition quartz ( ) { return CronDefinitionBuilder . defineCron ( ) . withSeconds ( ) . and ( ) . withMinutes ( ) . and ( ) . withHours ( ) . and ( ) . withDayOfMonth ( ) . withValidRange ( 1 , 32 ) . supportsL ( ) . supportsW ( ) . supportsLW ( ) . supportsQuestionMark ( ) . and ( ) . withMonth ( ) . withValidRange ( 1 , 13 ) . and ( ) . withDayOfWeek ( ) . withValidRange ( 1 , 7 ) . withMondayDoWValue ( 2 ) . supportsHash ( ) . supportsL ( ) . supportsQuestionMark ( ) . and ( ) . withYear ( ) . withValidRange ( 1970 , 2099 ) . optional ( ) . and ( ) . withCronValidation ( CronConstraintsFactory . ensureEitherDayOfWeekOrDayOfMonth ( ) ) . instance ( ) ; } | Creates CronDefinition instance matching Quartz specification . |
27,581 | private static CronDefinition spring ( ) { return CronDefinitionBuilder . defineCron ( ) . withSeconds ( ) . and ( ) . withMinutes ( ) . and ( ) . withHours ( ) . and ( ) . withDayOfMonth ( ) . supportsQuestionMark ( ) . and ( ) . withMonth ( ) . and ( ) . withDayOfWeek ( ) . withValidRange ( 1 , 7 ) . withMondayDoWValue ( 2 ) . supportsQuestionMark ( ) . and ( ) . instance ( ) ; } | Creates CronDefinition instance matching Spring specification . |
27,582 | private static CronDefinition unixCrontab ( ) { return CronDefinitionBuilder . defineCron ( ) . withMinutes ( ) . and ( ) . withHours ( ) . and ( ) . withDayOfMonth ( ) . and ( ) . withMonth ( ) . and ( ) . withDayOfWeek ( ) . withValidRange ( 0 , 7 ) . withMondayDoWValue ( 1 ) . withIntMapping ( 7 , 0 ) . and ( ) . enforceStrictRanges ( ) . instance ( ) ; } | Creates CronDefinition instance matching unix crontab specification . |
27,583 | public static CronDefinition instanceDefinitionFor ( final CronType cronType ) { switch ( cronType ) { case CRON4J : return cron4j ( ) ; case QUARTZ : return quartz ( ) ; case UNIX : return unixCrontab ( ) ; case SPRING : return spring ( ) ; default : throw new IllegalArgumentException ( String . format ( "No cron definition found for %s" , cronType ) ) ; } } | Creates CronDefinition instance matching cronType specification . |
27,584 | public int mapTo ( final int dayOfWeek , final WeekDay targetWeekDayDefinition ) { if ( firstDayZero && targetWeekDayDefinition . isFirstDayZero ( ) ) { return bothSameStartOfRange ( 0 , 6 , this , targetWeekDayDefinition ) . apply ( dayOfWeek ) ; } if ( ! firstDayZero && ! targetWeekDayDefinition . isFirstDayZero ( ) ) { return bothSameStartOfRange ( 1 , 7 , this , targetWeekDayDefinition ) . apply ( dayOfWeek ) ; } if ( targetWeekDayDefinition . isFirstDayZero ( ) ) { return mapTo ( dayOfWeek , new WeekDay ( targetWeekDayDefinition . getMondayDoWValue ( ) + 1 , false ) ) - 1 ; } else { return mapTo ( dayOfWeek , new WeekDay ( targetWeekDayDefinition . getMondayDoWValue ( ) - 1 , true ) ) + 1 ; } } | Maps given WeekDay to representation hold by this instance . |
27,585 | public static int weekDayMapping ( final WeekDay source , final WeekDay target , final int weekday ) { return source . mapTo ( weekday , target ) ; } | Performs weekday mapping between two weekday definitions . |
27,586 | public CronField parse ( final String expression ) { return new CronField ( field , parser . parse ( expression ) , constraints ) ; } | Parses a String cron expression . |
27,587 | private void buildPossibleExpressions ( final CronDefinition cronDefinition ) { final List < CronParserField > sortedExpression = cronDefinition . getFieldDefinitions ( ) . stream ( ) . map ( this :: toCronParserField ) . sorted ( CronParserField . createFieldTypeComparator ( ) ) . collect ( Collectors . toList ( ) ) ; List < CronParserField > tempExpression = sortedExpression ; while ( lastFieldIsOptional ( tempExpression ) ) { int expressionLength = tempExpression . size ( ) - 1 ; ArrayList < CronParserField > possibleExpression = new ArrayList < > ( tempExpression . subList ( 0 , expressionLength ) ) ; expressions . put ( expressionLength , possibleExpression ) ; tempExpression = possibleExpression ; } expressions . put ( sortedExpression . size ( ) , sortedExpression ) ; } | Build possible cron expressions from definitions . One is built for sure . A second one may be build if last field is optional . |
27,588 | public FieldExpression parse ( final String expression ) { if ( ! StringUtils . containsAny ( expression , SPECIAL_CHARS_MINUS_STAR ) ) { if ( expression . contains ( QUESTION_MARK_STRING ) && ! fieldConstraints . getSpecialChars ( ) . contains ( QUESTION_MARK ) ) { throw new IllegalArgumentException ( "Invalid expression: " + expression ) ; } return noSpecialCharsNorStar ( expression ) ; } else { final String [ ] array = expression . split ( "," ) ; if ( array . length > 1 ) { return commaSplitResult ( array ) ; } else { final String [ ] splitted = expression . split ( "-" ) ; if ( expression . contains ( "-" ) && splitted . length != 2 ) { throw new IllegalArgumentException ( "Missing values for range: " + expression ) ; } return splitted [ 0 ] . equalsIgnoreCase ( L_STRING ) ? parseOnWithL ( splitted [ 0 ] , mapToIntegerFieldValue ( splitted [ 1 ] ) ) : dashSplitResult ( expression , splitted ) ; } } } | Parse given expression for a single cron field . |
27,589 | protected int stringToInt ( final String exp ) { final Integer value = fieldConstraints . getStringMappingValue ( exp ) ; if ( value != null ) { return value ; } else { try { return Integer . parseInt ( exp ) ; } catch ( final NumberFormatException e ) { final String invalidChars = new StringValidations ( fieldConstraints ) . removeValidChars ( exp ) ; throw new IllegalArgumentException ( String . format ( "Invalid chars in expression! Expression: %s Invalid chars: %s" , exp , invalidChars ) ) ; } } } | Maps string expression to integer . If no mapping is found will try to parse String as Integer |
27,590 | public Optional < ZonedDateTime > nextExecution ( final ZonedDateTime date ) { Preconditions . checkNotNull ( date ) ; try { ZonedDateTime nextMatch = nextClosestMatch ( date ) ; if ( nextMatch . equals ( date ) ) { nextMatch = nextClosestMatch ( date . plusSeconds ( 1 ) ) ; } return Optional . of ( nextMatch ) ; } catch ( final NoSuchValueException e ) { return Optional . empty ( ) ; } } | Provide nearest date for next execution . |
27,591 | private ZonedDateTime nextClosestMatch ( final ZonedDateTime date ) throws NoSuchValueException { ExecutionTimeResult result = new ExecutionTimeResult ( date , false ) ; for ( int i = 0 ; i < MAX_ITERATIONS ; i ++ ) { result = potentialNextClosestMatch ( result . getTime ( ) ) ; if ( result . isMatch ( ) ) { return result . getTime ( ) ; } if ( result . getTime ( ) . getYear ( ) - date . getYear ( ) > 100 ) { throw new NoSuchValueException ( ) ; } } throw new NoSuchValueException ( ) ; } | If date is not match will return next closest match . If date is match will return this date . |
27,592 | private ZonedDateTime previousClosestMatch ( final ZonedDateTime date ) throws NoSuchValueException { ExecutionTimeResult result = new ExecutionTimeResult ( date , false ) ; for ( int i = 0 ; i < MAX_ITERATIONS ; i ++ ) { result = potentialPreviousClosestMatch ( result . getTime ( ) ) ; if ( result . isMatch ( ) ) { return result . getTime ( ) ; } } throw new NoSuchValueException ( ) ; } | If date is not match will return previous closest match . If date is match will return this date . |
27,593 | public Optional < ZonedDateTime > lastExecution ( final ZonedDateTime date ) { Preconditions . checkNotNull ( date ) ; try { ZonedDateTime previousMatch = previousClosestMatch ( date ) ; if ( previousMatch . equals ( date ) ) { previousMatch = previousClosestMatch ( date . minusSeconds ( 1 ) ) ; } return Optional . of ( previousMatch ) ; } catch ( final NoSuchValueException e ) { return Optional . empty ( ) ; } } | Provide nearest date for last execution . |
27,594 | public boolean isMatch ( ZonedDateTime date ) { final boolean isSecondGranularity = cronDefinition . containsFieldDefinition ( SECOND ) ; if ( isSecondGranularity ) { date = date . truncatedTo ( SECONDS ) ; } else { date = date . truncatedTo ( ChronoUnit . MINUTES ) ; } final Optional < ZonedDateTime > last = lastExecution ( date ) ; if ( last . isPresent ( ) ) { final Optional < ZonedDateTime > next = nextExecution ( last . get ( ) ) ; if ( next . isPresent ( ) ) { return next . get ( ) . equals ( date ) ; } else { boolean everythingInRange = false ; try { everythingInRange = dateValuesInExpectedRanges ( nextClosestMatch ( date ) , date ) ; } catch ( final NoSuchValueException ignored ) { } try { everythingInRange = dateValuesInExpectedRanges ( previousClosestMatch ( date ) , date ) ; } catch ( final NoSuchValueException ignored ) { } return everythingInRange ; } } return false ; } | Provide feedback if a given date matches the cron expression . |
27,595 | public synchronized EmbeddedElastic start ( ) throws IOException , InterruptedException { if ( ! started ) { started = true ; installElastic ( ) ; startElastic ( ) ; createRestClient ( ) ; createTemplates ( ) ; createIndices ( ) ; } return this ; } | Downloads Elasticsearch with specified plugins setups them and starts |
27,596 | @ SuppressWarnings ( "unchecked" ) public static < T extends Comparable < ? super T > > ComparatorCompat < T > naturalOrder ( ) { return ( ComparatorCompat < T > ) NATURAL_ORDER ; } | Returns a comparator with natural order . |
27,597 | @ SuppressWarnings ( "unchecked" ) public static < T extends Comparable < ? super T > > ComparatorCompat < T > reverseOrder ( ) { return ( ComparatorCompat < T > ) REVERSE_ORDER ; } | Returns a comparator with reverse order . |
27,598 | public static < T , U > ComparatorCompat < T > comparing ( final Function < ? super T , ? extends U > keyExtractor , final Comparator < ? super U > keyComparator ) { Objects . requireNonNull ( keyExtractor ) ; Objects . requireNonNull ( keyComparator ) ; return new ComparatorCompat < T > ( new Comparator < T > ( ) { public int compare ( T t1 , T t2 ) { final U u1 = keyExtractor . apply ( t1 ) ; final U u2 = keyExtractor . apply ( t2 ) ; return keyComparator . compare ( u1 , u2 ) ; } } ) ; } | Returns a comparator that uses a function that extracts a sort key to be compared with the specified comparator . |
27,599 | public ComparatorCompat < T > thenComparing ( final Comparator < ? super T > other ) { return new ComparatorCompat < T > ( thenComparing ( comparator , other ) ) ; } | Adds the given comparator to the chain . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.