Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller inheritance in grails 2.2

Tags:

grails

I have some code that I am trying to port from Grails 1.3.7 to Grails 2.2.

The current problem is that I have an BaseController class that defines some convenience methods, and specific controllers (ones actually instantiated by Grails) that inherit from it.

package com.fxpal.querium

import grails.converters.JSON
import groovy.lang.Closure;

abstract class BaseController {

    protected def executeSafely(Closure c) {
        def resp = null
        try { 
            populateContext();
            resp = c() 
        }
        catch(Exception ex) {
            resp = [error: ex.message]
            ex.printStackTrace()
        }
        def json = resp as JSON
        return json
    }

    protected void populateContext() {

    }
}

An example of a derived class is

package com.fxpal.querium

import grails.converters.JSON
import grails.plugins.springsecurity.Secured
import javax.servlet.http.HttpServletResponse

@Secured(['IS_AUTHENTICATED_REMEMBERED'])
class DocumentController extends BaseController {

    def grailsApplication

    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def getText = {
        try {
            String text = new URL(grailsApplication.config.querium.docurl + params.paperId).text
            render contentType: 'text/plain', text: text            
        }
        catch(Exception ex) {
            render contentType: 'text/plain', text: "Error loading document: ${ex.getMessage()}; please retry"
        }
    }

...
}

This worked in Grails 1.3.7. When I try to compile my app with Grails 2.2, I get the following error:

C:\code\querium\AppServer-grails-2\grails-app\controllers\com\fxpal\querium\DocumentController.groovy: -1: The return ty
pe of java.lang.Object getGrailsApplication() in com.fxpal.querium.DocumentController is incompatible with org.codehaus.
groovy.grails.commons.GrailsApplication getGrailsApplication() in com.fxpal.querium.BaseController
. At [-1:-1]  @ line -1, column -1.

Is this pattern no longer supported? I tried adding abstract to be BaseController declaration (it wasn't necessary in Grails 1.3.7), but that didn't seem to make any difference. I compiled my code after a clean, if that matters.

PS: To those who can: please create a grails-2.2 tag

like image 205
Gene Golovchinsky Avatar asked Dec 11 '22 19:12

Gene Golovchinsky


1 Answers

Remove def grailsApplication - the field is already added to the class bytecode via an AST transformation as a typed field (GrailsApplication) so your def field creates a second get/set pair with a weaker type (Object).

like image 166
Burt Beckwith Avatar answered Jan 24 '23 21:01

Burt Beckwith