idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
25,000
public static < Item extends IItem > void restoreSubItemSelectionStatesForAlternativeStateManagement ( Item item , List < String > selectedItems ) { if ( item instanceof IExpandable && ! ( ( IExpandable ) item ) . isExpanded ( ) && ( ( IExpandable ) item ) . getSubItems ( ) != null ) { List < Item > subItems = ( List < Item > ) ( ( IExpandable < Item , ? > ) item ) . getSubItems ( ) ; for ( int i = 0 , size = subItems . size ( ) ; i < size ; i ++ ) { Item subItem = subItems . get ( i ) ; String id = String . valueOf ( subItem . getIdentifier ( ) ) ; if ( selectedItems != null && selectedItems . contains ( id ) ) { subItem . withSetSelected ( true ) ; } restoreSubItemSelectionStatesForAlternativeStateManagement ( subItem , selectedItems ) ; } } }
internal method to restore the selection state of subItems
25,001
public static < Item extends IItem > void findSubItemSelections ( Item item , List < String > selections ) { if ( item instanceof IExpandable && ! ( ( IExpandable ) item ) . isExpanded ( ) && ( ( IExpandable ) item ) . getSubItems ( ) != null ) { List < Item > subItems = ( List < Item > ) ( ( IExpandable < Item , ? > ) item ) . getSubItems ( ) ; for ( int i = 0 , size = subItems . size ( ) ; i < size ; i ++ ) { Item subItem = subItems . get ( i ) ; String id = String . valueOf ( subItem . getIdentifier ( ) ) ; if ( subItem . isSelected ( ) ) { selections . add ( id ) ; } findSubItemSelections ( subItem , selections ) ; } } }
internal method to find all selections from subItems and sub sub items so we can save those inside our savedInstanceState
25,002
public static < Item extends IItem > void addAllSubItems ( Item item , List < Item > items ) { if ( item instanceof IExpandable && ! ( ( IExpandable ) item ) . isExpanded ( ) && ( ( IExpandable ) item ) . getSubItems ( ) != null ) { List < Item > subItems = ( List < Item > ) ( ( IExpandable < Item , ? > ) item ) . getSubItems ( ) ; Item subItem ; for ( int i = 0 , size = subItems . size ( ) ; i < size ; i ++ ) { subItem = subItems . get ( i ) ; items . add ( subItem ) ; addAllSubItems ( subItem , items ) ; } } }
Gets all subItems from a given parent item
25,003
public < A extends IAdapter < Item > > FastAdapter < Item > addAdapter ( int index , A adapter ) { mAdapters . add ( index , adapter ) ; adapter . withFastAdapter ( this ) ; adapter . mapPossibleTypes ( adapter . getAdapterItems ( ) ) ; for ( int i = 0 ; i < mAdapters . size ( ) ; i ++ ) { mAdapters . get ( i ) . setOrder ( i ) ; } cacheSizes ( ) ; return this ; }
add s a new adapter at the specific position
25,004
public IAdapter < Item > adapter ( int order ) { if ( mAdapters . size ( ) <= order ) { return null ; } return mAdapters . get ( order ) ; }
Tries to get an adapter by a specific order
25,005
public FastAdapter < Item > withSelectable ( boolean selectable ) { if ( selectable ) { addExtension ( mSelectExtension ) ; } else { mExtensions . remove ( mSelectExtension . getClass ( ) ) ; } mSelectExtension . withSelectable ( selectable ) ; return this ; }
Set to true if you want the items to be selectable . By default no items are selectable
25,006
@ SuppressWarnings ( "unchecked" ) public void registerTypeInstance ( Item item ) { if ( getTypeInstanceCache ( ) . register ( item ) ) { if ( item instanceof IHookable ) { withEventHooks ( ( ( IHookable < Item > ) item ) . getEventHooks ( ) ) ; } } }
register a new type into the TypeInstances to be able to efficiently create thew ViewHolders
25,007
@ SuppressWarnings ( "unchecked" ) public RecyclerView . ViewHolder onCreateViewHolder ( ViewGroup parent , int viewType ) { if ( mVerbose ) Log . v ( TAG , "onCreateViewHolder: " + viewType ) ; final RecyclerView . ViewHolder holder = mOnCreateViewHolderListener . onPreCreateViewHolder ( this , parent , viewType ) ; holder . itemView . setTag ( R . id . fastadapter_item_adapter , FastAdapter . this ) ; if ( mAttachDefaultListeners ) { EventHookUtil . attachToView ( fastAdapterViewClickListener , holder , holder . itemView ) ; EventHookUtil . attachToView ( fastAdapterViewLongClickListener , holder , holder . itemView ) ; EventHookUtil . attachToView ( fastAdapterViewTouchListener , holder , holder . itemView ) ; } return mOnCreateViewHolderListener . onPostCreateViewHolder ( this , holder ) ; }
Creates the ViewHolder by the viewType
25,008
@ SuppressWarnings ( "unchecked" ) public void onBindViewHolder ( final RecyclerView . ViewHolder holder , int position ) { if ( mLegacyBindViewMode ) { if ( mVerbose ) { Log . v ( TAG , "onBindViewHolderLegacy: " + position + "/" + holder . getItemViewType ( ) + " isLegacy: true" ) ; } holder . itemView . setTag ( R . id . fastadapter_item_adapter , this ) ; mOnBindViewHolderListener . onBindViewHolder ( holder , position , Collections . EMPTY_LIST ) ; } }
Binds the data to the created ViewHolder and sets the listeners to the holder . itemView Note that you should use the onBindViewHolder ( RecyclerView . ViewHolder holder int position List payloads as it allows you to implement a more efficient adapter implementation
25,009
public void onBindViewHolder ( RecyclerView . ViewHolder holder , int position , List < Object > payloads ) { if ( ! mLegacyBindViewMode ) { if ( mVerbose ) Log . v ( TAG , "onBindViewHolder: " + position + "/" + holder . getItemViewType ( ) + " isLegacy: false" ) ; holder . itemView . setTag ( R . id . fastadapter_item_adapter , this ) ; mOnBindViewHolderListener . onBindViewHolder ( holder , position , payloads ) ; } super . onBindViewHolder ( holder , position , payloads ) ; }
Binds the data to the created ViewHolder and sets the listeners to the holder . itemView
25,010
public void onViewRecycled ( RecyclerView . ViewHolder holder ) { if ( mVerbose ) Log . v ( TAG , "onViewRecycled: " + holder . getItemViewType ( ) ) ; super . onViewRecycled ( holder ) ; mOnBindViewHolderListener . unBindViewHolder ( holder , holder . getAdapterPosition ( ) ) ; }
Unbinds the data to the already existing ViewHolder and removes the listeners from the holder . itemView
25,011
public Item getItem ( int position ) { if ( position < 0 || position >= mGlobalSize ) { return null ; } int index = floorIndex ( mAdapterSizes , position ) ; return mAdapterSizes . valueAt ( index ) . getAdapterItem ( position - mAdapterSizes . keyAt ( index ) ) ; }
gets the IItem by a position from all registered adapters
25,012
public RelativeInfo < Item > getRelativeInfo ( int position ) { if ( position < 0 || position >= getItemCount ( ) ) { return new RelativeInfo < > ( ) ; } RelativeInfo < Item > relativeInfo = new RelativeInfo < > ( ) ; int index = floorIndex ( mAdapterSizes , position ) ; if ( index != - 1 ) { relativeInfo . item = mAdapterSizes . valueAt ( index ) . getAdapterItem ( position - mAdapterSizes . keyAt ( index ) ) ; relativeInfo . adapter = mAdapterSizes . valueAt ( index ) ; relativeInfo . position = position ; } return relativeInfo ; }
Internal method to get the Item as ItemHolder which comes with the relative position within its adapter Finds the responsible adapter for the given position
25,013
public IAdapter < Item > getAdapter ( int position ) { if ( position < 0 || position >= mGlobalSize ) { return null ; } if ( mVerbose ) Log . v ( TAG , "getAdapter" ) ; return mAdapterSizes . valueAt ( floorIndex ( mAdapterSizes , position ) ) ; }
Gets the adapter for the given position
25,014
protected void cacheSizes ( ) { mAdapterSizes . clear ( ) ; int size = 0 ; for ( IAdapter < Item > adapter : mAdapters ) { if ( adapter . getAdapterItemCount ( ) > 0 ) { mAdapterSizes . append ( size , adapter ) ; size = size + adapter . getAdapterItemCount ( ) ; } } if ( size == 0 && mAdapters . size ( ) > 0 ) { mAdapterSizes . append ( 0 , mAdapters . get ( 0 ) ) ; } mGlobalSize = size ; }
we cache the sizes of our adapters so get accesses are faster
25,015
@ SuppressWarnings ( "unchecked" ) public static < Item extends IItem > Triple < Boolean , Item , Integer > recursiveSub ( IAdapter < Item > lastParentAdapter , int lastParentPosition , IExpandable parent , AdapterPredicate < Item > predicate , boolean stopOnMatch ) { if ( ! parent . isExpanded ( ) && parent . getSubItems ( ) != null ) { for ( int ii = 0 ; ii < parent . getSubItems ( ) . size ( ) ; ii ++ ) { Item sub = ( Item ) parent . getSubItems ( ) . get ( ii ) ; if ( predicate . apply ( lastParentAdapter , lastParentPosition , sub , - 1 ) && stopOnMatch ) { return new Triple < > ( true , sub , null ) ; } if ( sub instanceof IExpandable ) { Triple < Boolean , Item , Integer > res = FastAdapter . recursiveSub ( lastParentAdapter , lastParentPosition , ( IExpandable ) sub , predicate , stopOnMatch ) ; if ( res . first ) { return res ; } } } } return new Triple < > ( false , null , null ) ; }
Util function which recursively iterates over all items of a IExpandable parent if and only if it is expanded and has subItems This is usually only used in
25,016
public FastAdapter < Item > getFastAdapter ( RecyclerView . ViewHolder viewHolder ) { Object tag = viewHolder . itemView . getTag ( R . id . fastadapter_item_adapter ) ; if ( tag instanceof FastAdapter ) { return ( FastAdapter < Item > ) tag ; } return null ; }
Helper method to get the FastAdapter from this ViewHolder
25,017
public Item getItem ( RecyclerView . ViewHolder viewHolder ) { FastAdapter < Item > adapter = getFastAdapter ( viewHolder ) ; if ( adapter == null ) { return null ; } int pos = adapter . getHolderAdapterPosition ( viewHolder ) ; if ( pos != RecyclerView . NO_POSITION ) { return adapter . getItem ( pos ) ; } return null ; }
helper method to get the item for this ViewHolder
25,018
private static Drawable getRippleMask ( int color , int radius ) { float [ ] outerRadius = new float [ 8 ] ; Arrays . fill ( outerRadius , radius ) ; RoundRectShape r = new RoundRectShape ( outerRadius , null , null ) ; ShapeDrawable shapeDrawable = new ShapeDrawable ( r ) ; shapeDrawable . getPaint ( ) . setColor ( color ) ; return shapeDrawable ; }
helper to create an ripple mask with the given color and radius
25,019
private static StateListDrawable getStateListDrawable ( int normalColor , int pressedColor ) { StateListDrawable states = new StateListDrawable ( ) ; states . addState ( new int [ ] { android . R . attr . state_pressed } , new ColorDrawable ( pressedColor ) ) ; states . addState ( new int [ ] { android . R . attr . state_focused } , new ColorDrawable ( pressedColor ) ) ; states . addState ( new int [ ] { android . R . attr . state_activated } , new ColorDrawable ( pressedColor ) ) ; states . addState ( new int [ ] { } , new ColorDrawable ( normalColor ) ) ; return states ; }
helper to create an StateListDrawable for the given normal and pressed color
25,020
public static Set < IItem > getSelectedItems ( FastAdapter adapter ) { Set < IItem > selections = new HashSet < > ( ) ; int length = adapter . getItemCount ( ) ; List < IItem > items = new ArrayList < > ( ) ; for ( int i = 0 ; i < length ; i ++ ) { items . add ( adapter . getItem ( i ) ) ; } updateSelectedItemsWithCollapsed ( selections , items ) ; return selections ; }
returns a set of selected items regardless of their visibility
25,021
public static List < IItem > getAllItems ( List < IItem > items , boolean countHeaders , IPredicate predicate ) { return getAllItems ( items , countHeaders , false , predicate ) ; }
retrieves a flat list of the items in the provided list respecting subitems regardless of there current visibility
25,022
public static < T extends IItem & IExpandable > int countSelectedSubItems ( final FastAdapter adapter , T header ) { SelectExtension extension = ( SelectExtension ) adapter . getExtension ( SelectExtension . class ) ; if ( extension != null ) { Set < IItem > selections = extension . getSelectedItems ( ) ; return countSelectedSubItems ( selections , header ) ; } return 0 ; }
counts the selected items in the adapter underneath an expandable item recursively
25,023
public static List < IItem > deleteSelected ( final FastAdapter fastAdapter , final ExpandableExtension expandableExtension , boolean notifyParent , boolean deleteEmptyHeaders ) { List < IItem > deleted = new ArrayList < > ( ) ; LinkedList < IItem > selectedItems = new LinkedList < > ( getSelectedItems ( fastAdapter ) ) ; IItem item , parent ; int pos , parentPos ; boolean expanded ; ListIterator < IItem > it = selectedItems . listIterator ( ) ; while ( it . hasNext ( ) ) { item = it . next ( ) ; pos = fastAdapter . getPosition ( item ) ; parent = getParent ( item ) ; if ( parent != null ) { parentPos = fastAdapter . getPosition ( parent ) ; boolean success = ( ( IExpandable ) parent ) . getSubItems ( ) . remove ( item ) ; if ( parentPos != - 1 && ( ( IExpandable ) parent ) . isExpanded ( ) ) { expandableExtension . notifyAdapterSubItemsChanged ( parentPos , ( ( IExpandable ) parent ) . getSubItems ( ) . size ( ) + 1 ) ; } if ( parentPos != - 1 && notifyParent ) { expanded = ( ( IExpandable ) parent ) . isExpanded ( ) ; fastAdapter . notifyAdapterItemChanged ( parentPos ) ; if ( expanded ) { expandableExtension . expand ( parentPos ) ; } } deleted . add ( item ) ; if ( deleteEmptyHeaders && ( ( IExpandable ) parent ) . getSubItems ( ) . size ( ) == 0 ) { it . add ( parent ) ; it . previous ( ) ; } } else if ( pos != - 1 ) { IAdapter adapter = fastAdapter . getAdapter ( pos ) ; boolean success = false ; if ( adapter instanceof IItemAdapter ) { success = ( ( IItemAdapter ) adapter ) . remove ( pos ) != null ; } boolean isHeader = item instanceof IExpandable && ( ( IExpandable ) item ) . getSubItems ( ) != null ; deleted . add ( item ) ; } } return deleted ; }
deletes all selected items from the adapter respecting if the are sub items or not subitems are removed from their parents sublists main items are directly removed
25,024
public static List < IItem > delete ( final FastAdapter fastAdapter , final ExpandableExtension expandableExtension , Collection < Long > identifiersToDelete , boolean notifyParent , boolean deleteEmptyHeaders ) { List < IItem > deleted = new ArrayList < > ( ) ; if ( identifiersToDelete == null || identifiersToDelete . size ( ) == 0 ) { return deleted ; } LinkedList < Long > identifiers = new LinkedList < > ( identifiersToDelete ) ; IItem item , parent ; int pos , parentPos ; boolean expanded ; Long identifier ; ListIterator < Long > it = identifiers . listIterator ( ) ; while ( it . hasNext ( ) ) { identifier = it . next ( ) ; pos = fastAdapter . getPosition ( identifier ) ; item = fastAdapter . getItem ( pos ) ; parent = getParent ( item ) ; if ( parent != null ) { parentPos = fastAdapter . getPosition ( parent ) ; boolean success = ( ( IExpandable ) parent ) . getSubItems ( ) . remove ( item ) ; if ( parentPos != - 1 && ( ( IExpandable ) parent ) . isExpanded ( ) ) { expandableExtension . notifyAdapterSubItemsChanged ( parentPos , ( ( IExpandable ) parent ) . getSubItems ( ) . size ( ) + 1 ) ; } if ( parentPos != - 1 && notifyParent ) { expanded = ( ( IExpandable ) parent ) . isExpanded ( ) ; fastAdapter . notifyAdapterItemChanged ( parentPos ) ; if ( expanded ) { expandableExtension . expand ( parentPos ) ; } } deleted . add ( item ) ; if ( deleteEmptyHeaders && ( ( IExpandable ) parent ) . getSubItems ( ) . size ( ) == 0 ) { it . add ( parent . getIdentifier ( ) ) ; it . previous ( ) ; } } else if ( pos != - 1 ) { IAdapter adapter = fastAdapter . getAdapter ( pos ) ; boolean success = false ; if ( adapter instanceof IItemAdapter ) { success = ( ( IItemAdapter ) adapter ) . remove ( pos ) != null ; if ( success ) { fastAdapter . notifyAdapterItemRemoved ( pos ) ; } } boolean isHeader = item instanceof IExpandable && ( ( IExpandable ) item ) . getSubItems ( ) != null ; deleted . add ( item ) ; } } return deleted ; }
deletes all items in identifiersToDelete collection from the adapter respecting if there are sub items or not subitems are removed from their parents sublists main items are directly removed
25,025
private RecyclerView createRecyclerView ( ) { RecyclerView recyclerView = new RecyclerView ( getContext ( ) ) ; RecyclerView . LayoutParams params = new RecyclerView . LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . MATCH_PARENT ) ; recyclerView . setLayoutParams ( params ) ; setContentView ( recyclerView ) ; return recyclerView ; }
Create the RecyclerView and set it as the dialog view .
25,026
public FastAdapterBottomSheetDialog < Item > withOnPreClickListener ( com . mikepenz . fastadapter . listeners . OnClickListener < Item > onPreClickListener ) { this . mFastAdapter . withOnPreClickListener ( onPreClickListener ) ; return this ; }
Define the OnPreClickListener which will be used for a single item and is called after all internal methods are done
25,027
private View getFirstViewUnobscuredByHeader ( RecyclerView parent , View firstHeader ) { boolean isReverseLayout = mOrientationProvider . isReverseLayout ( parent ) ; int step = isReverseLayout ? - 1 : 1 ; int from = isReverseLayout ? parent . getChildCount ( ) - 1 : 0 ; for ( int i = from ; i >= 0 && i <= parent . getChildCount ( ) - 1 ; i += step ) { View child = parent . getChildAt ( i ) ; if ( ! itemIsObscuredByHeader ( parent , child , firstHeader , mOrientationProvider . getOrientation ( parent ) ) ) { return child ; } } return null ; }
Returns the first item currently in the RecyclerView that is not obscured by a header .
25,028
public Identifiable checkId ( Identifiable item ) { if ( item . getIdentifier ( ) == - 1 ) { item . withIdentifier ( nextId ( item ) ) ; } return item ; }
set an unique identifier for the item which do not have one set already
25,029
public void toggleSelection ( int position ) { if ( mFastAdapter . getItem ( position ) . isSelected ( ) ) { deselect ( position ) ; } else { select ( position ) ; } }
toggles the selection of the item at the given position
25,030
public void select ( Item item , boolean considerSelectableFlag ) { if ( considerSelectableFlag && ! item . isSelectable ( ) ) { return ; } item . withSetSelected ( true ) ; if ( mSelectionListener != null ) { mSelectionListener . onSelectionChanged ( item , true ) ; } }
select s a provided item this won t notify the adapter
25,031
public void deselect ( Iterable < Integer > positions ) { Iterator < Integer > entries = positions . iterator ( ) ; while ( entries . hasNext ( ) ) { deselect ( entries . next ( ) , entries ) ; } }
deselects all items at the positions in the iteratable
25,032
private void style ( View view , int value ) { view . setScaleX ( value ) ; view . setScaleY ( value ) ; view . setAlpha ( value ) ; }
helper method to style the heart view
25,033
public void animateHeart ( View imageLovedOn , View imageLovedOff , boolean on ) { imageLovedOn . setVisibility ( View . VISIBLE ) ; imageLovedOff . setVisibility ( View . VISIBLE ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB_MR1 ) { viewPropertyStartCompat ( imageLovedOff . animate ( ) . scaleX ( on ? 0 : 1 ) . scaleY ( on ? 0 : 1 ) . alpha ( on ? 0 : 1 ) ) ; viewPropertyStartCompat ( imageLovedOn . animate ( ) . scaleX ( on ? 1 : 0 ) . scaleY ( on ? 1 : 0 ) . alpha ( on ? 1 : 0 ) ) ; } }
helper method to animate the heart view
25,034
public void apply ( List items ) { int size = items . size ( ) ; if ( size > 0 ) { if ( comparator != null ) { Collections . sort ( items , comparator ) ; } for ( int i = - 1 ; i < size ; i ++ ) { HeaderItem headerItem ; if ( i == - 1 ) { headerItem = groupingFunction . group ( null , ( Item ) items . get ( i + 1 ) , i ) ; } else if ( i == size - 1 ) { headerItem = groupingFunction . group ( ( Item ) items . get ( i ) , null , i ) ; } else { headerItem = groupingFunction . group ( ( Item ) items . get ( i ) , ( Item ) items . get ( i + 1 ) , i ) ; } if ( headerItem != null ) { items . add ( i + 1 , headerItem ) ; i = i + 1 ; size = size + 1 ; } } } if ( modelAdapter != null ) { modelAdapter . set ( items ) ; } }
call this when your list order has changed or was updated and you have to readd the headres
25,035
static String updateQueryAndParametersIndexes ( String parsedQuery , Map < String , List < Integer > > parameterNamesToIndexes , Map < String , Query . ParameterSetter > parameters , boolean allowArrayParameters ) { List < ArrayParameter > arrayParametersSortedAsc = arrayParametersSortedAsc ( parameterNamesToIndexes , parameters , allowArrayParameters ) ; if ( arrayParametersSortedAsc . isEmpty ( ) ) { return parsedQuery ; } updateParameterNamesToIndexes ( parameterNamesToIndexes , arrayParametersSortedAsc ) ; return updateQueryWithArrayParameters ( parsedQuery , arrayParametersSortedAsc ) ; }
Update both the query and the parameter indexes to include the array parameters .
25,036
static Map < String , List < Integer > > updateParameterNamesToIndexes ( Map < String , List < Integer > > parametersNameToIndex , List < ArrayParameter > arrayParametersSortedAsc ) { for ( Map . Entry < String , List < Integer > > parameterNameToIndexes : parametersNameToIndex . entrySet ( ) ) { List < Integer > newParameterIndex = new ArrayList < > ( parameterNameToIndexes . getValue ( ) . size ( ) ) ; for ( Integer parameterIndex : parameterNameToIndexes . getValue ( ) ) { newParameterIndex . add ( computeNewIndex ( parameterIndex , arrayParametersSortedAsc ) ) ; } parameterNameToIndexes . setValue ( newParameterIndex ) ; } return parametersNameToIndex ; }
Update the indexes of each query parameter
25,037
static int computeNewIndex ( int index , List < ArrayParameter > arrayParametersSortedAsc ) { int newIndex = index ; for ( ArrayParameter arrayParameter : arrayParametersSortedAsc ) { if ( index > arrayParameter . parameterIndex ) { newIndex = newIndex + arrayParameter . parameterCount - 1 ; } else { return newIndex ; } } return newIndex ; }
Compute the new index of a parameter given the index positions of the array parameters .
25,038
private static List < ArrayParameter > arrayParametersSortedAsc ( Map < String , List < Integer > > parameterNamesToIndexes , Map < String , Query . ParameterSetter > parameters , boolean allowArrayParameters ) { List < ArrayParameters . ArrayParameter > arrayParameters = new ArrayList < > ( ) ; for ( Map . Entry < String , Query . ParameterSetter > parameter : parameters . entrySet ( ) ) { if ( parameter . getValue ( ) . parameterCount > 1 ) { if ( ! allowArrayParameters ) { throw new Sql2oException ( "Array parameters are not allowed in batch mode" ) ; } for ( int i : parameterNamesToIndexes . get ( parameter . getKey ( ) ) ) { arrayParameters . add ( new ArrayParameters . ArrayParameter ( i , parameter . getValue ( ) . parameterCount ) ) ; } } } Collections . sort ( arrayParameters ) ; return arrayParameters ; }
List all the array parameters that contains more that 1 parameters . Indeed array parameter below 1 parameter will not change the text query nor the parameter indexes .
25,039
static String updateQueryWithArrayParameters ( String parsedQuery , List < ArrayParameter > arrayParametersSortedAsc ) { if ( arrayParametersSortedAsc . isEmpty ( ) ) { return parsedQuery ; } StringBuilder sb = new StringBuilder ( ) ; Iterator < ArrayParameter > parameterToReplaceIt = arrayParametersSortedAsc . iterator ( ) ; ArrayParameter nextParameterToReplace = parameterToReplaceIt . next ( ) ; int currentIndex = 1 ; for ( char c : parsedQuery . toCharArray ( ) ) { if ( nextParameterToReplace != null && c == '?' ) { if ( currentIndex == nextParameterToReplace . parameterIndex ) { sb . append ( "?" ) ; for ( int i = 1 ; i < nextParameterToReplace . parameterCount ; i ++ ) { sb . append ( ",?" ) ; } if ( parameterToReplaceIt . hasNext ( ) ) { nextParameterToReplace = parameterToReplaceIt . next ( ) ; } else { nextParameterToReplace = null ; } } else { sb . append ( c ) ; } currentIndex ++ ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; }
Change the query to replace ? at each arrayParametersSortedAsc . parameterIndex with ? ? ? .. multiple arrayParametersSortedAsc . parameterCount
25,040
public boolean hasNext ( ) { if ( next != null ) { return true ; } if ( resultSetFinished ) { return false ; } next = safeReadNext ( ) ; if ( next != null ) { return true ; } resultSetFinished = true ; return false ; }
used to note when result set exhausted
25,041
public Object get ( Object propertyName ) { if ( propertyName instanceof CharSequence ) { propertyName = propertyName . toString ( ) ; } if ( propertyName instanceof List ) { Map submap = new HashMap ( ) ; List propertyNames = ( List ) propertyName ; for ( Object currentName : propertyNames ) { if ( currentName != null ) { currentName = currentName . toString ( ) ; if ( containsKey ( currentName ) ) { submap . put ( currentName , get ( currentName ) ) ; } } } return submap ; } if ( NameUtils . isConfigurational ( propertyName . toString ( ) ) ) { return null ; } Object val = null ; MetaProperty mp = metaClass . getMetaProperty ( propertyName . toString ( ) ) ; if ( mp != null ) { val = mp . getProperty ( instance ) ; } return val ; }
Obtains the value of an object s properties on demand using Groovy s MOP .
25,042
protected GenericApplicationContext createApplicationContext ( ApplicationContext parentCtx ) { if ( parentCtx != null && beanFactory != null ) { Assert . isInstanceOf ( DefaultListableBeanFactory . class , beanFactory , "ListableBeanFactory set must be a subclass of DefaultListableBeanFactory" ) ; return new GrailsApplicationContext ( ( DefaultListableBeanFactory ) beanFactory , parentCtx ) ; } if ( beanFactory != null ) { Assert . isInstanceOf ( DefaultListableBeanFactory . class , beanFactory , "ListableBeanFactory set must be a subclass of DefaultListableBeanFactory" ) ; return new GrailsApplicationContext ( ( DefaultListableBeanFactory ) beanFactory ) ; } if ( parentCtx != null ) { return new GrailsApplicationContext ( parentCtx ) ; } return new GrailsApplicationContext ( ) ; }
Creates the ApplicationContext instance . Subclasses can override to customise the used ApplicationContext
25,043
protected void initialiseApplicationContext ( ) { if ( context != null ) { return ; } context = createApplicationContext ( parent ) ; if ( parent != null && classLoader == null ) { trySettingClassLoaderOnContextIfFoundInParent ( parent ) ; } else if ( classLoader != null ) { setClassLoaderOnContext ( classLoader ) ; } Assert . notNull ( context , "ApplicationContext cannot be null" ) ; }
Initialises the ApplicationContext instance .
25,044
public static GrailsApplication lookupApplication ( ServletContext servletContext ) { if ( servletContext == null ) { return null ; } GrailsApplication grailsApplication = ( GrailsApplication ) servletContext . getAttribute ( ApplicationAttributes . APPLICATION ) ; if ( grailsApplication != null ) { return grailsApplication ; } final WebApplicationContext context = WebApplicationContextUtils . getWebApplicationContext ( servletContext ) ; if ( context == null || ! context . containsBean ( GrailsApplication . APPLICATION_ID ) ) { return null ; } return context . getBean ( GrailsApplication . APPLICATION_ID , GrailsApplication . class ) ; }
Looks up a GrailsApplication instance from the ServletContext .
25,045
public static synchronized void runOperations ( ) { try { for ( Runnable shutdownOperation : shutdownOperations ) { try { shutdownOperation . run ( ) ; } catch ( Exception e ) { LOG . warn ( "Error occurred running shutdown operation: " + e . getMessage ( ) , e ) ; } } } finally { shutdownOperations . clear ( ) ; shutdownOperations . addAll ( preservedShutdownOperations ) ; } }
Runs the shutdown operations
25,046
public static synchronized void addOperation ( Runnable runnable , boolean preserveForNextShutdown ) { shutdownOperations . add ( runnable ) ; if ( preserveForNextShutdown ) { preservedShutdownOperations . add ( runnable ) ; } }
Adds a shutdown operation
25,047
public < T > T getStaticPropertyValue ( String propName , Class < T > type ) { return ClassPropertyFetcher . getStaticPropertyValue ( getClazz ( ) , propName , type ) ; }
Get the value of the named static property .
25,048
public static void initialize ( Object instance , Map namedArgs ) { PersistentEntity dc = getDomainClass ( instance ) ; if ( dc == null ) { DataBindingUtils . bindObjectToInstance ( instance , namedArgs ) ; } else { DataBindingUtils . bindObjectToDomainInstance ( dc , instance , namedArgs ) ; DataBindingUtils . assignBidirectionalAssociations ( instance , namedArgs , dc ) ; } autowire ( instance ) ; }
A map based constructor that binds the named arguments to the target instance
25,049
public static void deprecated ( Class < ? > clazz , String methodOrPropName , String version ) { if ( LOG_DEPRECATED ) { deprecated ( "Property or method [" + methodOrPropName + "] of class [" + clazz . getName ( ) + "] is deprecated in [" + version + "] and will be removed in future releases" ) ; } }
Logs warning message about deprecation of specified property or method of some class .
25,050
public static void main ( String [ ] args ) { System . out . println ( version ) ; if ( args . length < 1 ) { initReadme ( ) ; if ( readme != null ) { System . out . println ( readme ) ; } printUsage ( System . out ) ; return ; } String name = args [ args . length - 1 ] ; for ( int i = 0 ; i < args . length - 1 ; i ++ ) { if ( "-R" . equalsIgnoreCase ( args [ i ] ) ) { recursive = true ; } else if ( "-C" . equalsIgnoreCase ( args [ i ] ) ) { doPatch = false ; } else { System . err . println ( "Unknown option passed: " + args [ i ] ) ; printUsage ( System . err ) ; return ; } } new JavadocFixTool ( ) . proceed ( name ) ; }
By default only look in the folder in parameter
25,051
public boolean shouldEncode ( Encoder encoderToApply , EncodingState encodingState ) { return ignoreEncodingState || ( encoderToApply != null && ( encodingState == null || shouldEncodeWith ( encoderToApply , encodingState ) ) ) ; }
Check if the encoder should be used to a input with certain encodingState
25,052
protected void encodeAndWrite ( Encoder encoder , EncodingState newEncodingState , CharSequence input ) throws IOException { Object encoded = encoder . encode ( input ) ; if ( encoded != null ) { String encodedStr = String . valueOf ( encoded ) ; write ( newEncodingState , encodedStr , 0 , encodedStr . length ( ) ) ; } }
Encode and write input to buffer using a non - streaming encoder
25,053
public String getContextPath ( ) { final HttpServletRequest request = getCurrentRequest ( ) ; String appUri = ( String ) request . getAttribute ( GrailsApplicationAttributes . APP_URI_ATTRIBUTE ) ; if ( appUri == null ) { appUri = urlHelper . getContextPath ( request ) ; } return appUri ; }
Returns the context path of the request .
25,054
public boolean isFlowRequest ( ) { GrailsApplication application = getAttributes ( ) . getGrailsApplication ( ) ; Object controllerClassObject = getControllerClass ( ) ; GrailsControllerClass controllerClass = null ; if ( controllerClassObject instanceof GrailsControllerClass ) { controllerClass = ( GrailsControllerClass ) controllerClassObject ; } if ( controllerClass == null ) return false ; String actionName = getActionName ( ) ; if ( actionName == null ) actionName = controllerClass . getDefaultAction ( ) ; if ( actionName == null ) return false ; return false ; }
Returns true if the current executing request is a flow request
25,055
public PropertyEditorRegistry getPropertyEditorRegistry ( ) { final HttpServletRequest servletRequest = getCurrentRequest ( ) ; PropertyEditorRegistry registry = ( PropertyEditorRegistry ) servletRequest . getAttribute ( GrailsApplicationAttributes . PROPERTY_REGISTRY ) ; if ( registry == null ) { registry = new PropertyEditorRegistrySupport ( ) ; PropertyEditorRegistryUtils . registerCustomEditors ( this , registry , RequestContextUtils . getLocale ( servletRequest ) ) ; servletRequest . setAttribute ( GrailsApplicationAttributes . PROPERTY_REGISTRY , registry ) ; } return registry ; }
Obtains the PropertyEditorRegistry instance .
25,056
public static GrailsWebRequest lookup ( HttpServletRequest request ) { GrailsWebRequest webRequest = ( GrailsWebRequest ) request . getAttribute ( GrailsApplicationAttributes . WEB_REQUEST ) ; return webRequest == null ? lookup ( ) : webRequest ; }
Looks up the GrailsWebRequest from the current request .
25,057
public static GrailsWebRequest lookup ( ) { GrailsWebRequest webRequest = null ; RequestAttributes requestAttributes = RequestContextHolder . getRequestAttributes ( ) ; if ( requestAttributes instanceof GrailsWebRequest ) { webRequest = ( GrailsWebRequest ) requestAttributes ; } return webRequest ; }
Looks up the current Grails WebRequest instance
25,058
protected boolean isApplicationClass ( String className ) { for ( String packageName : packagesToFilter ) { if ( className . startsWith ( packageName ) ) return false ; } return true ; }
Whether the given class name is an internal class and should be filtered
25,059
private static final void registerPrimitiveClassPair ( Class < ? > left , Class < ? > right ) { PRIMITIVE_TYPE_COMPATIBLE_CLASSES . put ( left , right ) ; PRIMITIVE_TYPE_COMPATIBLE_CLASSES . put ( right , left ) ; }
Just add two entries to the class compatibility map
25,060
public static Class [ ] getAllInterfaces ( Object instance ) { Assert . notNull ( instance , "Instance must not be null" ) ; return getAllInterfacesForClass ( instance . getClass ( ) ) ; }
Return all interfaces that the given instance implements as array including ones implemented by superclasses .
25,061
public static boolean isPropertyOfType ( Class < ? > clazz , String propertyName , Class < ? > type ) { try { Class < ? > propType = getPropertyType ( clazz , propertyName ) ; return propType != null && propType . equals ( type ) ; } catch ( Exception e ) { return false ; } }
Returns true if the specified property in the specified class is of the specified type
25,062
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static Object getPropertyValueOfNewInstance ( Class clazz , String propertyName , Class < ? > propertyType ) { if ( clazz == null || ! StringUtils . hasText ( propertyName ) ) { return null ; } try { return getPropertyOrStaticPropertyOrFieldValue ( BeanUtils . instantiateClass ( clazz ) , propertyName ) ; } catch ( BeanInstantiationException e ) { return null ; } }
Returns the value of the specified property and type from an instance of the specified Grails class
25,063
public static PropertyDescriptor getPropertyDescriptorForValue ( Object instance , Object propertyValue ) { if ( instance == null || propertyValue == null ) { return null ; } PropertyDescriptor [ ] descriptors = BeanUtils . getPropertyDescriptors ( instance . getClass ( ) ) ; for ( PropertyDescriptor pd : descriptors ) { if ( isAssignableOrConvertibleFrom ( pd . getPropertyType ( ) , propertyValue . getClass ( ) ) ) { Object value ; try { ReflectionUtils . makeAccessible ( pd . getReadMethod ( ) ) ; value = pd . getReadMethod ( ) . invoke ( instance ) ; } catch ( Exception e ) { throw new FatalBeanException ( "Problem calling readMethod of " + pd , e ) ; } if ( propertyValue . equals ( value ) ) { return pd ; } } } return null ; }
Retrieves a PropertyDescriptor for the specified instance and property value
25,064
public static Class < ? > getPropertyType ( Class < ? > clazz , String propertyName ) { if ( clazz == null || ! StringUtils . hasText ( propertyName ) ) { return null ; } try { PropertyDescriptor desc = BeanUtils . getPropertyDescriptor ( clazz , propertyName ) ; if ( desc != null ) { return desc . getPropertyType ( ) ; } return null ; } catch ( Exception e ) { return null ; } }
Returns the type of the given property contained within the specified class
25,065
public static PropertyDescriptor [ ] getPropertiesAssignableToType ( Class < ? > clazz , Class < ? > propertySuperType ) { if ( clazz == null || propertySuperType == null ) return new PropertyDescriptor [ 0 ] ; Set < PropertyDescriptor > properties = new HashSet < PropertyDescriptor > ( ) ; PropertyDescriptor descriptor = null ; try { PropertyDescriptor [ ] descriptors = BeanUtils . getPropertyDescriptors ( clazz ) ; for ( int i = 0 ; i < descriptors . length ; i ++ ) { descriptor = descriptors [ i ] ; Class < ? > currentPropertyType = descriptor . getPropertyType ( ) ; if ( propertySuperType . isAssignableFrom ( descriptor . getPropertyType ( ) ) ) { properties . add ( descriptor ) ; } } } catch ( Exception e ) { if ( descriptor == null ) { LOG . error ( String . format ( "Got exception while checking property descriptors for class %s" , clazz . getName ( ) ) , e ) ; } else { LOG . error ( String . format ( "Got exception while checking PropertyDescriptor.propertyType for field %s.%s" , clazz . getName ( ) , descriptor . getName ( ) ) , e ) ; } return new PropertyDescriptor [ 0 ] ; } return properties . toArray ( new PropertyDescriptor [ properties . size ( ) ] ) ; }
Retrieves all the properties of the given class which are assignable to the given type
25,066
@ SuppressWarnings ( "rawtypes" ) public static boolean isMatchBetweenPrimativeAndWrapperTypes ( Class leftType , Class rightType ) { if ( leftType == null ) { throw new NullPointerException ( "Left type is null!" ) ; } if ( rightType == null ) { throw new NullPointerException ( "Right type is null!" ) ; } Class < ? > r = PRIMITIVE_TYPE_COMPATIBLE_CLASSES . get ( leftType ) ; return r == rightType ; }
Detect if left and right types are matching types . In particular test if one is a primitive type and the other is the corresponding Java wrapper type . Primitive and wrapper classes may be passed to either arguments .
25,067
public static boolean isPublicStatic ( Method m ) { final int modifiers = m . getModifiers ( ) ; return Modifier . isPublic ( modifiers ) && Modifier . isStatic ( modifiers ) ; }
Determine whether the method is declared public static
25,068
public static boolean isPublicStatic ( Field f ) { final int modifiers = f . getModifiers ( ) ; return Modifier . isPublic ( modifiers ) && Modifier . isStatic ( modifiers ) ; }
Determine whether the field is declared public static
25,069
public static Object getFieldValue ( Object obj , String name ) { Class < ? > clazz = obj . getClass ( ) ; try { Field f = clazz . getDeclaredField ( name ) ; return f . get ( obj ) ; } catch ( Exception e ) { return null ; } }
Get the value of a declared field on an object
25,070
public static boolean isPublicField ( Object obj , String name ) { Class < ? > clazz = obj . getClass ( ) ; try { Field f = clazz . getDeclaredField ( name ) ; return Modifier . isPublic ( f . getModifiers ( ) ) ; } catch ( NoSuchFieldException e ) { return false ; } }
Work out if the specified object has a public field with the name supplied .
25,071
@ SuppressWarnings ( "rawtypes" ) public static boolean isPropertyInherited ( Class clz , String propertyName ) { if ( clz == null ) return false ; Assert . isTrue ( StringUtils . hasText ( propertyName ) , "Argument [propertyName] cannot be null or blank" ) ; Class < ? > superClass = clz . getSuperclass ( ) ; PropertyDescriptor pd = BeanUtils . getPropertyDescriptor ( superClass , propertyName ) ; if ( pd != null && pd . getReadMethod ( ) != null ) { return true ; } return false ; }
Checks whether the specified property is inherited from a super class
25,072
public static boolean isPropertyGetter ( Method method ) { return ! Modifier . isStatic ( method . getModifiers ( ) ) && Modifier . isPublic ( method . getModifiers ( ) ) && GrailsNameUtils . isGetter ( method . getName ( ) , method . getReturnType ( ) , method . getParameterTypes ( ) ) ; }
Check whether the specified method is a property getter
25,073
@ SuppressWarnings ( "rawtypes" ) public static Collection createConcreteCollection ( Class interfaceType ) { Collection elements ; if ( interfaceType . equals ( List . class ) || interfaceType . equals ( Collection . class ) ) { elements = new ArrayList ( ) ; } else if ( interfaceType . equals ( SortedSet . class ) ) { elements = new TreeSet ( ) ; } else { elements = new HashSet ( ) ; } return elements ; }
Creates a concrete collection for the suppied interface
25,074
@ SuppressWarnings ( "rawtypes" ) public static boolean isSetter ( String name , Class [ ] args ) { if ( ! StringUtils . hasText ( name ) || args == null ) return false ; if ( name . startsWith ( "set" ) ) { if ( args . length != 1 ) return false ; return GrailsNameUtils . isPropertyMethodSuffix ( name . substring ( 3 ) ) ; } return false ; }
Returns true if the name of the method specified and the number of arguments make it a javabean property setter . The name is assumed to be a valid Java method name that is not verified .
25,075
public static boolean isAssignableOrConvertibleFrom ( Class < ? > clazz , Class < ? > type ) { if ( type == null || clazz == null ) { return false ; } if ( type . isPrimitive ( ) ) { Class < ? > primitiveClass = GrailsClassUtils . PRIMITIVE_TYPE_COMPATIBLE_CLASSES . get ( type ) ; if ( primitiveClass == null ) { return false ; } return clazz . isAssignableFrom ( primitiveClass ) ; } return clazz . isAssignableFrom ( type ) ; }
Returns true if the specified clazz parameter is either the same as or is a superclass or superinterface of the specified type parameter . Converts primitive types to compatible class automatically .
25,076
public static String findPropertyNameForValue ( Object target , Object obj ) { MetaClass mc = GroovySystem . getMetaClassRegistry ( ) . getMetaClass ( target . getClass ( ) ) ; List < MetaProperty > metaProperties = mc . getProperties ( ) ; for ( MetaProperty metaProperty : metaProperties ) { if ( isAssignableOrConvertibleFrom ( metaProperty . getType ( ) , obj . getClass ( ) ) ) { Object val = metaProperty . getProperty ( target ) ; if ( val != null && val . equals ( obj ) ) { return metaProperty . getName ( ) ; } } } return null ; }
Locates the name of a property for the given value on the target object using Groovy s meta APIs . Note that this method uses the reference so the incorrect result could be returned for two properties that refer to the same reference . Use with caution .
25,077
public static boolean isClassBelowPackage ( Class < ? > theClass , List < ? > packageList ) { String classPackage = theClass . getPackage ( ) . getName ( ) ; for ( Object packageName : packageList ) { if ( packageName != null ) { if ( classPackage . startsWith ( packageName . toString ( ) ) ) { return true ; } } } return false ; }
Returns whether the specified class is either within one of the specified packages or within a subpackage of one of the packages
25,078
protected void populateParamsForMapping ( GrailsWebRequest webRequest ) { Map dispatchParams = webRequest . getParams ( ) ; String encoding = webRequest . getRequest ( ) . getCharacterEncoding ( ) ; if ( encoding == null ) encoding = "UTF-8" ; for ( Map . Entry < String , Object > entry : params . entrySet ( ) ) { String name = entry . getKey ( ) ; Object param = entry . getValue ( ) ; if ( param instanceof Closure ) { param = evaluateNameForValue ( param ) ; } if ( param instanceof CharSequence ) { param = param . toString ( ) ; } dispatchParams . put ( name , param ) ; } final String viewName = getViewName ( ) ; if ( viewName == null && getURI ( ) == null ) { webRequest . setControllerNamespace ( getNamespace ( ) ) ; webRequest . setControllerName ( getControllerName ( ) ) ; webRequest . setActionName ( getActionName ( ) ) ; } String id = getId ( ) ; if ( ! GrailsStringUtils . isBlank ( id ) ) try { dispatchParams . put ( GrailsWebRequest . ID_PARAMETER , URLDecoder . decode ( id , encoding ) ) ; } catch ( UnsupportedEncodingException e ) { dispatchParams . put ( GrailsWebRequest . ID_PARAMETER , id ) ; } }
Populates request parameters for the given UrlMappingInfo instance using the GrailsWebRequest
25,079
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static void copyExpandoMetaClass ( Class < ? > fromClass , Class < ? > toClass , boolean removeSource ) { MetaClassRegistry registry = getRegistry ( ) ; MetaClass oldMetaClass = registry . getMetaClass ( fromClass ) ; AdaptingMetaClass adapter = null ; ExpandoMetaClass emc ; if ( oldMetaClass instanceof AdaptingMetaClass ) { adapter = ( ( AdaptingMetaClass ) oldMetaClass ) ; emc = ( ExpandoMetaClass ) adapter . getAdaptee ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Obtained adapted MetaClass [" + emc + "] from AdapterMetaClass instance [" + adapter + "]" ) ; } if ( removeSource ) { registry . removeMetaClass ( fromClass ) ; } } else { emc = ( ExpandoMetaClass ) oldMetaClass ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "No adapter MetaClass found, using original [" + emc + "]" ) ; } } ExpandoMetaClass replacement = new ExpandoMetaClass ( toClass , true , true ) ; for ( Object obj : emc . getExpandoMethods ( ) ) { if ( obj instanceof ClosureInvokingMethod ) { ClosureInvokingMethod cim = ( ClosureInvokingMethod ) obj ; Closure callable = cim . getClosure ( ) ; if ( ! cim . isStatic ( ) ) { replacement . setProperty ( cim . getName ( ) , callable ) ; } else { ( ( GroovyObject ) replacement . getProperty ( ExpandoMetaClass . STATIC_QUALIFIER ) ) . setProperty ( cim . getName ( ) , callable ) ; } } } for ( Object o : emc . getExpandoProperties ( ) ) { if ( o instanceof ThreadManagedMetaBeanProperty ) { ThreadManagedMetaBeanProperty mbp = ( ThreadManagedMetaBeanProperty ) o ; replacement . setProperty ( mbp . getName ( ) , mbp . getInitialValue ( ) ) ; } } replacement . initialize ( ) ; if ( adapter == null ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Adding MetaClass for class [" + toClass + "] MetaClass [" + replacement + "]" ) ; } registry . setMetaClass ( toClass , replacement ) ; } else { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Adding MetaClass for class [" + toClass + "] MetaClass [" + replacement + "] with adapter [" + adapter + "]" ) ; } try { Constructor c = adapter . getClass ( ) . getConstructor ( new Class [ ] { MetaClass . class } ) ; MetaClass newAdapter = ( MetaClass ) BeanUtils . instantiateClass ( c , new Object [ ] { replacement } ) ; registry . setMetaClass ( toClass , newAdapter ) ; } catch ( NoSuchMethodException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Exception thrown constructing new MetaClass adapter when reloading: " + e . getMessage ( ) , e ) ; } } } }
Copies the ExpandoMetaClass dynamic methods and properties from one Class to another .
25,080
public void skipPast ( String to ) { this . myIndex = this . mySource . indexOf ( to , this . myIndex ) ; if ( this . myIndex < 0 ) { this . myIndex = this . mySource . length ( ) ; } else { this . myIndex += to . length ( ) ; } }
Skip characters until past the requested string . If it is not found we are left at the end of the source .
25,081
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static < K , V > V getValue ( ConcurrentMap < K , CacheEntry < V > > map , K key , long timeoutMillis , Callable < V > updater , Callable < ? extends CacheEntry > cacheEntryFactory , boolean returnExpiredWhileUpdating , Object cacheRequestObject ) { CacheEntry < V > cacheEntry = map . get ( key ) ; if ( cacheEntry == null ) { try { cacheEntry = cacheEntryFactory . call ( ) ; } catch ( Exception e ) { throw new UpdateException ( e ) ; } CacheEntry < V > previousEntry = map . putIfAbsent ( key , cacheEntry ) ; if ( previousEntry != null ) { cacheEntry = previousEntry ; } } try { return cacheEntry . getValue ( timeoutMillis , updater , returnExpiredWhileUpdating , cacheRequestObject ) ; } catch ( UpdateException e ) { e . rethrowRuntimeException ( ) ; return null ; } }
Gets a value from cache . If the key doesn t exist it will create the value using the updater callback Prevents cache storms with a lock
25,082
public V getValue ( long timeout , Callable < V > updater , boolean returnExpiredWhileUpdating , Object cacheRequestObject ) { if ( ! isInitialized ( ) || hasExpired ( timeout , cacheRequestObject ) ) { boolean lockAcquired = false ; try { long beforeLockingCreatedMillis = createdMillis ; if ( returnExpiredWhileUpdating ) { if ( ! writeLock . tryLock ( ) ) { if ( isInitialized ( ) ) { return getValueWhileUpdating ( cacheRequestObject ) ; } else { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Locking cache for update" ) ; } writeLock . lock ( ) ; } } } else { LOG . debug ( "Locking cache for update" ) ; writeLock . lock ( ) ; } lockAcquired = true ; V value ; if ( ! isInitialized ( ) || shouldUpdate ( beforeLockingCreatedMillis , cacheRequestObject ) ) { try { value = updateValue ( getValue ( ) , updater , cacheRequestObject ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Updating cache for value [{}]" , value ) ; } setValue ( value ) ; } catch ( Exception e ) { throw new UpdateException ( e ) ; } } else { value = getValue ( ) ; resetTimestamp ( false ) ; } return value ; } finally { if ( lockAcquired ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Unlocking cache for update" ) ; } writeLock . unlock ( ) ; } } } else { return getValue ( ) ; } }
gets the current value from the entry and updates it if it s older than timeout
25,083
public static Encoder lookupEncoder ( GrailsApplication grailsApplication , String codecName ) { ApplicationContext ctx = grailsApplication != null ? grailsApplication . getMainContext ( ) : null ; if ( ctx != null ) { try { CodecLookup codecLookup = ctx . getBean ( "codecLookup" , CodecLookup . class ) ; return codecLookup . lookupEncoder ( codecName ) ; } catch ( NoSuchBeanDefinitionException e ) { log . debug ( "codecLookup bean is missing from test context." , e ) ; } } return null ; }
Lookup encoder .
25,084
public void updateConstantMetaClass ( MetaClassRegistryChangeEvent cmcu ) { Class < ? > classToUpdate = cmcu . getClassToUpdate ( ) ; MetaClass newMetaClass = cmcu . getNewMetaClass ( ) ; System . out . println ( "Class [" + classToUpdate + "] updated MetaClass to [" + newMetaClass + "]" ) ; Thread . dumpStack ( ) ; }
Called when the a constant MetaClass is updated . If the new MetaClass is null then the MetaClass is removed . Be careful while this method is executed other updates may happen . If you want this method thread safe you have to take care of that by yourself .
25,085
public static String getPropertyForSetter ( String setterName ) { if ( setterName == null || setterName . length ( ) == 0 ) return null ; if ( setterName . startsWith ( "set" ) ) { String prop = setterName . substring ( 3 ) ; return convertValidPropertyMethodSuffix ( prop ) ; } return null ; }
Returns a property name equivalent for the given setter name or null if it is not a valid setter . If not null or empty the setter name is assumed to be a valid identifier .
25,086
private MethodNode convertToMethodAction ( ClassNode classNode , MethodNode methodNode , SourceUnit source , GeneratorContext context ) { final ClassNode returnType = methodNode . getReturnType ( ) ; Parameter [ ] parameters = methodNode . getParameters ( ) ; for ( Parameter param : parameters ) { if ( param . hasInitialExpression ( ) ) { String paramName = param . getName ( ) ; String methodName = methodNode . getName ( ) ; String initialValue = param . getInitialExpression ( ) . getText ( ) ; String methodDeclaration = methodNode . getText ( ) ; String message = "Parameter [%s] to method [%s] has default value [%s]. " + "Default parameter values are not allowed in controller action methods. ([%s])" ; String formattedMessage = String . format ( message , paramName , methodName , initialValue , methodDeclaration ) ; GrailsASTUtils . error ( source , methodNode , formattedMessage ) ; } } MethodNode method = null ; if ( methodNode . getParameters ( ) . length > 0 ) { final BlockStatement methodCode = new BlockStatement ( ) ; final BlockStatement codeToHandleAllowedMethods = getCodeToHandleAllowedMethods ( classNode , methodNode . getName ( ) ) ; final Statement codeToCallOriginalMethod = addOriginalMethodCall ( methodNode , initializeActionParameters ( classNode , methodNode , methodNode . getName ( ) , parameters , source , context ) ) ; methodCode . addStatement ( codeToHandleAllowedMethods ) ; methodCode . addStatement ( codeToCallOriginalMethod ) ; method = new MethodNode ( methodNode . getName ( ) , Modifier . PUBLIC , returnType , ZERO_PARAMETERS , EMPTY_CLASS_ARRAY , methodCode ) ; GrailsASTUtils . copyAnnotations ( methodNode , method ) ; methodNode . addAnnotation ( DELEGATING_METHOD_ANNOATION ) ; annotateActionMethod ( classNode , parameters , method ) ; wrapMethodBodyWithExceptionHandling ( classNode , method ) ; } else { annotateActionMethod ( classNode , parameters , methodNode ) ; } wrapMethodBodyWithExceptionHandling ( classNode , methodNode ) ; return method ; }
Converts a method into a controller action . If the method accepts parameters a no - arg counterpart is created which delegates to the original .
25,087
private boolean doesModulePathIncludeSubstring ( ModuleNode moduleNode , final String substring ) { if ( moduleNode == null ) { return false ; } boolean substringFoundInDescription = false ; String commandObjectModuleDescription = moduleNode . getDescription ( ) ; if ( commandObjectModuleDescription != null ) { substringFoundInDescription = commandObjectModuleDescription . contains ( substring ) ; } return substringFoundInDescription ; }
Checks to see if a Module is defined at a path which includes the specified substring
25,088
public String getViewURI ( GroovyObject controller , String viewName ) { return getViewURI ( getLogicalControllerName ( controller ) , viewName ) ; }
Obtains a view URI of the given controller and view name
25,089
public String getNoSuffixViewURI ( GroovyObject controller , String viewName ) { return getNoSuffixViewURI ( getLogicalControllerName ( controller ) , viewName ) ; }
Obtains a view URI of the given controller and view name without the suffix
25,090
public String getAbsoluteTemplateURI ( String templateName , boolean includeExtension ) { FastStringWriter buf = new FastStringWriter ( ) ; String tmp = templateName . substring ( 1 , templateName . length ( ) ) ; if ( tmp . indexOf ( SLASH ) > - 1 ) { buf . append ( SLASH ) ; int i = tmp . lastIndexOf ( SLASH ) ; buf . append ( tmp . substring ( 0 , i ) ) ; buf . append ( SLASH_UNDR ) ; buf . append ( tmp . substring ( i + 1 , tmp . length ( ) ) ) ; } else { buf . append ( SLASH_UNDR ) ; buf . append ( templateName . substring ( 1 , templateName . length ( ) ) ) ; } if ( includeExtension ) { buf . append ( EXTENSION ) ; } String uri = buf . toString ( ) ; buf . close ( ) ; return uri ; }
Used to resolve template names that are not relative to a controller .
25,091
public String getViewURI ( String controllerName , String viewName ) { FastStringWriter buf = new FastStringWriter ( ) ; return getViewURIInternal ( controllerName , viewName , buf , true ) ; }
Obtains a view URI of the given controller name and view name
25,092
public String getAbsoluteViewURI ( String viewName ) { FastStringWriter buf = new FastStringWriter ( ) ; return getAbsoluteViewURIInternal ( viewName , buf , true ) ; }
Obtains a view URI that is not relative to any given controller
25,093
public String getNoSuffixViewURI ( String controllerName , String viewName ) { FastStringWriter buf = new FastStringWriter ( ) ; return getViewURIInternal ( controllerName , viewName , buf , false ) ; }
Obtains a view URI of the given controller name and view name without the suffix
25,094
public static boolean shouldEncodeWith ( Encoder encoderToApply , EncodingState currentEncodingState ) { if ( isNoneEncoder ( encoderToApply ) ) return false ; if ( currentEncodingState != null && currentEncodingState . getEncoders ( ) != null ) { for ( Encoder encoder : currentEncodingState . getEncoders ( ) ) { if ( isPreviousEncoderSafeOrEqual ( encoderToApply , encoder ) ) { return false ; } } } return true ; }
Checks if encoder should be applied to a input with given encoding state
25,095
public static boolean isPreviousEncoderSafeOrEqual ( Encoder encoderToApply , Encoder previousEncoder ) { return previousEncoder == encoderToApply || ! encoderToApply . isApplyToSafelyEncoded ( ) && previousEncoder . isSafe ( ) && encoderToApply . isSafe ( ) || previousEncoder . getCodecIdentifier ( ) . isEquivalent ( encoderToApply . getCodecIdentifier ( ) ) ; }
Checks if is previous encoder is already safe equal or equivalent
25,096
public static boolean isDomainClass ( URL url ) { if ( url == null ) return false ; return KNOWN_DOMAIN_CLASSES . get ( url . getFile ( ) ) ; }
Checks whether the file referenced by the given url is a domain class
25,097
public static String getClassNameForClassFile ( String rootDir , String path ) { path = path . replace ( "/" , "." ) ; path = path . replace ( '\\' , '.' ) ; path = path . substring ( 0 , path . length ( ) - CLASS_EXTENSION . length ( ) ) ; if ( rootDir != null ) { path = path . substring ( rootDir . length ( ) ) ; } return path ; }
Returns the class name for a compiled class file
25,098
public static boolean isGrailsResource ( Resource r ) { try { String file = r . getURL ( ) . getFile ( ) ; return isGrailsPath ( file ) || file . endsWith ( "GrailsPlugin.groovy" ) ; } catch ( IOException e ) { return false ; } }
Checks whether the specific resources is a Grails resource . A Grails resource is a Groovy or Java class under the grails - app directory
25,099
public static String getPathFromBaseDir ( String path ) { int i = path . indexOf ( "grails-app/" ) ; if ( i > - 1 ) { return path . substring ( i + 11 ) ; } else { try { File baseDir = BuildSettings . BASE_DIR ; String basePath = baseDir != null ? baseDir . getCanonicalPath ( ) : null ; if ( basePath != null ) { String canonicalPath = new File ( path ) . getCanonicalPath ( ) ; return canonicalPath . substring ( basePath . length ( ) + 1 ) ; } } catch ( IOException e ) { } } return null ; }
Gets the path relative to the project base directory .