You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by bo...@apache.org on 2026/04/10 01:06:58 UTC

(grails-core) 02/03: chore: fix code style plugin and resolve code quality violations

This is an automated email from the ASF dual-hosted git repository.

borinquenkid pushed a commit to branch 8.0.x-hibernate7-dev
in repository https://gitbox.apache.org/repos/asf/grails-core.git

commit 753607e412cca6920d7360ec6af83417e655c27e
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Thu Apr 9 19:20:34 2026 -0500

    chore: fix code style plugin and resolve code quality violations
---
 .../grails/buildsrc/GrailsCodeStylePlugin.groovy   | 157 ++++++++++++++-------
 .../buildsrc/GrailsCodeStylePluginSpec.groovy      | 116 ++++++++++++---
 build.gradle                                       |   6 +-
 dependencies.gradle                                |   2 +
 grails-bom/build.gradle                            |   1 +
 grails-data-hibernate7/core/build.gradle           |  14 --
 .../org/grails/web/pages/GroovyPagesServlet.java   |  23 ++-
 7 files changed, 220 insertions(+), 99 deletions(-)

diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsCodeStylePlugin.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsCodeStylePlugin.groovy
index 7f15a07407..a1612aabb5 100644
--- a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsCodeStylePlugin.groovy
+++ b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/GrailsCodeStylePlugin.groovy
@@ -49,6 +49,10 @@ import com.github.spotbugs.snom.Effort
 import com.github.spotbugs.snom.SpotBugsExtension
 import com.github.spotbugs.snom.SpotBugsPlugin
 import com.github.spotbugs.snom.SpotBugsTask
+import org.gradle.api.tasks.testing.Test
+import org.gradle.testing.jacoco.plugins.JacocoPlugin
+import org.gradle.testing.jacoco.plugins.JacocoPluginExtension
+import org.gradle.testing.jacoco.tasks.JacocoReport
 
 /**
  * Convention plugin for Grails code style enforcement.
@@ -77,6 +81,8 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
 
     static String SPOTBUGS_ENABLED_PROPERTY = 'grails.codestyle.enabled.spotbugs'
 
+    static String JACOCO_ENABLED_PROPERTY = 'grails.codestyle.enabled.jacoco'
+
     static String IGNORE_FAILURES_PROPERTY = 'grails.codestyle.ignoreFailures'
 
     static String TEST_STYLING_PROPERTY = 'grails.codestyle.enabled.tests'
@@ -88,6 +94,44 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
         initExtension(project)
         configureCodeStyle(project)
         configureAggregation(project)
+        
+        boolean jacocoEnabled = GradleUtils.lookupProperty(project, JACOCO_ENABLED_PROPERTY, false)
+        if (jacocoEnabled) {
+            configureJacoco(project)
+            if (project == project.rootProject) {
+                project.logger.info("JaCoCo enabled globally, applying to subprojects")
+                project.subprojects.each { subproject ->
+                    subproject.pluginManager.withPlugin('java') {
+                        configureJacoco(subproject)
+                    }
+                    subproject.pluginManager.withPlugin('groovy') {
+                        configureJacoco(subproject)
+                    }
+                }
+            }
+        }
+    }
+
+    static void configureJacoco(Project project) {
+        project.logger.info("Configuring JaCoCo for project: ${project.name}")
+        project.pluginManager.apply(JacocoPlugin)
+
+        project.extensions.configure(JacocoPluginExtension) {
+            it.toolVersion = "0.8.14"
+        }
+
+        project.tasks.withType(Test).configureEach {
+            it.finalizedBy 'jacocoTestReport'
+        }
+
+        project.tasks.withType(JacocoReport).configureEach {
+            it.dependsOn project.tasks.withType(Test)
+            it.reports {
+                it.xml.required = true
+                it.html.required = true
+                it.csv.required = true
+            }
+        }
     }
 
     private static void configureAggregation(Project project) {
@@ -101,6 +145,7 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
             task.description = 'Aggregates all code style violations into separate reports'
 
             boolean checkTests = GradleUtils.lookupProperty(project, TEST_STYLING_PROPERTY, false)
+            boolean jacocoEnabled = GradleUtils.lookupProperty(project, JACOCO_ENABLED_PROPERTY, false)
 
             // Dependencies: all check tasks in all subprojects
             root.subprojects.each { subproject ->
@@ -125,6 +170,10 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
                         checkTests || (!t.name.toLowerCase().contains('test') && !t.name.toLowerCase().contains('integrationtest'))
                     })
                 }
+
+                if (jacocoEnabled) {
+                    task.dependsOn(subproject.tasks.withType(JacocoReport))
+                }
             }
 
             def reportsDir = project.extensions.getByType(GrailsCodeStyleExtension).reportsDirectory
@@ -133,7 +182,10 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
             task.outputs.file(root.layout.projectDirectory.file('CHECKSTYLE_VIOLATIONS.md'))
             task.outputs.file(root.layout.projectDirectory.file('PMD_VIOLATIONS.md'))
             task.outputs.file(root.layout.projectDirectory.file('SPOTBUGS_VIOLATIONS.md'))
-            task.outputs.file(root.layout.projectDirectory.file('JACOCO_COVERAGE_VIOLATIONS.md'))
+            
+            if (jacocoEnabled) {
+                task.outputs.file(root.layout.projectDirectory.file('JACOCO_COVERAGE_VIOLATIONS.md'))
+            }
 
             task.doLast {
                 parseViolations(root, reportsDir.get())
@@ -148,6 +200,7 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
         slurper.setFeature("http://xml.org/sax/features/namespaces", false)
 
         boolean checkTests = GradleUtils.lookupProperty(project, TEST_STYLING_PROPERTY, false)
+        boolean jacocoEnabled = GradleUtils.lookupProperty(project, JACOCO_ENABLED_PROPERTY, false)
 
         def getModule = { String fileName ->
             def lastDash = fileName.lastIndexOf('-')
@@ -326,56 +379,64 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
         writeReport('SPOTBUGS_VIOLATIONS.md', spotbugsViolations, 'SpotBugs Violations Summary')
 
         // 5. JaCoCo
-        def jacocoCoverage = []
-        project.rootProject.allprojects.each { p ->
-            // JaCoCo reports for test are usually in build/reports/jacoco/test/jacocoTestReport.csv
-            def csvReport = p.file("build/reports/jacoco/test/jacocoTestReport.csv")
-            if (csvReport.exists()) {
-                csvReport.splitEachLine(',') { fields ->
-                    if (fields[0] == 'GROUP') return // header
-                    def module = fields[0]
-                    def pkg = fields[1]
-                    def clazz = fields[2]
-                    def missed = fields[3]
-                    def covered = fields[4]
-                    
-                    // Skip if fields are not numeric (handle potential header/empty lines)
-                    if (missed.isNumber() && covered.isNumber()) {
-                        def m = missed.toInteger()
-                        def c = covered.toInteger()
-                        def total = m + c
-                        def percent = total > 0 ? (c * 100 / total).round(2) : 100.0
-                        
-                        jacocoCoverage << [
-                            module: module,
-                            className: "${pkg}.${clazz}",
-                            percent: percent
-                        ]
+        if (jacocoEnabled) {
+            project.logger.info("Aggregating JaCoCo coverage reports")
+            def jacocoCoverage = []
+            project.rootProject.allprojects.each { p ->
+                // JaCoCo reports for test are usually in build/reports/jacoco/test/jacocoTestReport.csv
+                def csvReport = p.file("build/reports/jacoco/test/jacocoTestReport.csv")
+                if (csvReport.exists()) {
+                    project.logger.debug("Processing JaCoCo report: ${csvReport.absolutePath}")
+                    csvReport.splitEachLine(',') { fields ->
+                        if (fields.size() < 5 || fields[0] == 'GROUP') return // header or malformed line
+                        def module = fields[0]
+                        def pkg = fields[1]
+                        def clazz = fields[2]
+                        def missedStr = fields[3]
+                        def coveredStr = fields[4]
+
+                        // Skip if fields are not numeric
+                        if (missedStr.isNumber() && coveredStr.isNumber()) {
+                            def m = missedStr.toInteger()
+                            def c = coveredStr.toInteger()
+                            def total = m + c
+                            def percent = total > 0 ? (c * 100 / total).round(2) : 100.0
+
+                            jacocoCoverage << [
+                                    module   : module,
+                                    className: "${pkg}.${clazz}",
+                                    percent  : percent
+                            ]
+                        }
                     }
                 }
             }
-        }
 
-        // Filter out classes in the 'org.grails.orm.hibernate.support.hibernate7' package
-        jacocoCoverage.removeIf { it.className.startsWith('org.grails.orm.hibernate.support.hibernate7.') }
+            if (!jacocoCoverage.isEmpty()) {
+                // Filter out classes in the 'org.grails.orm.hibernate.support.hibernate7' package
+                jacocoCoverage.removeIf { it.className.startsWith('org.grails.orm.hibernate.support.hibernate7.') }
 
-        def jacocoReportFile = project.layout.projectDirectory.file('JACOCO_COVERAGE_VIOLATIONS.md').asFile
-        def out = new StringBuilder()
-        out.append("# JaCoCo Coverage Report\n")
-        out.append("Generated on: ${LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))}\n\n")
-        
-        def groupedByModule = jacocoCoverage.groupBy { it.module }.sort()
-        groupedByModule.each { module, coverageList ->
-            out.append("## Module: ${module}\n")
-            out.append("| Class | % Instructions Covered |\n")
-            out.append("| :--- | :--- |\n")
-            coverageList.sort { it.percent }.each { c ->
-                out.append("| ${c.className} | ${c.percent}% |\n")
+                def jacocoReportFile = project.layout.projectDirectory.file('JACOCO_COVERAGE_VIOLATIONS.md').asFile
+                def out = new StringBuilder()
+                out.append("# JaCoCo Coverage Report\n")
+                out.append("Generated on: ${LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))}\n\n")
+
+                def groupedByModule = jacocoCoverage.groupBy { it.module }.sort()
+                groupedByModule.each { module, coverageList ->
+                    out.append("## Module: ${module}\n")
+                    out.append("| Class | % Instructions Covered |\n")
+                    out.append("| :--- | :--- |\n")
+                    coverageList.sort { it.percent }.each { c ->
+                        out.append("| ${c.className} | ${c.percent}% |\n")
+                    }
+                    out.append("\n")
+                }
+                jacocoReportFile.text = out.toString()
+                project.logger.lifecycle("Aggregated JaCoCo report generated: ${jacocoReportFile.absolutePath}")
+            } else {
+                project.logger.info("No JaCoCo coverage reports found to aggregate")
             }
-            out.append("\n")
         }
-        jacocoReportFile.text = out.toString()
-        project.logger.lifecycle("Aggregated JaCoCo report generated: ${jacocoReportFile.absolutePath}")
     }
 
     private static void initExtension(Project project) {
@@ -533,7 +594,7 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
         }
 
         if (!GradleUtils.lookupProperty(project, TEST_STYLING_PROPERTY, false)) {
-            project.tasks.named('checkstyleTest') {
+            project.tasks.matching { it.name == 'checkstyleTest' }.configureEach {
                 it.enabled = false // Do not check test sources at this time
             }
         }
@@ -743,10 +804,8 @@ class GrailsCodeStylePlugin implements Plugin<Project> {
             project.afterEvaluate {
                 // Do not check test sources at this time
                 ['codenarcIntegrationTest', 'codenarcTest'].each { testTaskName ->
-                    if (project.tasks.names.contains(testTaskName)) {
-                        project.tasks.named(testTaskName) {
-                            it.enabled = false
-                        }
+                    project.tasks.matching { it.name == testTaskName }.configureEach {
+                        it.enabled = false
                     }
                 }
             }
diff --git a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/GrailsCodeStylePluginSpec.groovy b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/GrailsCodeStylePluginSpec.groovy
index 7254cf045d..49d416ffbd 100644
--- a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/GrailsCodeStylePluginSpec.groovy
+++ b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/GrailsCodeStylePluginSpec.groovy
@@ -48,44 +48,122 @@ class GrailsCodeStylePluginSpec extends Specification {
         groovyFile = testProjectDir.resolve('src/main/groovy/Test.groovy').toFile()
     }
 
-    def "test aggregateStyleViolations generates jacoco report"() {
-        given: "a module with a jacoco csv report"
+    def "test codeStyle and aggregation tasks including jacoco"() {
+        given: "a project structure with violations and jacoco report"
+        testProjectDir.resolve('build/reports/codestyle/checkstyle').toFile().mkdirs()
+        testProjectDir.resolve('build/reports/codestyle/codenarc').toFile().mkdirs()
         def jacocoDir = testProjectDir.resolve('build/reports/jacoco/test').toFile()
         jacocoDir.mkdirs()
         
-        // Create an empty reports directory to satisfy task input validation
-        testProjectDir.resolve('build/reports/codestyle').toFile().mkdirs()
-        
-        def csvReport = new File(jacocoDir, 'jacocoTestReport.csv')
-        csvReport.text = """GROUP,PACKAGE,CLASS,INSTRUCTION_MISSED,INSTRUCTION_COVERED,BRANCH_MISSED,BRANCH_COVERED,LINE_MISSED,LINE_COVERED,COMPLEXITY_MISSED,COMPLEXITY_COVERED,METHOD_MISSED,METHOD_COVERED
-test-module,com.example,TestClass,1,9,0,0,0,1,0,1,0,1
-"""
-        
         buildFile = testProjectDir.resolve('settings.gradle').toFile()
-        buildFile.text = "include 'test-module'"
-        def moduleBuildFile = testProjectDir.resolve('test-module/build.gradle').toFile()
+        buildFile.text = "include 'app-module'"
+        def moduleDir = testProjectDir.resolve('app-module')
+        def moduleBuildFile = moduleDir.resolve('build.gradle').toFile()
         moduleBuildFile.parentFile.mkdirs()
         moduleBuildFile.text = """
             plugins {
                 id 'groovy'
+                id 'jacoco'
                 id 'org.apache.grails.gradle.grails-code-style'
             }
+            repositories {
+                mavenCentral()
+            }
+            dependencies {
+                implementation 'org.apache.groovy:groovy:4.0.11'
+            }
         """
+        def sourceFile = moduleDir.resolve('src/main/groovy/com/example/AppClass.groovy')
+        sourceFile.toFile().parentFile.mkdirs()
+        sourceFile.toFile().text = "package com.example\nclass AppClass {}"
+
+        def checkstyleReport = testProjectDir.resolve('build/reports/codestyle/checkstyle/app-module-checkstyleMain.xml').toFile()
+        checkstyleReport.parentFile.mkdirs()
+        checkstyleReport.text = """<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="10.0">
+<file name="${sourceFile.toFile().absolutePath}">
+<error line="1" column="1" severity="error" message="Missing a Javadoc comment." source="com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck"/>
+</file>
+</checkstyle>
+"""
+        def codenarcReport = testProjectDir.resolve('build/reports/codestyle/codenarc/app-module-codenarcMain.xml').toFile()
+        codenarcReport.parentFile.mkdirs()
+        codenarcReport.text = """<?xml version="1.0" encoding="UTF-8"?>
+<CodeNarc version="3.1.0">
+<Package name="com.example">
+<File name="AppClass.groovy">
+<Violation ruleName="EmptyClass" priority="2" lineNumber="1">
+<Message>The class is empty</Message>
+</Violation>
+</File>
+</Package>
+</CodeNarc>
+"""
+        def csvReport = new File(jacocoDir, 'jacocoTestReport.csv')
+        csvReport.text = """GROUP,PACKAGE,CLASS,INSTRUCTION_MISSED,INSTRUCTION_COVERED,BRANCH_MISSED,BRANCH_COVERED,LINE_MISSED,LINE_COVERED,COMPLEXITY_MISSED,COMPLEXITY_COVERED,METHOD_MISSED,METHOD_COVERED
+app-module,com.example,AppClass,1,9,0,0,0,1,0,1,0,1
+"""
 
-        when: "running aggregateStyleViolations"
+        when: "running aggregateStyleViolations with jacoco enabled"
         def result = GradleRunner.create()
                 .withProjectDir(testProjectDir.toFile())
-                .withArguments('aggregateStyleViolations', '--stacktrace')
+                .withArguments('aggregateStyleViolations', '-Pgrails.codestyle.enabled.jacoco=true', '-x', 'checkstyleMain', '-x', 'codenarcMain', '--stacktrace')
                 .withPluginClasspath()
                 .build()
 
         then: "task finished successfully"
         result.task(':aggregateStyleViolations').outcome == org.gradle.testkit.runner.TaskOutcome.SUCCESS
 
-        and: "JACOCO_COVERAGE_VIOLATIONS.md exists and contains the coverage data"
-        def report = testProjectDir.resolve('JACOCO_COVERAGE_VIOLATIONS.md').toFile()
-        report.exists()
-        report.text.contains('## Module: test-module')
-        report.text.contains('| com.example.TestClass | 90.00% |')
+        and: "violation reports are generated"
+        testProjectDir.resolve('CHECKSTYLE_VIOLATIONS.md').toFile().exists()
+        testProjectDir.resolve('CODENARC_VIOLATIONS.md').toFile().exists()
+        testProjectDir.resolve('JACOCO_COVERAGE_VIOLATIONS.md').toFile().exists()
+        
+        def checkstyleMd = testProjectDir.resolve('CHECKSTYLE_VIOLATIONS.md').toFile().text
+        checkstyleMd.contains('## Module: app-module')
+        checkstyleMd.contains('| com.example.AppClass | Checkstyle | JavadocPackageCheck | 1 | Missing a Javadoc comment. |')
+
+        def codenarcMd = testProjectDir.resolve('CODENARC_VIOLATIONS.md').toFile().text
+        codenarcMd.contains('## Module: app-module')
+        codenarcMd.contains('| com.example.AppClass | CodeNarc | EmptyClass | 1 | The class is empty |')
+
+        def jacocoMd = testProjectDir.resolve('JACOCO_COVERAGE_VIOLATIONS.md').toFile().text
+        jacocoMd.contains('## Module: app-module')
+        jacocoMd.contains('| com.example.AppClass | 90.00% |')
+    }
+
+    def "test codenarcFix task fixes violations"() {
+        given: "a file with violations"
+        groovyFile.text = """package org.test
+
+class Test{
+    def map = [key:"value"]
+    def str = "unnecessary gstring"
+    def semi = "semicolon";
+    def lines = 1
+
+
+    def other = 2
+}
+"""
+        when: "running codenarcFix"
+        def result = GradleRunner.create()
+                .withProjectDir(testProjectDir.toFile())
+                .withArguments('codenarcFix', '--stacktrace')
+                .withPluginClasspath()
+                .build()
+
+        then: "task finished successfully"
+        result.task(':codenarcFix').outcome == org.gradle.testkit.runner.TaskOutcome.SUCCESS
+
+        and: "violations are fixed"
+        def fixedContent = groovyFile.text
+        fixedContent.contains('class Test {') // SpaceBeforeOpeningBrace
+        fixedContent.contains('class Test {\n\n    def map') 
+        fixedContent.contains("[key: 'value']") // SpaceAroundMapEntryColon and UnnecessaryGString
+        fixedContent.contains("'unnecessary gstring'") // UnnecessaryGString
+        fixedContent.contains("def semi = 'semicolon'") // UnnecessarySemicolon
+        !fixedContent.contains(";")
+        fixedContent.count('\n\n') == 3 // ConsecutiveBlankLines
     }
 }
diff --git a/build.gradle b/build.gradle
index 80bffdc83d..d921e35d37 100644
--- a/build.gradle
+++ b/build.gradle
@@ -17,6 +17,7 @@
 
 plugins {
     id 'org.apache.grails.gradle.test-aggregation'
+    id 'org.apache.grails.gradle.grails-code-style'
 }
 
 import java.time.Instant
@@ -87,11 +88,6 @@ subprojects {
             cacheChangingModulesFor(cacheHours, 'hours')
         }
     }
-    pluginManager.withPlugin('jacoco') {
-        jacoco {
-            toolVersion = "0.8.14" // Set the specific tool version here
-        }
-    }
 }
 
 interface ExecSupport {
diff --git a/dependencies.gradle b/dependencies.gradle
index ae7a1cd114..00fb089554 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -38,12 +38,14 @@ ext {
             'jquery.version'                : '3.7.1',
             'objenesis.version'             : '3.4',
             'spring-boot.version'           : '4.0.5',
+            'testcontainers.version'        : '1.20.1',
     ]
 
     // Note: the name of the dependency must be the prefix of the property name so properties in the pom are resolved correctly
     gradleBomPlatformDependencies = [
             'spring-boot-bom' : "org.springframework.boot:spring-boot-dependencies:${gradleBomDependencyVersions['spring-boot.version']}",
             'gradle-spock-bom': "org.spockframework:spock-bom:${gradleBomDependencyVersions['gradle-spock.version']}",
+            'testcontainers-bom': "org.testcontainers:testcontainers-bom:${gradleBomDependencyVersions['testcontainers.version']}",
     ]
 
     // Note: the name of the dependency must be the prefix of the property name so properties in the pom are resolved correctly
diff --git a/grails-bom/build.gradle b/grails-bom/build.gradle
index a1f38b9945..5e5e8b91ff 100644
--- a/grails-bom/build.gradle
+++ b/grails-bom/build.gradle
@@ -59,6 +59,7 @@ dependencies {
     for (def entry : bomPlatformDependencies.entrySet()) {
         api platform(entry.value)
     }
+    api platform(gradleBomPlatformDependencies['testcontainers-bom'])
 
     constraints {
         for (def entry : gradleBomDependencies.entrySet()) {
diff --git a/grails-data-hibernate7/core/build.gradle b/grails-data-hibernate7/core/build.gradle
index b5510afc90..98b5d30d18 100644
--- a/grails-data-hibernate7/core/build.gradle
+++ b/grails-data-hibernate7/core/build.gradle
@@ -20,7 +20,6 @@
 plugins {
     id 'groovy'
     id 'java-library'
-    id 'jacoco'
     id 'org.apache.grails.buildsrc.properties'
     id 'org.apache.grails.buildsrc.compile'
     id 'org.apache.grails.buildsrc.publish'
@@ -143,19 +142,6 @@ apply {
     from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
 }
 
-test {
-    finalizedBy jacocoTestReport
-}
-
-jacocoTestReport {
-    dependsOn test
-    reports {
-        xml.required = true
-        html.required = true
-        csv.required = true
-    }
-}
-
 // spotbugs {
 //     effort = Effort.valueOf('MAX')
 //     reportLevel = Confidence.valueOf('HIGH')// or Confidence.MEDIUM, Confidence.LOW
diff --git a/grails-gsp/grails-web-gsp/src/main/groovy/org/grails/web/pages/GroovyPagesServlet.java b/grails-gsp/grails-web-gsp/src/main/groovy/org/grails/web/pages/GroovyPagesServlet.java
index 9cbac449d2..7901be366a 100644
--- a/grails-gsp/grails-web-gsp/src/main/groovy/org/grails/web/pages/GroovyPagesServlet.java
+++ b/grails-gsp/grails-web-gsp/src/main/groovy/org/grails/web/pages/GroovyPagesServlet.java
@@ -117,7 +117,7 @@ public class GroovyPagesServlet extends FrameworkServlet implements PluginManage
         context.setAttribute(SERVLET_INSTANCE, this);
 
         final WebApplicationContext webApplicationContext = getWebApplicationContext();
-        grailsAttributes = GrailsFactoriesLoader.loadFactoriesWithArguments(GrailsApplicationAttributes.class, getClass().getClassLoader(), new Object[]{context}).get(0);
+        grailsAttributes = GrailsFactoriesLoader.loadFactoriesWithArguments(GrailsApplicationAttributes.class, Thread.currentThread().getContextClassLoader(), new Object[]{context}).get(0);
         final AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext.getAutowireCapableBeanFactory();
         if (autowireCapableBeanFactory != null) {
             autowireCapableBeanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
@@ -218,18 +218,17 @@ public class GroovyPagesServlet extends FrameworkServlet implements PluginManage
     protected void renderPageWithEngine(GroovyPagesTemplateEngine engine, HttpServletRequest request,
                                         HttpServletResponse response, GroovyPageScriptSource scriptSource) throws Exception {
         request.setAttribute(GroovyPagesUriService.RENDERING_VIEW_ATTRIBUTE, Boolean.TRUE);
-        GSPResponseWriter out = createResponseWriter(response);
-        try {
-            Template template = engine.createTemplate(scriptSource);
-            if (template instanceof GroovyPageTemplate) {
-                ((GroovyPageTemplate) template).setAllowSettingContentType(true);
+        try (GSPResponseWriter out = createResponseWriter(response)) {
+            try {
+                Template template = engine.createTemplate(scriptSource);
+                if (template instanceof GroovyPageTemplate) {
+                    ((GroovyPageTemplate) template).setAllowSettingContentType(true);
+                }
+                template.make().writeTo(out);
+            } catch (Exception e) {
+                out.setError();
+                throw e;
             }
-            template.make().writeTo(out);
-        } catch (Exception e) {
-            out.setError();
-            throw e;
-        } finally {
-            if (out != null) out.close();
         }
     }