<commit_before>/*
 * Copyright 2004-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.codehaus.groovy.grails.plugins.web

import grails.util.BuildSettingsHolder
import grails.util.Environment
import grails.util.PluginBuildSettings

import groovy.lang.MetaClass
import java.lang.reflect.Modifier

import org.codehaus.groovy.grails.commons.GrailsClass
import org.codehaus.groovy.grails.commons.GrailsClassUtils
import org.codehaus.groovy.grails.commons.GrailsTagLibClass
import org.codehaus.groovy.grails.commons.TagLibArtefactHandler
import org.codehaus.groovy.grails.web.pages.ext.jsp.TagLibraryResolver
import org.codehaus.groovy.grails.web.plugins.support.WebMetaUtils
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.codehaus.groovy.grails.web.servlet.view.GrailsViewResolver
import org.springframework.beans.factory.config.PropertiesFactoryBean
import org.springframework.context.ApplicationContext
import org.springframework.core.io.FileSystemResource
import org.springframework.web.context.request.RequestContextHolder
import org.codehaus.groovy.grails.plugins.web.taglib.*
import org.codehaus.groovy.grails.web.pages.*
import org.codehaus.groovy.grails.web.filters.JavascriptLibraryFilters
import org.codehaus.groovy.grails.plugins.GrailsPluginManager
import grails.util.BuildSettings

/**
 * A Plugin that sets up and configures the GSP and GSP tag library support in Grails 
 *
 * @author <NAME>
 * @since 1.1
 * 
 * Created: Jan 5, 2009
 */

public class GroovyPagesGrailsPlugin {

    // monitor all resources that end with TagLib.groovy
    def watchedResources = [ "file:./plugins/*/grails-app/taglib/**/*TagLib.groovy",
                             "file:./grails-app/taglib/**/*TagLib.groovy"]


    def version = grails.util.GrailsUtil.getGrailsVersion()
    def dependsOn = [core: version, i18n: version]
    def observe = ['controllers']


    // Provide these tag libraries declaratively
    def providedArtefacts = [
            ApplicationTagLib,
            CountryTagLib,
            FormatTagLib,
            FormTagLib,
            JavascriptTagLib,
            RenderTagLib,
            ValidationTagLib,
            PluginTagLib,
            SitemeshTagLib,
            JavascriptLibraryFilters
    ]



    /**
     * Clear the page cache with the ApplicationContext is loaded
     */
    def doWithApplicationContext = {ApplicationContext ctx ->
        GroovyPagesTemplateEngine templateEngine = ctx.getBean("groovyPagesTemplateEngine")
        templateEngine.clearPageCache()
    }

    /**
     * Configures the various Spring beans required by GSP
     */
    def doWithSpring = {
        // A bean used to resolve JSP tag libraries
        jspTagLibraryResolver(TagLibraryResolver)
        // A bean used to resolve GSP tag libraries
        gspTagLibraryLookup(TagLibraryLookup)

        boolean developmentMode = !application.warDeployed
        Environment env = Environment.current
        boolean enableReload = env.isReloadEnabled() || application.config.grails.gsp.enable.reload == true || (developmentMode && env == Environment.DEVELOPMENT)
        boolean warDeployedWithReload = application.warDeployed && enableReload

        // If the development environment is used we need to load GSP files relative to the base directory
        // as oppose to in WAR deployment where views are loaded from /WEB-INF
        def viewsDir = application.config.grails.gsp.view.dir
        if (viewsDir) {
            log.info "Configuring GSP views directory as '${viewsDir}'"
            groovyPageResourceLoader(org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader) {
                baseResource = "file:${viewsDir}"
                pluginSettings = new PluginBuildSettings(BuildSettingsHolder.settings)
            }
        }
        else {
            if (developmentMode) {
                groovyPageResourceLoader(org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader) {
                    BuildSettings settings = BuildSettingsHolder.settings
                    baseResource = new FileSystemResource(settings?.baseDir ?: new File('.'))                    
                    pluginSettings = new PluginBuildSettings(settings)
                }
            }
            else {
                if (warDeployedWithReload) {
                    groovyPageResourceLoader(org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader) {
                        if(env.hasReloadLocation()) {
                            def location = env.reloadLocation
                            if(!location.endsWith(File.separator)) location = "${location}${File.separator}"
                            baseResource = "file:${location}"
                        }
                        else {
                            baseResource = "/WEB-INF"
                        }
                        pluginSettings = new PluginBuildSettings(BuildSettingsHolder.settings)
                    }
                }
            }
        }

        // Setup the main templateEngine used to render GSPs
        groovyPagesTemplateEngine(org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine) {
            classLoader = ref("classLoader")
            if (developmentMode || warDeployedWithReload) {
                resourceLoader = groovyPageResourceLoader
            }
            if (enableReload) {
                reloadEnabled = enableReload
            }
            tagLibraryLookup = gspTagLibraryLookup
            jspTagLibraryResolver = jspTagLibraryResolver
			precompiledGspMap = { PropertiesFactoryBean pfb -> 
				ignoreResourceNotFound = true
				location = "classpath:gsp/views.properties"
			}
        }

        // Setup the GroovyPagesUriService
        groovyPagesUriService(org.codehaus.groovy.grails.web.pages.DefaultGroovyPagesUriService) {
        	
        }
        
        // Configure a Spring MVC view resolver
        jspViewResolver(GrailsViewResolver) {
            viewClass = org.springframework.web.servlet.view.JstlView.class
            prefix = GrailsApplicationAttributes.PATH_TO_VIEWS
            suffix = ".jsp"
            templateEngine = groovyPagesTemplateEngine
            if (developmentMode) {
                resourceLoader = groovyPageResourceLoader
            }
        }

        // Now go through tag libraries and configure them in spring too. With AOP proxies and so on
        for(taglib in application.tagLibClasses) {
            "${taglib.fullName}"(taglib.clazz) { bean ->
                   bean.autowire = true
                   // Taglib scoping support could be easily added here. Scope could be based on a static field in the taglib class.
				   //bean.scope = 'request'
            }
        }

    }

    /**
     * Modifies the web.xml when in development mode to allow viewing of sources
     */
    def doWithWebDescriptor = { webXml ->
        if (Environment.current == Environment.DEVELOPMENT) {
            // Find the GSP servlet and allow viewing generated source in
            // development mode
            def gspServlet = webXml.servlet.find {it.'servlet-name'?.text() == 'gsp'}
            gspServlet.'servlet-class' + {
                'init-param'
                {
                    description """
		              Allows developers to view the intermediade source code, when they pass
		                a spillGroovy argument in the URL.
							"""
                    'param-name'('showSource')
                    'param-value'(1)
                }
            }
        }
    }


    /**
     * Sets up dynamic methods required by the GSP implementation including dynamic tag method dispatch
     */
    def doWithDynamicMethods = { ApplicationContext ctx ->
<commit_msg>fix for view resolution resolving from basedir when using BuildSettings.baseDir<commit_after>/*
 * Copyright 2004-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.codehaus.groovy.grails.plugins.web

import grails.util.BuildSettingsHolder
import grails.util.Environment
import grails.util.PluginBuildSettings

import groovy.lang.MetaClass
import java.lang.reflect.Modifier

import org.codehaus.groovy.grails.commons.GrailsClass
import org.codehaus.groovy.grails.commons.GrailsClassUtils
import org.codehaus.groovy.grails.commons.GrailsTagLibClass
import org.codehaus.groovy.grails.commons.TagLibArtefactHandler
import org.codehaus.groovy.grails.web.pages.ext.jsp.TagLibraryResolver
import org.codehaus.groovy.grails.web.plugins.support.WebMetaUtils
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.codehaus.groovy.grails.web.servlet.view.GrailsViewResolver
import org.springframework.beans.factory.config.PropertiesFactoryBean
import org.springframework.context.ApplicationContext
import org.springframework.core.io.FileSystemResource
import org.springframework.web.context.request.RequestContextHolder
import org.codehaus.groovy.grails.plugins.web.taglib.*
import org.codehaus.groovy.grails.web.pages.*
import org.codehaus.groovy.grails.web.filters.JavascriptLibraryFilters
import org.codehaus.groovy.grails.plugins.GrailsPluginManager
import grails.util.BuildSettings

/**
 * A Plugin that sets up and configures the GSP and GSP tag library support in Grails 
 *
 * @author <NAME>
 * @since 1.1
 * 
 * Created: Jan 5, 2009
 */

public class GroovyPagesGrailsPlugin {

    // monitor all resources that end with TagLib.groovy
    def watchedResources = [ "file:./plugins/*/grails-app/taglib/**/*TagLib.groovy",
                             "file:./grails-app/taglib/**/*TagLib.groovy"]


    def version = grails.util.GrailsUtil.getGrailsVersion()
    def dependsOn = [core: version, i18n: version]
    def observe = ['controllers']


    // Provide these tag libraries declaratively
    def providedArtefacts = [
            ApplicationTagLib,
            CountryTagLib,
            FormatTagLib,
            FormTagLib,
            JavascriptTagLib,
            RenderTagLib,
            ValidationTagLib,
            PluginTagLib,
            SitemeshTagLib,
            JavascriptLibraryFilters
    ]



    /**
     * Clear the page cache with the ApplicationContext is loaded
     */
    def doWithApplicationContext = {ApplicationContext ctx ->
        GroovyPagesTemplateEngine templateEngine = ctx.getBean("groovyPagesTemplateEngine")
        templateEngine.clearPageCache()
    }

    /**
     * Configures the various Spring beans required by GSP
     */
    def doWithSpring = {
        // A bean used to resolve JSP tag libraries
        jspTagLibraryResolver(TagLibraryResolver)
        // A bean used to resolve GSP tag libraries
        gspTagLibraryLookup(TagLibraryLookup)

        boolean developmentMode = !application.warDeployed
        Environment env = Environment.current
        boolean enableReload = env.isReloadEnabled() || application.config.grails.gsp.enable.reload == true || (developmentMode && env == Environment.DEVELOPMENT)
        boolean warDeployedWithReload = application.warDeployed && enableReload

        // If the development environment is used we need to load GSP files relative to the base directory
        // as oppose to in WAR deployment where views are loaded from /WEB-INF
        def viewsDir = application.config.grails.gsp.view.dir
        if (viewsDir) {
            log.info "Configuring GSP views directory as '${viewsDir}'"
            groovyPageResourceLoader(org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader) {
                baseResource = "file:${viewsDir}"
                pluginSettings = new PluginBuildSettings(BuildSettingsHolder.settings)
            }
        }
        else {
            if (developmentMode) {
                groovyPageResourceLoader(org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader) {
                    BuildSettings settings = BuildSettingsHolder.settings
                    def location = settings?.baseDir ? GroovyPagesGrailsPlugin.transformToValidLocation(settings.baseDir.absolutePath) : '.'
                    baseResource = "file:$location"
                    pluginSettings = new PluginBuildSettings(settings)
                }
            }
            else {
                if (warDeployedWithReload) {
                    groovyPageResourceLoader(org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader) {
                        if(env.hasReloadLocation()) {
                            def location = GroovyPagesGrailsPlugin.transformToValidLocation(env.reloadLocation)                             
                            baseResource = "file:${location}"
                        }
                        else {
                            baseResource = "/WEB-INF"
                        }
                        pluginSettings = new PluginBuildSettings(BuildSettingsHolder.settings)
                    }
                }
            }
        }

        // Setup the main templateEngine used to render GSPs
        groovyPagesTemplateEngine(org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine) {
            classLoader = ref("classLoader")
            if (developmentMode || warDeployedWithReload) {
                resourceLoader = groovyPageResourceLoader
            }
            if (enableReload) {
                reloadEnabled = enableReload
            }
            tagLibraryLookup = gspTagLibraryLookup
            jspTagLibraryResolver = jspTagLibraryResolver
			precompiledGspMap = { PropertiesFactoryBean pfb -> 
				ignoreResourceNotFound = true
				location = "classpath:gsp/views.properties"
			}
        }

        // Setup the GroovyPagesUriService
        groovyPagesUriService(org.codehaus.groovy.grails.web.pages.DefaultGroovyPagesUriService) {
        	
        }
        
        // Configure a Spring MVC view resolver
        jspViewResolver(GrailsViewResolver) {
            viewClass = org.springframework.web.servlet.view.JstlView.class
            prefix = GrailsApplicationAttributes.PATH_TO_VIEWS
            suffix = ".jsp"
            templateEngine = groovyPagesTemplateEngine
            if (developmentMode) {
                resourceLoader = groovyPageResourceLoader
            }
        }

        // Now go through tag libraries and configure them in spring too. With AOP proxies and so on
        for(taglib in application.tagLibClasses) {
            "${taglib.fullName}"(taglib.clazz) { bean ->
                   bean.autowire = true
                   // Taglib scoping support could be easily added here. Scope could be based on a static field in the taglib class.
				   //bean.scope = 'request'
            }
        }

    }

    static String transformToValidLocation(String location) {
        if(location == '.') return location
        if (!location.endsWith(File.separator)) return "${location}${File.separator}"
        return location
    }

    /**
     * Modifies the web.xml when in development mode to allow viewing of sources
     */
    def doWithWebDescriptor = { webXml ->
        if (Environment.current == Environment.DEVELOPMENT) {
            // Find the GSP servlet and allow viewing generated source in
            // development mode
            def gspServlet = webXml.servlet.find {it.'servlet-name'?.text() == 'gsp'}
            gspServlet.'servlet-class' + {
                'init-param'
                {
                    description """
		              Allows developers to view the intermediade source code, when they pass
		                a spillGroovy argument in the URL.
							"""
                    'param-name'('showSource')
                    'param-value'(1)
                }
            }
        }
    }


    /**
     * Sets up dynamic methods required by the GSP implementation including dynamic tag method dispatch
     */
    def doWithDynamicMethods = { ApplicationContext ctx ->

{'fraction_non_alphanumeric': 0.07699563730692136, 'fraction_numerical': 0.0025940337224383916, 'mean_word_length': 2.2552293225868354, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5110082', 'n_tokens_mistral': 4560, 'n_tokens_neox': 4223, 'n_words': 1056}