idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
25,100 | public static String appendPiecesForUri ( String ... pieces ) { if ( pieces == null || pieces . length == 0 ) return "" ; StringBuilder builder = new StringBuilder ( 16 * pieces . length ) ; char previous = 0 ; for ( int i = 0 ; i < pieces . length ; i ++ ) { String piece = pieces [ i ] ; if ( piece != null && piece . length ( ) > 0 ) { for ( int j = 0 , maxlen = piece . length ( ) ; j < maxlen ; j ++ ) { char current = piece . charAt ( j ) ; if ( ! ( previous == '/' && current == '/' ) ) { builder . append ( current ) ; previous = current ; } } if ( i + 1 < pieces . length && previous != '/' ) { builder . append ( '/' ) ; previous = '/' ; } } } return builder . toString ( ) ; } | Takes any number of Strings and appends them into a uri making sure that a forward slash is inserted between each piece and making sure that no duplicate slashes are in the uri |
25,101 | @ SuppressWarnings ( "deprecation" ) protected void initArtefactHandlers ( ) { List < ArtefactHandler > additionalArtefactHandlers = GrailsFactoriesLoader . loadFactories ( ArtefactHandler . class , getClassLoader ( ) ) ; for ( ArtefactHandler artefactHandler : additionalArtefactHandlers ) { registerArtefactHandler ( artefactHandler ) ; } updateArtefactHandlers ( ) ; } | Initialises the default set of ArtefactHandler instances . |
25,102 | protected void configureLoadedClasses ( Class < ? > [ ] classes ) { initArtefactHandlers ( ) ; artefactInfo . clear ( ) ; allArtefactClasses . clear ( ) ; allArtefactClassesArray = null ; allClasses = classes ; log . debug ( "Going to inspect artefact classes." ) ; MetaClassRegistry metaClassRegistry = GroovySystem . getMetaClassRegistry ( ) ; for ( final Class < ? > theClass : classes ) { log . debug ( "Inspecting [" + theClass . getName ( ) + "]" ) ; metaClassRegistry . removeMetaClass ( theClass ) ; if ( allArtefactClasses . contains ( theClass ) ) { continue ; } for ( ArtefactHandler artefactHandler : artefactHandlers ) { if ( artefactHandler . isArtefact ( theClass ) ) { log . debug ( "Adding artefact " + theClass + " of kind " + artefactHandler . getType ( ) ) ; GrailsClass gclass = addArtefact ( artefactHandler . getType ( ) , theClass ) ; allArtefactClasses . add ( theClass ) ; DefaultArtefactInfo info = getArtefactInfo ( artefactHandler . getType ( ) , true ) ; info . addGrailsClass ( gclass ) ; break ; } } } refreshArtefactGrailsClassCaches ( ) ; allArtefactClassesArray = allArtefactClasses . toArray ( new Class [ allArtefactClasses . size ( ) ] ) ; for ( ArtefactHandler artefactHandler : artefactHandlers ) { initializeArtefacts ( artefactHandler ) ; } } | Configures the loaded classes within the GrailsApplication instance using the registered ArtefactHandler instances . |
25,103 | protected int getArtefactCount ( String artefactType ) { ArtefactInfo info = getArtefactInfo ( artefactType ) ; return info == null ? 0 : info . getClasses ( ) . length ; } | Retrieves the number of artefacts registered for the given artefactType as defined by the ArtefactHandler . |
25,104 | public Class < ? > getClassForName ( String className ) { if ( ! StringUtils . hasText ( className ) ) { return null ; } for ( Class < ? > c : allClasses ) { if ( c . getName ( ) . equals ( className ) ) { return c ; } } return null ; } | Retrieves a class from the GrailsApplication for the given name . |
25,105 | public boolean isArtefact ( @ SuppressWarnings ( "rawtypes" ) Class theClazz ) { String className = theClazz . getName ( ) ; for ( Class < ? > artefactClass : allArtefactClasses ) { if ( className . equals ( artefactClass . getName ( ) ) ) { return true ; } } return false ; } | Returns true if the given class is an artefact identified by one of the registered ArtefactHandler instances . Uses class name equality to handle class reloading |
25,106 | public boolean isArtefactOfType ( String artefactType , @ SuppressWarnings ( "rawtypes" ) Class theClazz ) { ArtefactHandler handler = artefactHandlersByName . get ( artefactType ) ; if ( handler == null ) { throw new GrailsConfigurationException ( "Unable to locate arefact handler for specified type: " + artefactType ) ; } return handler . isArtefact ( theClazz ) ; } | Returns true if the specified class is of the given artefact type as defined by the ArtefactHandler . |
25,107 | public GrailsClass getArtefact ( String artefactType , String name ) { ArtefactInfo info = getArtefactInfo ( artefactType ) ; return info == null ? null : info . getGrailsClass ( name ) ; } | Retrieves an artefact for the given type and name . |
25,108 | public GrailsClass addArtefact ( String artefactType , GrailsClass artefactGrailsClass ) { ArtefactHandler handler = artefactHandlersByName . get ( artefactType ) ; if ( handler . isArtefactGrailsClass ( artefactGrailsClass ) ) { DefaultArtefactInfo info = getArtefactInfo ( artefactType , true ) ; info . addGrailsClass ( artefactGrailsClass ) ; info . updateComplete ( ) ; initializeArtefacts ( artefactType ) ; return artefactGrailsClass ; } throw new GrailsConfigurationException ( "Cannot add " + artefactType + " class [" + artefactGrailsClass + "]. It is not a " + artefactType + "!" ) ; } | Adds an artefact of the given type for the given GrailsClass . |
25,109 | public void registerArtefactHandler ( ArtefactHandler handler ) { GrailsApplicationAwareBeanPostProcessor . processAwareInterfaces ( this , handler ) ; artefactHandlersByName . put ( handler . getType ( ) , handler ) ; updateArtefactHandlers ( ) ; } | Registers a new ArtefactHandler that is responsible for identifying and managing a particular artefact type that is defined by some convention . |
25,110 | protected void initializeArtefacts ( ArtefactHandler handler ) { if ( handler == null ) { return ; } ArtefactInfo info = getArtefactInfo ( handler . getType ( ) ) ; if ( info != null ) { handler . initialize ( info ) ; } } | Re - initialize the artefacts of the specified type . This gives handlers a chance to update caches etc . |
25,111 | protected DefaultArtefactInfo getArtefactInfo ( String artefactType , boolean create ) { DefaultArtefactInfo cache = ( DefaultArtefactInfo ) artefactInfo . get ( artefactType ) ; if ( cache == null && create ) { cache = new DefaultArtefactInfo ( ) ; artefactInfo . put ( artefactType , cache ) ; cache . updateComplete ( ) ; } return cache ; } | Get or create the cache of classes for the specified artefact type . |
25,112 | public Object getProperty ( String propertyName ) { final Matcher match = GETCLASSESPROP_PATTERN . matcher ( propertyName ) ; match . find ( ) ; if ( match . matches ( ) ) { String artefactName = GrailsNameUtils . getClassNameRepresentation ( match . group ( 1 ) ) ; if ( artefactHandlersByName . containsKey ( artefactName ) ) { return getArtefacts ( artefactName ) ; } } return super . getProperty ( propertyName ) ; } | Override property access and hit on xxxxClasses to return class arrays of artefacts . |
25,113 | public synchronized void updateComplete ( ) { grailsClassesByName = Collections . unmodifiableMap ( grailsClassesByName ) ; classesByName = Collections . unmodifiableMap ( classesByName ) ; grailsClassesArray = grailsClasses . toArray ( new GrailsClass [ grailsClasses . size ( ) ] ) ; classes = classesByName . values ( ) . toArray ( new Class [ classesByName . size ( ) ] ) ; } | Refresh the arrays generated from the maps . |
25,114 | public static UrlMappingsHolder lookupUrlMappings ( ServletContext servletContext ) { WebApplicationContext wac = WebApplicationContextUtils . getRequiredWebApplicationContext ( servletContext ) ; return ( UrlMappingsHolder ) wac . getBean ( UrlMappingsHolder . BEAN_ID ) ; } | Looks up the UrlMappingsHolder instance |
25,115 | public static View resolveView ( HttpServletRequest request , UrlMappingInfo info , String viewName , ViewResolver viewResolver ) throws Exception { String controllerName = info . getControllerName ( ) ; return WebUtils . resolveView ( request , viewName , controllerName , viewResolver ) ; } | Resolves a view for the given view and UrlMappingInfo instance |
25,116 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static String forwardRequestForUrlMappingInfo ( HttpServletRequest request , HttpServletResponse response , UrlMappingInfo info , Map < String , Object > model , boolean includeParams ) throws ServletException , IOException { String forwardUrl = buildDispatchUrlForMapping ( info , includeParams ) ; for ( Map . Entry < String , Object > entry : model . entrySet ( ) ) { request . setAttribute ( entry . getKey ( ) , entry . getValue ( ) ) ; } RequestDispatcher dispatcher = request . getRequestDispatcher ( forwardUrl ) ; final GrailsWebRequest webRequest = GrailsWebRequest . lookup ( request ) ; webRequest . removeAttribute ( GrailsApplicationAttributes . MODEL_AND_VIEW , 0 ) ; info . configure ( webRequest ) ; webRequest . removeAttribute ( GrailsApplicationAttributes . GRAILS_CONTROLLER_CLASS_AVAILABLE , WebRequest . SCOPE_REQUEST ) ; webRequest . removeAttribute ( UrlMappingsHandlerMapping . MATCHED_REQUEST , WebRequest . SCOPE_REQUEST ) ; webRequest . removeAttribute ( "grailsWebRequestFilter" + OncePerRequestFilter . ALREADY_FILTERED_SUFFIX , WebRequest . SCOPE_REQUEST ) ; dispatcher . forward ( request , response ) ; return forwardUrl ; } | Forwards a request for the given UrlMappingInfo object and model |
25,117 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static IncludedContent includeForUrlMappingInfo ( HttpServletRequest request , HttpServletResponse response , UrlMappingInfo info , Map model , LinkGenerator linkGenerator ) { final String includeUrl = buildDispatchUrlForMapping ( info , true , linkGenerator ) ; return includeForUrlMappingInfoHelper ( includeUrl , request , response , info , model ) ; } | Include whatever the given UrlMappingInfo maps to within the current response |
25,118 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static IncludedContent includeForUrl ( String includeUrl , HttpServletRequest request , HttpServletResponse response , Map model ) { RequestDispatcher dispatcher = request . getRequestDispatcher ( includeUrl ) ; HttpServletResponse wrapped = WrappedResponseHolder . getWrappedResponse ( ) ; response = wrapped != null ? wrapped : response ; WebUtils . exposeIncludeRequestAttributes ( request ) ; Map toRestore = WebUtils . exposeRequestAttributesAndReturnOldValues ( request , model ) ; final GrailsWebRequest webRequest = GrailsWebRequest . lookup ( request ) ; final boolean hasPreviousWebRequest = webRequest != null ; final Object previousControllerClass = hasPreviousWebRequest ? webRequest . getAttribute ( GrailsApplicationAttributes . GRAILS_CONTROLLER_CLASS_AVAILABLE , WebRequest . SCOPE_REQUEST ) : null ; final Object previousMatchedRequest = hasPreviousWebRequest ? webRequest . getAttribute ( UrlMappingsHandlerMapping . MATCHED_REQUEST , WebRequest . SCOPE_REQUEST ) : null ; try { if ( hasPreviousWebRequest ) { webRequest . removeAttribute ( GrailsApplicationAttributes . GRAILS_CONTROLLER_CLASS_AVAILABLE , WebRequest . SCOPE_REQUEST ) ; webRequest . removeAttribute ( UrlMappingsHandlerMapping . MATCHED_REQUEST , WebRequest . SCOPE_REQUEST ) ; webRequest . removeAttribute ( "grailsWebRequestFilter" + OncePerRequestFilter . ALREADY_FILTERED_SUFFIX , WebRequest . SCOPE_REQUEST ) ; } final IncludeResponseWrapper responseWrapper = new IncludeResponseWrapper ( response ) ; try { WrappedResponseHolder . setWrappedResponse ( responseWrapper ) ; WebUtils . clearGrailsWebRequest ( ) ; dispatcher . include ( request , responseWrapper ) ; if ( responseWrapper . getRedirectURL ( ) != null ) { return new IncludedContent ( responseWrapper . getRedirectURL ( ) ) ; } return new IncludedContent ( responseWrapper . getContentType ( ) , responseWrapper . getContent ( ) ) ; } finally { if ( hasPreviousWebRequest ) { WebUtils . storeGrailsWebRequest ( webRequest ) ; if ( webRequest . isActive ( ) ) { webRequest . setAttribute ( GrailsApplicationAttributes . GRAILS_CONTROLLER_CLASS_AVAILABLE , previousControllerClass , WebRequest . SCOPE_REQUEST ) ; webRequest . setAttribute ( UrlMappingsHandlerMapping . MATCHED_REQUEST , previousMatchedRequest , WebRequest . SCOPE_REQUEST ) ; } } WrappedResponseHolder . setWrappedResponse ( wrapped ) ; } } catch ( Exception e ) { throw new ControllerExecutionException ( "Unable to execute include: " + e . getMessage ( ) , e ) ; } finally { WebUtils . cleanupIncludeRequestAttributes ( request , toRestore ) ; } } | Includes the given URL returning the resulting content as a String |
25,119 | public Resource getResource ( String path ) { final Resource descriptorResource = descriptor . getResource ( ) ; try { Resource resource = descriptorResource . createRelative ( "static" + path ) ; if ( resource . exists ( ) ) { return resource ; } } catch ( IOException e ) { return null ; } return null ; } | Resolves a static resource contained within this binary plugin |
25,120 | public Properties getProperties ( final Locale locale ) { Resource url = this . baseResourcesResource ; Properties properties = null ; if ( url != null ) { StaticResourceLoader resourceLoader = new StaticResourceLoader ( ) ; resourceLoader . setBaseResource ( url ) ; ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver ( resourceLoader ) ; try { Resource [ ] resources = resolver . getResources ( '*' + PROPERTIES_EXTENSION ) ; resources = resources . length > 0 ? filterResources ( resources , locale ) : resources ; if ( resources . length > 0 ) { properties = new Properties ( ) ; Arrays . sort ( resources , ( o1 , o2 ) -> { String f1 = o1 . getFilename ( ) ; String f2 = o2 . getFilename ( ) ; int firstUnderscoreCount = StringUtils . countOccurrencesOf ( f1 , "_" ) ; int secondUnderscoreCount = StringUtils . countOccurrencesOf ( f2 , "_" ) ; if ( firstUnderscoreCount == secondUnderscoreCount ) { return 0 ; } else { return firstUnderscoreCount > secondUnderscoreCount ? 1 : - 1 ; } } ) ; loadFromResources ( properties , resources ) ; } } catch ( IOException e ) { return null ; } } return properties ; } | Obtains all properties for this binary plugin for the given locale . |
25,121 | public Class resolveView ( String viewName ) { String extraPath = "/plugins/" + getName ( ) + '-' + getVersion ( ) + '/' ; viewName = viewName . replace ( extraPath , "/" ) ; return precompiledViewMap . get ( viewName ) ; } | Resolves a view for the given view name . |
25,122 | public static Map getOrCreateChildMap ( Map parent , String key ) { Object o = parent . get ( key ) ; if ( o instanceof Map ) { return ( Map ) o ; } return new LinkedHashMap ( ) ; } | Gets a child map of the given parent map or returns an empty map if it doesn t exist |
25,123 | public String getDatasource ( ) { if ( datasourceName == null ) { CharSequence name = getStaticPropertyValue ( DATA_SOURCE , CharSequence . class ) ; datasourceName = name == null ? null : name . toString ( ) ; if ( datasourceName == null ) { datasourceName = DEFAULT_DATA_SOURCE ; } } return datasourceName ; } | If service is transactional then get data source will always apply |
25,124 | protected boolean isDependentOn ( GrailsPlugin plugin , String pluginName ) { String [ ] dependencyNames = plugin . getDependencyNames ( ) ; for ( int i = 0 ; i < dependencyNames . length ; i ++ ) { final String dependencyName = dependencyNames [ i ] ; if ( pluginName . equals ( dependencyName ) ) { return true ; } } return false ; } | Checks whether a plugin is dependent on another plugin with the specified name |
25,125 | private void buildExplicitlyNamedList ( ) { for ( GrailsPlugin plugin : originalPlugins ) { String name = plugin . getName ( ) ; if ( suppliedNames . contains ( name ) ) { explicitlyNamedPlugins . add ( plugin ) ; addedNames . add ( name ) ; } } } | Returns the sublist of the supplied set who are explicitly named either as included or excluded plugins |
25,126 | private void buildNameMap ( ) { nameMap = new HashMap < String , GrailsPlugin > ( ) ; for ( GrailsPlugin plugin : originalPlugins ) { nameMap . put ( plugin . getName ( ) , plugin ) ; } } | Builds a name to plugin map from the original list of plugins supplied |
25,127 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) protected void registerDependency ( List additionalList , GrailsPlugin plugin ) { if ( ! addedNames . contains ( plugin . getName ( ) ) ) { addedNames . add ( plugin . getName ( ) ) ; additionalList . add ( plugin ) ; addPluginDependencies ( additionalList , plugin ) ; } } | Adds a plugin to the additional if this hasn t happened already |
25,128 | public static boolean canUseOriginalForSubSequence ( CharSequence str , int start , int count ) { if ( start != 0 ) return false ; final Class < ? > csqClass = str . getClass ( ) ; return ( csqClass == String . class || csqClass == StringBuilder . class || csqClass == StringBuffer . class ) && count == str . length ( ) ; } | Checks if start == 0 and count == length of CharSequence It does this check only for String StringBuilder and StringBuffer classes which have a fast way to check length |
25,129 | public static void writeCharSequence ( Writer target , CharSequence csq , int start , int end ) throws IOException { final Class < ? > csqClass = csq . getClass ( ) ; if ( csqClass == String . class ) { target . write ( ( String ) csq , start , end - start ) ; } else if ( csqClass == StringBuffer . class ) { char [ ] buf = new char [ end - start ] ; ( ( StringBuffer ) csq ) . getChars ( start , end , buf , 0 ) ; target . write ( buf ) ; } else if ( csqClass == StringBuilder . class ) { char [ ] buf = new char [ end - start ] ; ( ( StringBuilder ) csq ) . getChars ( start , end , buf , 0 ) ; target . write ( buf ) ; } else if ( csq instanceof CharArrayAccessible ) { char [ ] buf = new char [ end - start ] ; ( ( CharArrayAccessible ) csq ) . getChars ( start , end , buf , 0 ) ; target . write ( buf ) ; } else { String str = csq . subSequence ( start , end ) . toString ( ) ; target . write ( str , 0 , str . length ( ) ) ; } } | Writes a CharSequence instance in the most optimal way to the target writer |
25,130 | public static void getChars ( CharSequence csq , int srcBegin , int srcEnd , char dst [ ] , int dstBegin ) { final Class < ? > csqClass = csq . getClass ( ) ; if ( csqClass == String . class ) { ( ( String ) csq ) . getChars ( srcBegin , srcEnd , dst , dstBegin ) ; } else if ( csqClass == StringBuffer . class ) { ( ( StringBuffer ) csq ) . getChars ( srcBegin , srcEnd , dst , dstBegin ) ; } else if ( csqClass == StringBuilder . class ) { ( ( StringBuilder ) csq ) . getChars ( srcBegin , srcEnd , dst , dstBegin ) ; } else if ( csq instanceof CharArrayAccessible ) { ( ( CharArrayAccessible ) csq ) . getChars ( srcBegin , srcEnd , dst , dstBegin ) ; } else { String str = csq . subSequence ( srcBegin , srcEnd ) . toString ( ) ; str . getChars ( 0 , str . length ( ) , dst , dstBegin ) ; } } | Provides an optimized way to copy CharSequence content to target array . Uses getChars method available on String StringBuilder and StringBuffer classes . |
25,131 | public int complete ( final String buffer , final int cursor , final List < CharSequence > candidates ) { checkNotNull ( candidates ) ; List < Completion > completions = new ArrayList < Completion > ( completers . size ( ) ) ; int max = - 1 ; for ( Completer completer : completers ) { Completion completion = new Completion ( candidates ) ; completion . complete ( completer , buffer , cursor ) ; max = Math . max ( max , completion . cursor ) ; completions . add ( completion ) ; } SortedSet < CharSequence > allCandidates = new TreeSet < > ( ) ; for ( Completion completion : completions ) { if ( completion . cursor == max ) { allCandidates . addAll ( completion . candidates ) ; } } candidates . addAll ( allCandidates ) ; return max ; } | Perform a completion operation across all aggregated completers . |
25,132 | protected void appendMapKey ( StringBuilder buffer , Map < String , Object > params ) { if ( params == null || params . isEmpty ( ) ) { buffer . append ( EMPTY_MAP_STRING ) ; buffer . append ( OPENING_BRACKET ) ; } else { buffer . append ( OPENING_BRACKET ) ; Map map = new LinkedHashMap < > ( params ) ; final String requestControllerName = getRequestStateLookupStrategy ( ) . getControllerName ( ) ; if ( map . get ( UrlMapping . ACTION ) != null && map . get ( UrlMapping . CONTROLLER ) == null && map . get ( RESOURCE_PREFIX ) == null ) { Object action = map . remove ( UrlMapping . ACTION ) ; map . put ( UrlMapping . CONTROLLER , requestControllerName ) ; map . put ( UrlMapping . ACTION , action ) ; } if ( map . get ( UrlMapping . NAMESPACE ) == null && map . get ( UrlMapping . CONTROLLER ) == requestControllerName ) { String namespace = getRequestStateLookupStrategy ( ) . getControllerNamespace ( ) ; if ( GrailsStringUtils . isNotEmpty ( namespace ) ) { map . put ( UrlMapping . NAMESPACE , namespace ) ; } } boolean first = true ; for ( Object o : map . entrySet ( ) ) { Map . Entry entry = ( Map . Entry ) o ; Object value = entry . getValue ( ) ; if ( value == null ) continue ; first = appendCommaIfNotFirst ( buffer , first ) ; Object key = entry . getKey ( ) ; if ( RESOURCE_PREFIX . equals ( key ) ) { value = getCacheKeyValueForResource ( value ) ; } appendKeyValue ( buffer , map , key , value ) ; } } buffer . append ( CLOSING_BRACKET ) ; } | Based on DGM toMapString but with StringBuilder instead of StringBuffer |
25,133 | protected Pattern convertToRegex ( String url ) { Pattern regex ; String pattern = null ; try { pattern = url . replace ( "." , "\\." ) ; pattern = pattern . replace ( "+" , "\\+" ) ; int lastSlash = pattern . lastIndexOf ( '/' ) ; String urlRoot = lastSlash > - 1 ? pattern . substring ( 0 , lastSlash ) : pattern ; String urlEnd = lastSlash > - 1 ? pattern . substring ( lastSlash , pattern . length ( ) ) : "" ; pattern = "^" + urlRoot . replace ( "(\\.(*))" , "(\\.[^/]+)?" ) . replaceAll ( "([^\\*])\\*([^\\*])" , "$1[^/]+?$2" ) . replaceAll ( "([^\\*])\\*$" , "$1[^/]+?" ) . replaceAll ( "\\*\\*" , ".*" ) ; if ( "/(*)(\\.(*))" . equals ( urlEnd ) ) { pattern += "/([^/]+)\\.([^/.]+)?" ; } else { pattern += urlEnd . replace ( "(\\.(*))" , "(\\.[^/]+)?" ) . replaceAll ( "([^\\*])\\*([^\\*])" , "$1[^/]+?$2" ) . replaceAll ( "([^\\*])\\*$" , "$1[^/]+?" ) . replaceAll ( "\\*\\*" , ".*" ) . replaceAll ( "\\(\\[\\^\\/\\]\\+\\)\\\\\\." , "([^/.]+?)\\\\." ) . replaceAll ( "\\(\\[\\^\\/\\]\\+\\)\\?\\\\\\." , "([^/.]+?)\\?\\\\." ) ; } pattern += "/??$" ; regex = Pattern . compile ( pattern ) ; } catch ( PatternSyntaxException pse ) { throw new UrlMappingException ( "Error evaluating mapping for pattern [" + pattern + "] from Grails URL mappings: " + pse . getMessage ( ) , pse ) ; } return regex ; } | Converts a Grails URL provides via the UrlMappingData interface to a regular expression . |
25,134 | public UrlMappingInfo match ( String uri ) { for ( Pattern pattern : patterns ) { Matcher m = pattern . matcher ( uri ) ; if ( m . matches ( ) ) { UrlMappingInfo urlInfo = createUrlMappingInfo ( uri , m ) ; if ( urlInfo != null ) { return urlInfo ; } } } return null ; } | Matches the given URI and returns a DefaultUrlMappingInfo instance or null |
25,135 | private Object createRuntimeConstraintEvaluator ( final String name , ConstrainedProperty [ ] constraints ) { if ( constraints == null ) return null ; for ( ConstrainedProperty constraint : constraints ) { if ( constraint . getPropertyName ( ) . equals ( name ) ) { return new Closure ( this ) { private static final long serialVersionUID = - 2404119898659287216L ; public Object call ( Object ... objects ) { GrailsWebRequest webRequest = ( GrailsWebRequest ) RequestContextHolder . currentRequestAttributes ( ) ; return webRequest . getParams ( ) . get ( name ) ; } } ; } } return null ; } | This method will look for a constraint for the given name and return a closure that when executed will attempt to evaluate its value from the bound request parameters at runtime . |
25,136 | private static void doLoadSpringGroovyResources ( RuntimeSpringConfiguration config , GrailsApplication application , GenericApplicationContext context ) { loadExternalSpringConfig ( config , application ) ; if ( context != null ) { springGroovyResourcesBeanBuilder . registerBeans ( context ) ; } } | Attempt to load the beans defined by a BeanBuilder DSL closure in resources . groovy . |
25,137 | public static void loadExternalSpringConfig ( RuntimeSpringConfiguration config , final GrailsApplication application ) { if ( springGroovyResourcesBeanBuilder == null ) { try { Class < ? > groovySpringResourcesClass = null ; try { groovySpringResourcesClass = ClassUtils . forName ( SPRING_RESOURCES_CLASS , application . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { } if ( groovySpringResourcesClass != null ) { reloadSpringResourcesConfig ( config , application , groovySpringResourcesClass ) ; } } catch ( Exception ex ) { LOG . error ( "[RuntimeConfiguration] Unable to load beans from resources.groovy" , ex ) ; } } else { if ( ! springGroovyResourcesBeanBuilder . getSpringConfig ( ) . equals ( config ) ) { springGroovyResourcesBeanBuilder . registerBeans ( config ) ; } } } | Loads any external Spring configuration into the given RuntimeSpringConfiguration object . |
25,138 | protected String resolveCodeWithoutArgumentsFromPlugins ( String code , Locale locale ) { if ( pluginCacheMillis < 0 ) { PropertiesHolder propHolder = getMergedPluginProperties ( locale ) ; String result = propHolder . getProperty ( code ) ; if ( result != null ) { return result ; } } else { String result = findCodeInBinaryPlugins ( code , locale ) ; if ( result != null ) return result ; } return null ; } | Attempts to resolve a String for the code from the list of plugin base names |
25,139 | protected MessageFormat resolveCodeFromPlugins ( String code , Locale locale ) { if ( pluginCacheMillis < 0 ) { PropertiesHolder propHolder = getMergedPluginProperties ( locale ) ; MessageFormat result = propHolder . getMessageFormat ( code , locale ) ; if ( result != null ) { return result ; } } else { MessageFormat result = findMessageFormatInBinaryPlugins ( code , locale ) ; if ( result != null ) return result ; } return null ; } | Attempts to resolve a MessageFormat for the code from the list of plugin base names |
25,140 | public void doRuntimeConfiguration ( RuntimeSpringConfiguration springConfig ) { ApplicationContext context = springConfig . getUnrefreshedApplicationContext ( ) ; AutowireCapableBeanFactory autowireCapableBeanFactory = context . getAutowireCapableBeanFactory ( ) ; if ( autowireCapableBeanFactory instanceof ConfigurableListableBeanFactory ) { ConfigurableListableBeanFactory beanFactory = ( ConfigurableListableBeanFactory ) autowireCapableBeanFactory ; ConversionService existingConversionService = beanFactory . getConversionService ( ) ; ConverterRegistry converterRegistry ; if ( existingConversionService == null ) { GenericConversionService conversionService = new GenericConversionService ( ) ; converterRegistry = conversionService ; beanFactory . setConversionService ( conversionService ) ; } else { converterRegistry = ( ConverterRegistry ) existingConversionService ; } converterRegistry . addConverter ( new Converter < NavigableMap . NullSafeNavigator , Object > ( ) { public Object convert ( NavigableMap . NullSafeNavigator source ) { return null ; } } ) ; } checkInitialised ( ) ; for ( GrailsPlugin plugin : pluginList ) { if ( plugin . supportsCurrentScopeAndEnvironment ( ) && plugin . isEnabled ( context . getEnvironment ( ) . getActiveProfiles ( ) ) ) { plugin . doWithRuntimeConfiguration ( springConfig ) ; } } } | Base implementation that simply goes through the list of plugins and calls doWithRuntimeConfiguration on each |
25,141 | public void doRuntimeConfiguration ( String pluginName , RuntimeSpringConfiguration springConfig ) { checkInitialised ( ) ; GrailsPlugin plugin = getGrailsPlugin ( pluginName ) ; if ( plugin == null ) { throw new PluginException ( "Plugin [" + pluginName + "] not found" ) ; } if ( ! plugin . supportsCurrentScopeAndEnvironment ( ) ) { return ; } if ( ! plugin . isEnabled ( applicationContext . getEnvironment ( ) . getActiveProfiles ( ) ) ) return ; String [ ] dependencyNames = plugin . getDependencyNames ( ) ; doRuntimeConfigurationForDependencies ( dependencyNames , springConfig ) ; String [ ] loadAfters = plugin . getLoadAfterNames ( ) ; for ( String name : loadAfters ) { GrailsPlugin current = getGrailsPlugin ( name ) ; if ( current != null ) { current . doWithRuntimeConfiguration ( springConfig ) ; } } plugin . doWithRuntimeConfiguration ( springConfig ) ; } | Base implementation that will perform runtime configuration for the specified plugin name . |
25,142 | public void doPostProcessing ( ApplicationContext ctx ) { checkInitialised ( ) ; for ( GrailsPlugin plugin : pluginList ) { if ( isPluginDisabledForProfile ( plugin ) ) continue ; if ( plugin . supportsCurrentScopeAndEnvironment ( ) ) { plugin . doWithApplicationContext ( ctx ) ; } } } | Base implementation that will simply go through each plugin and call doWithApplicationContext on each . |
25,143 | public synchronized void flush ( ) { if ( trouble ) { return ; } if ( isDestinationActivated ( ) ) { try { getOut ( ) . flush ( ) ; } catch ( IOException e ) { handleIOException ( e ) ; } } } | Flush the stream . |
25,144 | public static HandlerInterceptor [ ] lookupHandlerInterceptors ( ServletContext servletContext ) { WebApplicationContext wac = WebApplicationContextUtils . getRequiredWebApplicationContext ( servletContext ) ; final Collection < HandlerInterceptor > allHandlerInterceptors = new ArrayList < HandlerInterceptor > ( ) ; WebRequestInterceptor [ ] webRequestInterceptors = lookupWebRequestInterceptors ( servletContext ) ; for ( WebRequestInterceptor webRequestInterceptor : webRequestInterceptors ) { allHandlerInterceptors . add ( new WebRequestHandlerInterceptorAdapter ( webRequestInterceptor ) ) ; } final Collection < HandlerInterceptor > handlerInterceptors = wac . getBeansOfType ( HandlerInterceptor . class ) . values ( ) ; allHandlerInterceptors . addAll ( handlerInterceptors ) ; return allHandlerInterceptors . toArray ( new HandlerInterceptor [ allHandlerInterceptors . size ( ) ] ) ; } | Looks up all of the HandlerInterceptor instances registered for the application |
25,145 | public static WebRequestInterceptor [ ] lookupWebRequestInterceptors ( ServletContext servletContext ) { WebApplicationContext wac = WebApplicationContextUtils . getRequiredWebApplicationContext ( servletContext ) ; final Collection < WebRequestInterceptor > webRequestInterceptors = wac . getBeansOfType ( WebRequestInterceptor . class ) . values ( ) ; return webRequestInterceptors . toArray ( new WebRequestInterceptor [ webRequestInterceptors . size ( ) ] ) ; } | Looks up all of the WebRequestInterceptor instances registered with the application |
25,146 | public static ApplicationContext findApplicationContext ( ServletContext servletContext ) { if ( servletContext == null ) { return ContextLoader . getCurrentWebApplicationContext ( ) ; } return WebApplicationContextUtils . getWebApplicationContext ( servletContext ) ; } | Locates the ApplicationContext returns null if not found |
25,147 | public static View resolveView ( HttpServletRequest request , String viewName , String controllerName , ViewResolver viewResolver ) throws Exception { GrailsWebRequest webRequest = GrailsWebRequest . lookup ( request ) ; Locale locale = webRequest != null ? webRequest . getLocale ( ) : Locale . getDefault ( ) ; return viewResolver . resolveViewName ( addViewPrefix ( viewName , controllerName ) , locale ) ; } | Resolves a view for the given view name and controller name |
25,148 | private static void exposeRequestAttributeIfNotPresent ( ServletRequest request , String name , Object value ) { if ( request . getAttribute ( name ) == null ) { request . setAttribute ( name , value ) ; } } | Expose the specified request attribute if not already present . |
25,149 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static Map < String , Object > fromQueryString ( String queryString ) { Map < String , Object > result = new LinkedHashMap < String , Object > ( ) ; if ( queryString . startsWith ( "?" ) ) queryString = queryString . substring ( 1 ) ; String [ ] pairs = queryString . split ( "&" ) ; for ( String pair : pairs ) { int i = pair . indexOf ( '=' ) ; if ( i > - 1 ) { try { String name = URLDecoder . decode ( pair . substring ( 0 , i ) , "UTF-8" ) ; String value = URLDecoder . decode ( pair . substring ( i + 1 , pair . length ( ) ) , "UTF-8" ) ; Object current = result . get ( name ) ; if ( current instanceof List ) { ( ( List ) current ) . add ( value ) ; } else if ( current != null ) { List multi = new ArrayList ( ) ; multi . add ( current ) ; multi . add ( value ) ; result . put ( name , multi ) ; } else { result . put ( name , value ) ; } } catch ( UnsupportedEncodingException e ) { } } } return result ; } | Takes a query string and returns the results as a map where the values are either a single entry or a list of values |
25,150 | @ SuppressWarnings ( "rawtypes" ) public static String toQueryString ( Map params , String encoding ) throws UnsupportedEncodingException { if ( encoding == null ) encoding = "UTF-8" ; StringBuilder queryString = new StringBuilder ( "?" ) ; for ( Iterator i = params . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) i . next ( ) ; boolean hasMore = i . hasNext ( ) ; boolean wasAppended = appendEntry ( entry , queryString , encoding , "" ) ; if ( hasMore && wasAppended ) queryString . append ( '&' ) ; } return queryString . toString ( ) ; } | Converts the given params into a query string started with ? |
25,151 | @ SuppressWarnings ( "rawtypes" ) public static boolean areFileExtensionsEnabled ( ) { Config config = GrailsWebUtil . currentApplication ( ) . getConfig ( ) ; return config . getProperty ( ENABLE_FILE_EXTENSIONS , Boolean . class , true ) ; } | Returns the value of the grails . mime . file . extensions setting configured in application . groovy |
25,152 | public static void storeGrailsWebRequest ( GrailsWebRequest webRequest ) { RequestContextHolder . setRequestAttributes ( webRequest ) ; webRequest . getRequest ( ) . setAttribute ( GrailsApplicationAttributes . WEB_REQUEST , webRequest ) ; } | Helper method to store the given GrailsWebRequest for the current request . Ensures consistency between RequestContextHolder and the relevant request attribute . This is the preferred means of updating the current web request . |
25,153 | public static void clearGrailsWebRequest ( ) { RequestAttributes reqAttrs = RequestContextHolder . getRequestAttributes ( ) ; if ( reqAttrs != null ) { GrailsWebRequest webRequest = ( GrailsWebRequest ) reqAttrs ; webRequest . getRequest ( ) . removeAttribute ( GrailsApplicationAttributes . WEB_REQUEST ) ; RequestContextHolder . resetRequestAttributes ( ) ; } } | Removes any GrailsWebRequest instance from the current request . |
25,154 | public static String getForwardURI ( HttpServletRequest request ) { String result = ( String ) request . getAttribute ( WebUtils . FORWARD_REQUEST_URI_ATTRIBUTE ) ; if ( GrailsStringUtils . isBlank ( result ) ) result = request . getRequestURI ( ) ; return result ; } | Obtains the forwardURI from the request since Grails uses a forwarding technique for URL mappings . The actual request URI is held within a request attribute |
25,155 | public Object methodMissing ( String name , Object args ) { String str = this . toString ( ) ; return InvokerHelper . invokeMethod ( str , name , args ) ; } | Delegates methodMissing to String object |
25,156 | public File getFile ( ) throws IOException { URL url = getURL ( ) ; return GrailsResourceUtils . getFile ( url , getDescription ( ) ) ; } | This implementation returns a File reference for the underlying class path resource provided that it refers to a file in the file system . |
25,157 | public JSONArray put ( int index , double value ) throws JSONException { put ( index , Double . valueOf ( value ) ) ; return this ; } | Put or replace a double value . If the index is greater than the length of the JSONArray then null elements will be added as necessary to pad it out . |
25,158 | public JSONArray put ( int index , int value ) throws JSONException { put ( index , Integer . valueOf ( value ) ) ; return this ; } | Put or replace an int value . If the index is greater than the length of the JSONArray then null elements will be added as necessary to pad it out . |
25,159 | public JSONArray put ( int index , long value ) throws JSONException { put ( index , Long . valueOf ( value ) ) ; return this ; } | Put or replace a long value . If the index is greater than the length of the JSONArray then null elements will be added as necessary to pad it out . |
25,160 | public Character getChar ( String name ) { Object o = get ( name ) ; if ( o instanceof Character ) { return ( Character ) o ; } if ( o != null ) { String string = o . toString ( ) ; if ( string != null && string . length ( ) == 1 ) { return string . charAt ( 0 ) ; } } return null ; } | Helper method for obtaining Character value from parameter |
25,161 | public Long getLong ( String name ) { Object o = get ( name ) ; if ( o instanceof Number ) { return ( ( Number ) o ) . longValue ( ) ; } if ( o != null ) { try { return Long . parseLong ( o . toString ( ) ) ; } catch ( NumberFormatException e ) { } } return null ; } | Helper method for obtaining long value from parameter |
25,162 | public Short getShort ( String name ) { Object o = get ( name ) ; if ( o instanceof Number ) { return ( ( Number ) o ) . shortValue ( ) ; } if ( o != null ) { try { String string = o . toString ( ) ; if ( string != null ) { return Short . parseShort ( string ) ; } } catch ( NumberFormatException e ) { } } return null ; } | Helper method for obtaining short value from parameter |
25,163 | public Double getDouble ( String name ) { Object o = get ( name ) ; if ( o instanceof Number ) { return ( ( Number ) o ) . doubleValue ( ) ; } if ( o != null ) { try { String string = o . toString ( ) ; if ( string != null ) { return Double . parseDouble ( string ) ; } } catch ( NumberFormatException e ) { } } return null ; } | Helper method for obtaining double value from parameter |
25,164 | public Float getFloat ( String name ) { Object o = get ( name ) ; if ( o instanceof Number ) { return ( ( Number ) o ) . floatValue ( ) ; } if ( o != null ) { try { String string = o . toString ( ) ; if ( string != null ) { return Float . parseFloat ( string ) ; } } catch ( NumberFormatException e ) { } } return null ; } | Helper method for obtaining float value from parameter |
25,165 | public Boolean getBoolean ( String name ) { Object o = get ( name ) ; if ( o instanceof Boolean ) { return ( Boolean ) o ; } if ( o != null ) { try { String string = o . toString ( ) ; if ( string != null ) { return GrailsStringUtils . toBoolean ( string ) ; } } catch ( Exception e ) { } } return null ; } | Helper method for obtaining boolean value from parameter |
25,166 | public Date getDate ( String name , String format ) { Object value = get ( name ) ; if ( value instanceof Date ) { return ( Date ) value ; } if ( value != null ) { try { return new SimpleDateFormat ( format ) . parse ( value . toString ( ) ) ; } catch ( ParseException e ) { } } return null ; } | Obtains a date from the parameter using the given format |
25,167 | public Date date ( String name , Collection < String > formats ) { return getDate ( name , formats ) ; } | Obtains a date for the given parameter name and format |
25,168 | public List getList ( String name ) { Object paramValues = get ( name ) ; if ( paramValues == null ) { return Collections . emptyList ( ) ; } if ( paramValues . getClass ( ) . isArray ( ) ) { return Arrays . asList ( ( Object [ ] ) paramValues ) ; } if ( paramValues instanceof Collection ) { return new ArrayList ( ( Collection ) paramValues ) ; } return Collections . singletonList ( paramValues ) ; } | Helper method for obtaining a list of values from parameter |
25,169 | protected Map < String , ClassNode > getPropertiesToEnsureConstraintsFor ( final ClassNode classNode ) { final Map < String , ClassNode > fieldsToConstrain = new HashMap < String , ClassNode > ( ) ; final List < FieldNode > allFields = classNode . getFields ( ) ; for ( final FieldNode field : allFields ) { if ( ! field . isStatic ( ) ) { final PropertyNode property = classNode . getProperty ( field . getName ( ) ) ; if ( property != null ) { fieldsToConstrain . put ( field . getName ( ) , field . getType ( ) ) ; } } } final Map < String , MethodNode > declaredMethodsMap = classNode . getDeclaredMethodsMap ( ) ; for ( Entry < String , MethodNode > methodEntry : declaredMethodsMap . entrySet ( ) ) { final MethodNode value = methodEntry . getValue ( ) ; if ( ! value . isStatic ( ) && value . isPublic ( ) && classNode . equals ( value . getDeclaringClass ( ) ) && value . getLineNumber ( ) > 0 ) { Parameter [ ] parameters = value . getParameters ( ) ; if ( parameters == null || parameters . length == 0 ) { final String methodName = value . getName ( ) ; if ( methodName . startsWith ( "get" ) ) { final ClassNode returnType = value . getReturnType ( ) ; final String restOfMethodName = methodName . substring ( 3 ) ; final String propertyName = GrailsNameUtils . getPropertyName ( restOfMethodName ) ; fieldsToConstrain . put ( propertyName , returnType ) ; } } } } final ClassNode superClass = classNode . getSuperClass ( ) ; if ( ! superClass . equals ( new ClassNode ( Object . class ) ) ) { fieldsToConstrain . putAll ( getPropertiesToEnsureConstraintsFor ( superClass ) ) ; } return fieldsToConstrain ; } | Retrieves a Map describing all of the properties which need to be constrained for the class represented by classNode . The keys in the Map will be property names and the values are the type of the corresponding property . |
25,170 | public static boolean implementsZeroArgMethod ( ClassNode classNode , String methodName ) { MethodNode method = classNode . getDeclaredMethod ( methodName , Parameter . EMPTY_ARRAY ) ; return method != null && ( method . isPublic ( ) || method . isProtected ( ) ) && ! method . isAbstract ( ) ; } | Tests whether the ClasNode implements the specified method name . |
25,171 | public static ArgumentListExpression createArgumentListFromParameters ( Parameter [ ] parameterTypes , boolean thisAsFirstArgument , Map < String , ClassNode > genericsPlaceholders ) { ArgumentListExpression arguments = new ArgumentListExpression ( ) ; if ( thisAsFirstArgument ) { arguments . addExpression ( new VariableExpression ( "this" ) ) ; } for ( Parameter parameterType : parameterTypes ) { arguments . addExpression ( new VariableExpression ( parameterType . getName ( ) , replaceGenericsPlaceholders ( parameterType . getType ( ) , genericsPlaceholders ) ) ) ; } return arguments ; } | Creates an argument list from the given parameter types . |
25,172 | public static Parameter [ ] getRemainingParameterTypes ( Parameter [ ] parameters ) { if ( parameters . length == 0 ) { return GrailsArtefactClassInjector . ZERO_PARAMETERS ; } Parameter [ ] newParameters = new Parameter [ parameters . length - 1 ] ; System . arraycopy ( parameters , 1 , newParameters , 0 , parameters . length - 1 ) ; return newParameters ; } | Gets the remaining parameters excluding the first parameter in the given list |
25,173 | public static MethodNode addDelegateStaticMethod ( ClassNode classNode , MethodNode delegateMethod ) { ClassExpression classExpression = new ClassExpression ( delegateMethod . getDeclaringClass ( ) ) ; return addDelegateStaticMethod ( classExpression , classNode , delegateMethod ) ; } | Adds a static method call to given class node that delegates to the given method |
25,174 | public static ConstructorNode addDelegateConstructor ( ClassNode classNode , MethodNode constructorMethod , Map < String , ClassNode > genericsPlaceholders ) { BlockStatement constructorBody = new BlockStatement ( ) ; Parameter [ ] constructorParams = getRemainingParameterTypes ( constructorMethod . getParameters ( ) ) ; ArgumentListExpression arguments = createArgumentListFromParameters ( constructorParams , true , genericsPlaceholders ) ; MethodCallExpression constructCallExpression = new MethodCallExpression ( new ClassExpression ( constructorMethod . getDeclaringClass ( ) ) , "initialize" , arguments ) ; constructCallExpression . setMethodTarget ( constructorMethod ) ; ExpressionStatement constructorInitExpression = new ExpressionStatement ( constructCallExpression ) ; if ( constructorParams . length > 0 ) { constructorBody . addStatement ( new ExpressionStatement ( new ConstructorCallExpression ( ClassNode . THIS , GrailsArtefactClassInjector . ZERO_ARGS ) ) ) ; } constructorBody . addStatement ( constructorInitExpression ) ; if ( constructorParams . length == 0 ) { ConstructorNode constructorNode = getDefaultConstructor ( classNode ) ; if ( constructorNode != null ) { List < AnnotationNode > annotations = constructorNode . getAnnotations ( new ClassNode ( GrailsDelegatingConstructor . class ) ) ; if ( annotations . size ( ) == 0 ) { Statement existingBodyCode = constructorNode . getCode ( ) ; if ( existingBodyCode instanceof BlockStatement ) { ( ( BlockStatement ) existingBodyCode ) . addStatement ( constructorInitExpression ) ; } else { constructorNode . setCode ( constructorBody ) ; } } } else { constructorNode = new ConstructorNode ( Modifier . PUBLIC , constructorBody ) ; classNode . addConstructor ( constructorNode ) ; } constructorNode . addAnnotation ( new AnnotationNode ( new ClassNode ( GrailsDelegatingConstructor . class ) ) ) ; return constructorNode ; } else { ConstructorNode cn = findConstructor ( classNode , constructorParams ) ; if ( cn == null ) { cn = new ConstructorNode ( Modifier . PUBLIC , copyParameters ( constructorParams , genericsPlaceholders ) , null , constructorBody ) ; classNode . addConstructor ( cn ) ; } else { List < AnnotationNode > annotations = cn . getAnnotations ( new ClassNode ( GrailsDelegatingConstructor . class ) ) ; if ( annotations . size ( ) == 0 ) { Statement code = cn . getCode ( ) ; constructorBody . addStatement ( code ) ; cn . setCode ( constructorBody ) ; } } ConstructorNode defaultConstructor = getDefaultConstructor ( classNode ) ; if ( defaultConstructor == null ) { classNode . addConstructor ( new ConstructorNode ( Modifier . PUBLIC , new BlockStatement ( ) ) ) ; } cn . addAnnotation ( new AnnotationNode ( new ClassNode ( GrailsDelegatingConstructor . class ) ) ) ; return cn ; } } | Adds or modifies an existing constructor to delegate to the given static constructor method for initialization logic . |
25,175 | public static ConstructorNode findConstructor ( ClassNode classNode , Parameter [ ] constructorParams ) { List < ConstructorNode > declaredConstructors = classNode . getDeclaredConstructors ( ) ; for ( ConstructorNode declaredConstructor : declaredConstructors ) { if ( parametersEqual ( constructorParams , declaredConstructor . getParameters ( ) ) ) { return declaredConstructor ; } } return null ; } | Finds a constructor for the given class node and parameter types |
25,176 | public static ConstructorNode getDefaultConstructor ( ClassNode classNode ) { for ( ConstructorNode cons : classNode . getDeclaredConstructors ( ) ) { if ( cons . getParameters ( ) . length == 0 ) { return cons ; } } return null ; } | Obtains the default constructor for the given class node . |
25,177 | public static boolean isAssignableFrom ( ClassNode superClass , ClassNode childClass ) { ClassNode currentSuper = childClass ; while ( currentSuper != null ) { if ( currentSuper . equals ( superClass ) ) { return true ; } currentSuper = currentSuper . getSuperClass ( ) ; } return false ; } | Determines if the class or interface represented by the superClass argument is either the same as or is a superclass or superinterface of the class or interface represented by the specified subClass parameter . |
25,178 | public static void addExpressionToAnnotationMember ( AnnotationNode annotationNode , String memberName , Expression expression ) { Expression exclude = annotationNode . getMember ( memberName ) ; if ( exclude instanceof ListExpression ) { ( ( ListExpression ) exclude ) . addExpression ( expression ) ; } else if ( exclude != null ) { ListExpression list = new ListExpression ( ) ; list . addExpression ( exclude ) ; list . addExpression ( expression ) ; annotationNode . setMember ( memberName , list ) ; } else { annotationNode . setMember ( memberName , expression ) ; } } | Adds the given expression as a member of the given annotation |
25,179 | public static AnnotationNode addEnhancedAnnotation ( final ClassNode classNode , final String ... enhancedFor ) { final AnnotationNode enhancedAnnotationNode ; final List < AnnotationNode > annotations = classNode . getAnnotations ( ENHANCED_CLASS_NODE ) ; if ( annotations . isEmpty ( ) ) { enhancedAnnotationNode = new AnnotationNode ( ENHANCED_CLASS_NODE ) ; String grailsVersion = getGrailsVersion ( ) ; if ( grailsVersion == null ) { grailsVersion = System . getProperty ( "grails.version" ) ; } if ( grailsVersion != null ) { enhancedAnnotationNode . setMember ( "version" , new ConstantExpression ( grailsVersion ) ) ; } classNode . addAnnotation ( enhancedAnnotationNode ) ; } else { enhancedAnnotationNode = annotations . get ( 0 ) ; } if ( enhancedFor != null && enhancedFor . length > 0 ) { ListExpression enhancedForArray = ( ListExpression ) enhancedAnnotationNode . getMember ( "enhancedFor" ) ; if ( enhancedForArray == null ) { enhancedForArray = new ListExpression ( ) ; enhancedAnnotationNode . setMember ( "enhancedFor" , enhancedForArray ) ; } final List < Expression > featureNameExpressions = enhancedForArray . getExpressions ( ) ; for ( final String feature : enhancedFor ) { boolean exists = false ; for ( Expression expression : featureNameExpressions ) { if ( expression instanceof ConstantExpression && feature . equals ( ( ( ConstantExpression ) expression ) . getValue ( ) ) ) { exists = true ; break ; } } if ( ! exists ) { featureNameExpressions . add ( new ConstantExpression ( feature ) ) ; } } } return enhancedAnnotationNode ; } | Add the grails . artefact . Enhanced annotation to classNode if it does not already exist and ensure that all of the features in the enhancedFor array are represented in the enhancedFor attribute of the Enhanced annnotation |
25,180 | public static boolean hasAnnotation ( final ClassNode classNode , final Class < ? extends Annotation > annotationClass ) { return ! classNode . getAnnotations ( new ClassNode ( annotationClass ) ) . isEmpty ( ) ; } | Returns true if classNode is marked with annotationClass |
25,181 | public static boolean hasAnnotation ( final MethodNode methodNode , final Class < ? extends Annotation > annotationClass ) { return ! methodNode . getAnnotations ( new ClassNode ( annotationClass ) ) . isEmpty ( ) ; } | Returns true if MethodNode is marked with annotationClass |
25,182 | public static Map < String , ClassNode > getAssocationMap ( ClassNode classNode , String associationType ) { PropertyNode property = classNode . getProperty ( associationType ) ; Map < String , ClassNode > associationMap = new HashMap < String , ClassNode > ( ) ; if ( property != null && property . isStatic ( ) ) { Expression e = property . getInitialExpression ( ) ; if ( e instanceof MapExpression ) { MapExpression me = ( MapExpression ) e ; for ( MapEntryExpression mee : me . getMapEntryExpressions ( ) ) { String key = mee . getKeyExpression ( ) . getText ( ) ; Expression valueExpression = mee . getValueExpression ( ) ; if ( valueExpression instanceof ClassExpression ) { associationMap . put ( key , valueExpression . getType ( ) ) ; } } } } return associationMap ; } | Returns a map containing the names and types of the given association type . eg . GrailsDomainClassProperty . HAS_MANY |
25,183 | public static boolean isSubclassOf ( ClassNode classNode , String parentClassName ) { ClassNode currentSuper = classNode . getSuperClass ( ) ; while ( currentSuper != null && ! currentSuper . getName ( ) . equals ( OBJECT_CLASS ) ) { if ( currentSuper . getName ( ) . equals ( parentClassName ) ) return true ; currentSuper = currentSuper . getSuperClass ( ) ; } return false ; } | Returns true if the given class name is a parent class of the given class |
25,184 | public static MethodCallExpression buildSetPropertyExpression ( final Expression objectExpression , final String propertyName , final ClassNode targetClassNode , final Expression valueExpression ) { String methodName = "set" + MetaClassHelper . capitalize ( propertyName ) ; MethodCallExpression methodCallExpression = new MethodCallExpression ( objectExpression , methodName , new ArgumentListExpression ( valueExpression ) ) ; MethodNode setterMethod = targetClassNode . getSetterMethod ( methodName ) ; if ( setterMethod != null ) { methodCallExpression . setMethodTarget ( setterMethod ) ; } return methodCallExpression ; } | Build static direct call to setter of a property |
25,185 | public static MethodCallExpression buildPutMapExpression ( final Expression objectExpression , final String keyName , final Expression valueExpression ) { return applyDefaultMethodTarget ( new MethodCallExpression ( objectExpression , "put" , new ArgumentListExpression ( new ConstantExpression ( keyName ) , valueExpression ) ) , Map . class ) ; } | Build static direct call to put entry in Map |
25,186 | public static MethodCallExpression buildGetMapExpression ( final Expression objectExpression , final String keyName ) { return applyDefaultMethodTarget ( new MethodCallExpression ( objectExpression , "get" , new ArgumentListExpression ( new ConstantExpression ( keyName ) ) ) , Map . class ) ; } | Build static direct call to get entry from Map |
25,187 | public static URL getSourceUrl ( SourceUnit source ) { URL url = null ; final String filename = source . getName ( ) ; if ( filename == null ) { return null ; } Resource resource = new FileSystemResource ( filename ) ; if ( resource . exists ( ) ) { try { url = resource . getURL ( ) ; } catch ( IOException e ) { } } return url ; } | Find URL of SourceUnit |
25,188 | public JSONWriter value ( Number number ) { return number != null ? append ( number . toString ( ) ) : valueNull ( ) ; } | Append a number value |
25,189 | public JSONWriter value ( Object o ) { return o != null ? append ( new QuotedWritable ( o ) ) : valueNull ( ) ; } | Append an object value . |
25,190 | public static void assignBidirectionalAssociations ( Object object , Map source , PersistentEntity persistentEntity ) { if ( source == null ) { return ; } for ( Object key : source . keySet ( ) ) { String propertyName = key . toString ( ) ; if ( propertyName . indexOf ( '.' ) > - 1 ) { propertyName = propertyName . substring ( 0 , propertyName . indexOf ( '.' ) ) ; } PersistentProperty prop = persistentEntity . getPropertyByName ( propertyName ) ; if ( prop != null && prop instanceof OneToOne && ( ( OneToOne ) prop ) . isBidirectional ( ) ) { Object val = source . get ( key ) ; PersistentProperty otherSide = ( ( OneToOne ) prop ) . getInverseSide ( ) ; if ( val != null && otherSide != null ) { MetaClass mc = GroovySystem . getMetaClassRegistry ( ) . getMetaClass ( val . getClass ( ) ) ; try { mc . setProperty ( val , otherSide . getName ( ) , object ) ; } catch ( Exception e ) { } } } } } | Associations both sides of any bidirectional relationships found in the object and source map to bind |
25,191 | public static < T > void bindToCollection ( final Class < T > targetType , final Collection < T > collectionToPopulate , final CollectionDataBindingSource collectionBindingSource ) throws InstantiationException , IllegalAccessException { final GrailsApplication application = Holders . findApplication ( ) ; PersistentEntity entity = null ; if ( application != null ) { try { entity = application . getMappingContext ( ) . getPersistentEntity ( targetType . getClass ( ) . getName ( ) ) ; } catch ( GrailsConfigurationException e ) { } } final List < DataBindingSource > dataBindingSources = collectionBindingSource . getDataBindingSources ( ) ; for ( final DataBindingSource dataBindingSource : dataBindingSources ) { final T newObject = targetType . newInstance ( ) ; bindObjectToDomainInstance ( entity , newObject , dataBindingSource , getBindingIncludeList ( newObject ) , Collections . emptyList ( ) , null ) ; collectionToPopulate . add ( newObject ) ; } } | For each DataBindingSource provided by collectionBindingSource a new instance of targetType is created data binding is imposed on that instance with the DataBindingSource and the instance is added to the end of collectionToPopulate |
25,192 | public Object invoke ( Object controller , String action ) throws Throwable { if ( action == null ) action = this . defaultActionName ; ActionInvoker handle = actions . get ( action ) ; if ( handle == null ) throw new IllegalArgumentException ( "Invalid action name: " + action ) ; return handle . invoke ( controller ) ; } | Invokes the controller action for the given name on the given controller instance |
25,193 | public static boolean isConfigTrue ( GrailsApplication application , String propertyName ) { return application . getConfig ( ) . getProperty ( propertyName , Boolean . class , false ) ; } | Checks if a Config parameter is true or a System property with the same name is true |
25,194 | public Set < String > getBundleCodes ( Locale locale , String ... basenames ) { List < String > validBaseNames = getValidBasenames ( basenames ) ; Set < String > codes = new HashSet < > ( ) ; for ( String basename : validBaseNames ) { List < Pair < String , Resource > > filenamesAndResources = calculateAllFilenames ( basename , locale ) ; for ( Pair < String , Resource > filenameAndResource : filenamesAndResources ) { if ( filenameAndResource . getbValue ( ) != null ) { PropertiesHolder propHolder = getProperties ( filenameAndResource . getaValue ( ) , filenameAndResource . getbValue ( ) ) ; codes . addAll ( propHolder . getProperties ( ) . stringPropertyNames ( ) ) ; } } } return codes ; } | Retrieves all codes from one or multiple basenames |
25,195 | @ SuppressWarnings ( "rawtypes" ) protected PropertiesHolder getProperties ( final String filename , final Resource resource ) { return CacheEntry . getValue ( cachedProperties , filename , fileCacheMillis , new Callable < PropertiesHolder > ( ) { public PropertiesHolder call ( ) throws Exception { return new PropertiesHolder ( filename , resource ) ; } } , new Callable < CacheEntry > ( ) { public CacheEntry call ( ) throws Exception { return new PropertiesHolderCacheEntry ( ) ; } } , true , null ) ; } | Get a PropertiesHolder for the given filename either from the cache or freshly loaded . |
25,196 | protected Properties loadProperties ( Resource resource , String filename ) throws IOException { InputStream is = resource . getInputStream ( ) ; Properties props = new Properties ( ) ; try { if ( resource . getFilename ( ) . endsWith ( XML_SUFFIX ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Loading properties [" + resource . getFilename ( ) + "]" ) ; } this . propertiesPersister . loadFromXml ( props , is ) ; } else { String encoding = null ; if ( this . fileEncodings != null ) { encoding = this . fileEncodings . getProperty ( filename ) ; } if ( encoding == null ) { encoding = this . defaultEncoding ; } if ( encoding != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Loading properties [" + resource . getFilename ( ) + "] with encoding '" + encoding + "'" ) ; } this . propertiesPersister . load ( props , new InputStreamReader ( is , encoding ) ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Loading properties [" + resource . getFilename ( ) + "]" ) ; } this . propertiesPersister . load ( props , is ) ; } } return props ; } finally { is . close ( ) ; } } | Load the properties from the given resource . |
25,197 | public void clearCache ( ) { logger . debug ( "Clearing entire resource bundle cache" ) ; this . cachedProperties . clear ( ) ; this . cachedMergedProperties . clear ( ) ; this . cachedFilenames . clear ( ) ; this . cachedResources . clear ( ) ; } | Clear the resource bundle cache . Subsequent resolve calls will lead to reloading of the properties files . |
25,198 | public void clearCacheIncludingAncestors ( ) { clearCache ( ) ; if ( getParentMessageSource ( ) instanceof ReloadableResourceBundleMessageSource ) { ( ( ReloadableResourceBundleMessageSource ) getParentMessageSource ( ) ) . clearCacheIncludingAncestors ( ) ; } else if ( getParentMessageSource ( ) instanceof org . springframework . context . support . ReloadableResourceBundleMessageSource ) { ( ( org . springframework . context . support . ReloadableResourceBundleMessageSource ) getParentMessageSource ( ) ) . clearCacheIncludingAncestors ( ) ; } } | Clear the resource bundle caches of this MessageSource and all its ancestors . |
25,199 | public void importBeans ( String resourcePattern ) { try { Resource [ ] resources = resourcePatternResolver . getResources ( resourcePattern ) ; for ( Resource resource : resources ) { importBeans ( resource ) ; } } catch ( IOException e ) { LOG . error ( "Error loading beans for resource pattern: " + resourcePattern , e ) ; } } | Imports Spring bean definitions from either XML or Groovy sources into the current bean builder instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.