Quick setup to use groovy with maven and OpenEJB


Using groovy often makes dev time easier and faster. Since groovy is compilable to java bytecode we should be able to use it even in JEE. Here a short tutorial on the way to do it.

First configure your compiler plugin to manage groovy (using multiple executions make the java+groovy management easy):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.4</version>
    <configuration>
      <compilerId>groovy-eclipse-compiler</compilerId>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
    <dependencies>
    <dependency>
     <groupId>org.codehaus.groovy</groupId>
     <artifactId>groovy-eclipse-compiler</artifactId>
     <version>2.6.0-01</version>
    </dependency>
  </dependencies>
</plugin>

Then simply write your main or test code (that’s probably a great place to start) in groovy.

Here a sample CDI bean:

package org.superbiz.groovy

class Hello {
    def hi() {
        "hi"
    }
}

And finally an Arquillian test:

package org.superbiz.groovy

import org.junit.runner.RunWith
import org.jboss.arquillian.junit.Arquillian
import org.jboss.arquillian.container.test.api.Deployment
import org.jboss.shrinkwrap.api.spec.WebArchive
import org.jboss.shrinkwrap.api.ShrinkWrap
import org.apache.ziplock.JarLocation
import javax.inject.Inject
import org.junit.Test

import static org.junit.Assert.assertEquals
import static org.junit.Assert.assertNotNull
import org.jboss.shrinkwrap.api.asset.EmptyAsset
import org.jboss.shrinkwrap.api.ArchivePaths

@RunWith(Arquillian.class)
class HelloTest {
    @Inject
    private Hello hello

    @Deployment
    static WebArchive war() {
        ShrinkWrap.create(WebArchive.class) // to managed depdendencies
            .addAsLibraries(JarLocation.jarLocation(GroovyObject.class)) // groovy-all
            .addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")) // cdi on
            .addClasses(Hello.class) // app classes
    }

    @Test
    void hello() {
        assertNotNull hello
        assertEquals "hi", hello.hi()
    }
}

This sample can be found here: http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/groovy-cdi

Groovy is pretty fine in particular for JPA entities or JSF backend beans (avoiding getters/setters, easy looping over collections…). Another great usage is to integrate some groovy testing framework like Spock (http://code.google.com/p/spock/).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s