Search

Dark theme | Light theme

October 20, 2009

Use GroovyDSL in IntelliJ IDEA Community Edition

If we define our own DSL or use dynamically added methods or properties we can use GroovyDSL to enable code completion in our project. Normally IntelliJ IDEA doesn't know about a DSL or dynamically added properties and methods, but we can describe them in GroovyDSL. GroovyDSL is a small framework we use to describe new behaviour of Groovy scripts. In an earlier post we saw how can use Dynamic properties to get a similar effect.

In this post we write a GroovyDSL script to enable code completion for Groovlets' implicit variables, like request, repsonse and application. We start by creating a new Groovy script in our project. We right-click on the src node and select Groovy script from the popup menu. We get a dialog window where we fill in the name of our script, groovletTransform, and change the Kind to GroovyDSL script:

We click the OK button and IntelliJ IDEA adds the file groovletTransform.gdsl to our project. We use the following code to define the DSL:

// Create context for Groovy script files which names end with groovlet.
def groovletContext = context(filetypes: ['groovlet'], scope: scriptScope())

contributor(groovletContext) {
    property name: 'request', type: 'javax.servlet.http.HttpServletRequest'
    property name: 'response', type: 'javax.servlet.http.HttpServletResponse'
    property name: 'session', type: 'javax.servlet.http.HttpSession'
    property name: 'application', type: 'javax.servlet.ServletContext'
    property name: 'context', type: 'javax.servlet.ServletContext'
    property name: 'params', type: 'java.util.LinkedHashMap'
    property name: 'headers', type: 'java.util.LinkedHashMap'
    property name: 'html', type: 'groovy.xml.MarkupBuilder'
    property name: 'out', type: 'java.io.PrintWriter'
    property name: 'sout', type: 'javax.servlet.ServletOutputStream'

    method name: 'forward', type: 'void', params: [path: 'java.lang.String']
    method name: 'include', type: 'void', params: [path: 'java.lang.String']
    method name: 'redirect', type: 'void', params: [path: 'java.lang.String']
}

At the top of our editor window we get the following message: DSL descriptor file has been changed and isn't currently executed. Click to activate it back. We click on this message and a popup menu with the action Activate appears:

We select Activate and now the rules in our DSL are active for our project. So we can create a new Groovy script with the extension groovlet and in the editor we get code completion for the variables and methods that are available for Groovlets:

It takes some extra effort, but especially when we define our own DSL or on a large project adding code completion for dynamic properties and methods can save a lot of time (and errors) in the long run.