forked from grails/grails-gsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GroovyPagesGrailsPlugin.groovy
332 lines (282 loc) · 13 KB
/
GroovyPagesGrailsPlugin.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
* 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.grails.plugins.web
import grails.config.Config
import grails.core.gsp.GrailsTagLibClass
import grails.gsp.PageRenderer
import grails.plugins.Plugin
import grails.util.BuildSettings
import grails.util.Environment
import grails.util.GrailsUtil
import grails.util.Metadata
import grails.web.pages.GroovyPagesUriService
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.grails.core.artefact.TagLibArtefactHandler
import org.grails.gsp.GroovyPageResourceLoader
import org.grails.gsp.GroovyPagesTemplateEngine
import org.grails.gsp.io.CachingGroovyPageStaticResourceLocator
import org.grails.gsp.jsp.TagLibraryResolverImpl
import org.grails.plugins.web.taglib.*
import org.grails.spring.RuntimeSpringConfiguration
import org.grails.taglib.TagLibraryLookup
import org.grails.taglib.TagLibraryMetaUtils
import org.grails.web.errors.ErrorsViewStackTracePrinter
import org.grails.web.gsp.GroovyPagesTemplateRenderer
import org.grails.web.gsp.io.CachingGrailsConventionGroovyPageLocator
import org.grails.web.pages.DefaultGroovyPagesUriService
import org.grails.web.pages.FilteringCodecsByContentTypeSettings
import org.grails.web.pages.GroovyPagesServlet
import org.grails.web.servlet.view.GroovyPageViewResolver
import org.grails.web.sitemesh.GroovyPageLayoutFinder
import org.grails.web.util.GrailsApplicationAttributes
import org.springframework.beans.factory.config.PropertiesFactoryBean
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.core.io.Resource
import org.springframework.util.ClassUtils
import org.springframework.web.servlet.view.InternalResourceViewResolver
/**
* Sets up and configures the GSP and GSP tag library support in Grails.
*
* @author Graeme Rocher
* @since 1.1
*/
@Slf4j
class GroovyPagesGrailsPlugin extends Plugin {
public static final String GSP_RELOAD_INTERVAL = "grails.gsp.reload.interval"
public static final String GSP_VIEWS_DIR = 'grails.gsp.view.dir'
public static final String GSP_VIEW_LAYOUT_RESOLVER_ENABLED = 'grails.gsp.view.layoutViewResolver'
public static final String SITEMESH_DEFAULT_LAYOUT = 'grails.sitemesh.default.layout'
public static final String SITEMESH_ENABLE_NONGSP = 'grails.sitemesh.enable.nongsp'
def watchedResources = ["file:./plugins/*/grails-app/taglib/**/*TagLib.groovy",
"file:./grails-app/taglib/**/*TagLib.groovy"]
def grailsVersion = "3.3.0 > *"
def dependsOn = [core: GrailsUtil.getGrailsVersion(), i18n: GrailsUtil.getGrailsVersion()]
def observe = ['controllers']
def loadAfter = ['filters']
def providedArtefacts = [
ApplicationTagLib,
CountryTagLib,
FormatTagLib,
FormTagLib,
JavascriptTagLib,
RenderTagLib,
UrlMappingTagLib,
ValidationTagLib,
PluginTagLib,
SitemeshTagLib
]
/**
* Clear the page cache with the ApplicationContext is loaded
*/
@CompileStatic
@Override
void doWithApplicationContext() {
applicationContext.getBean("groovyPagesTemplateEngine", GroovyPagesTemplateEngine).clearPageCache()
}
/**
* Configures the various Spring beans required by GSP
*/
Closure doWithSpring() {{->
def application = grailsApplication
Config config = application.config
boolean developmentMode = isDevelopmentMode()
Environment env = Environment.current
boolean enableReload = env.isReloadEnabled() ||
config.getProperty(GroovyPagesTemplateEngine.CONFIG_PROPERTY_GSP_ENABLE_RELOAD, Boolean, false) ||
(developmentMode && env == Environment.DEVELOPMENT)
boolean warDeployed = application.warDeployed
boolean warDeployedWithReload = warDeployed && enableReload
long gspCacheTimeout = config.getProperty(GSP_RELOAD_INTERVAL, Long, (developmentMode && env == Environment.DEVELOPMENT) ? 0L : 5000L)
boolean enableCacheResources = !config.getProperty(GroovyPagesTemplateEngine.CONFIG_PROPERTY_DISABLE_CACHING_RESOURCES, Boolean, false)
String viewsDir = config.getProperty(GSP_VIEWS_DIR, '')
def disableLayoutViewResolver = config.getProperty(GSP_VIEW_LAYOUT_RESOLVER_ENABLED, Boolean, true)
String defaultDecoratorNameSetting = config.getProperty(SITEMESH_DEFAULT_LAYOUT, '')
def sitemeshEnableNonGspViews = config.getProperty(SITEMESH_ENABLE_NONGSP, Boolean, false)
RuntimeSpringConfiguration spring = springConfig
// resolves JSP tag libraries
if(ClassUtils.isPresent("org.grails.gsp.jsp.TagLibraryResolverImpl", application.classLoader)) {
jspTagLibraryResolver(TagLibraryResolverImpl)
}
// resolves GSP tag libraries
gspTagLibraryLookup(TagLibraryLookup) { bean ->
bean.lazyInit = true
}
boolean customResourceLoader = false
// 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
if (viewsDir) {
log.info "Configuring GSP views directory as '${viewsDir}'"
customResourceLoader = true
groovyPageResourceLoader(GroovyPageResourceLoader) {
baseResource = "file:${viewsDir}"
}
}
else {
if (developmentMode) {
customResourceLoader = true
groovyPageResourceLoader(GroovyPageResourceLoader) { bean ->
bean.lazyInit = true
def location = GroovyPagesGrailsPlugin.transformToValidLocation(BuildSettings.BASE_DIR.absolutePath)
baseResource = "file:$location"
}
}
else {
if (warDeployedWithReload && env.hasReloadLocation()) {
customResourceLoader = true
groovyPageResourceLoader(GroovyPageResourceLoader) {
def location = GroovyPagesGrailsPlugin.transformToValidLocation(env.reloadLocation)
baseResource = "file:${location}"
}
}
}
}
def deployed = !Metadata.getCurrent().isDevelopmentEnvironmentAvailable()
groovyPageLocator(CachingGrailsConventionGroovyPageLocator) { bean ->
bean.lazyInit = true
if (customResourceLoader) {
resourceLoader = groovyPageResourceLoader
}
if (deployed) {
Resource defaultViews = applicationContext?.getResource('gsp/views.properties')
if(defaultViews != null) {
if(!defaultViews.exists()) {
defaultViews = applicationContext?.getResource('classpath:gsp/views.properties')
}
}
if(defaultViews?.exists()) {
precompiledGspMap = { PropertiesFactoryBean pfb ->
ignoreResourceNotFound = true
locations = [defaultViews] as Resource[]
}
}
}
if (enableReload) {
cacheTimeout = gspCacheTimeout
}
reloadEnabled = enableReload
}
grailsResourceLocator(CachingGroovyPageStaticResourceLocator) { bean ->
bean.parent = "abstractGrailsResourceLocator"
if (enableReload) {
cacheTimeout = gspCacheTimeout
}
}
// Setup the main templateEngine used to render GSPs
groovyPagesTemplateEngine(GroovyPagesTemplateEngine) { bean ->
bean.lazyInit = true
groovyPageLocator = groovyPageLocator
if (enableReload) {
reloadEnabled = enableReload
}
tagLibraryLookup = gspTagLibraryLookup
jspTagLibraryResolver = jspTagLibraryResolver
cacheResources = enableCacheResources
}
spring.addAlias('groovyTemplateEngine', 'groovyPagesTemplateEngine')
groovyPageRenderer(PageRenderer, ref("groovyPagesTemplateEngine")) { bean ->
bean.lazyInit = true
groovyPageLocator = groovyPageLocator
}
groovyPagesTemplateRenderer(GroovyPagesTemplateRenderer) { bean ->
bean.autowire = true
}
groovyPageLayoutFinder(GroovyPageLayoutFinder) {
gspReloadEnabled = enableReload
defaultDecoratorName = defaultDecoratorNameSetting ?: null
enableNonGspViews = sitemeshEnableNonGspViews
}
// Setup the GroovyPagesUriService
groovyPagesUriService(DefaultGroovyPagesUriService) { bean ->
bean.lazyInit = true
}
boolean jstlPresent = ClassUtils.isPresent(
"javax.servlet.jsp.jstl.core.Config", InternalResourceViewResolver.class.getClassLoader())
abstractViewResolver {
prefix = GrailsApplicationAttributes.PATH_TO_VIEWS
suffix = jstlPresent ? GroovyPageViewResolver.JSP_SUFFIX : GroovyPageViewResolver.GSP_SUFFIX
templateEngine = groovyPagesTemplateEngine
groovyPageLocator = groovyPageLocator
if (enableReload) {
cacheTimeout = gspCacheTimeout
}
}
// Configure a Spring MVC view resolver
jspViewResolver(GroovyPageViewResolver) { bean ->
bean.lazyInit = true
bean.parent = "abstractViewResolver"
}
// "grails.gsp.view.layoutViewResolver=false" can be used to disable GrailsLayoutViewResolver
// containsKey check must be made to check existence of boolean false values in ConfigObject
if(disableLayoutViewResolver) {
grailsLayoutViewResolverPostProcessor(GrailsLayoutViewResolverPostProcessor)
}
// Now go through tag libraries and configure them in Spring too. With AOP proxies and so on
for (taglib in application.tagLibClasses) {
final tagLibClass = taglib.clazz
"${taglib.fullName}"(tagLibClass) { bean ->
bean.autowire = true
bean.lazyInit = true
// Taglib scoping support could be easily added here. Scope could be based on a static field in the taglib class.
//bean.scope = 'request'
}
}
errorsViewStackTracePrinter(ErrorsViewStackTracePrinter, ref('grailsResourceLocator'))
filteringCodecsByContentTypeSettings(FilteringCodecsByContentTypeSettings, application)
groovyPagesServlet(ServletRegistrationBean, new GroovyPagesServlet(), "*.gsp") {
if(Environment.isDevelopmentMode()) {
initParameters = [showSource:"1"]
}
}
grailsTagDateHelper(DefaultGrailsTagDateHelper)
}}
protected boolean isDevelopmentMode() {
Metadata.getCurrent().isDevelopmentEnvironmentAvailable()
}
static String transformToValidLocation(String location) {
if (location == '.') return location
if (!location.endsWith(File.separator)) return "${location}${File.separator}"
return location
}
@Override
void onChange(Map<String, Object> event) {
def application = grailsApplication
def ctx = applicationContext
if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, event.source)) {
GrailsTagLibClass taglibClass = (GrailsTagLibClass)application.addArtefact(TagLibArtefactHandler.TYPE, event.source)
if (taglibClass) {
// replace tag library bean
def beanName = taglibClass.fullName
beans {
"$beanName"(taglibClass.clazz) { bean ->
bean.autowire = true
}
}
// The tag library lookup class caches "tag -> taglib class"
// so we need to update it now.
def lookup = applicationContext.getBean('gspTagLibraryLookup', TagLibraryLookup)
lookup.registerTagLib(taglibClass)
TagLibraryMetaUtils.enhanceTagLibMetaClass(taglibClass, lookup)
}
}
// clear uri cache after changes
ctx.getBean('groovyPagesUriService',GroovyPagesUriService).clear()
}
@CompileStatic
void onConfigChange(Map<String, Object> event) {
applicationContext.getBean('filteringCodecsByContentTypeSettings', FilteringCodecsByContentTypeSettings).initialize(grailsApplication)
}
}