Anthony Goubard is a freelance Senior Software Engineer from Amsterdam. He has developed in Java since 1995. He has developed many softwares available at http://www.japplis.com and is the main developer of the Web Services framework XINS. Anthony is a DZone MVB and is not an employee of DZone and has posted 33 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy in One Day

05.25.2009
| 15266 views |
  • submit to reddit

After JavaFX, now let's have a look at Groovy. Note that I already had a quick look at it when 1.0 has been released and I wrote one of the XINS Web Services demo using Groovy.

Installation

The Getting started guide page tells us to download the installer and set up some environment variables.The default install directory is C:\Program Files\Groovy\Groovy-1.6.3 but as it seems to have problems with spaces in directories, I'll install it somewhere else (and without any version number in the directory name).

The installer is quite smart as it sets the environment variable for you and even register the .groovy and .gy with the groovy executable.

Groovy is released under the Apache 2.0 license.You also have a NetBeans plug-in. In Tools -> Plug-ins, choose Groovy and Grails, and restart the IDE.You can also run Groovy console with Web Start in the sandbox.

The language

The user guide is available at http://groovy.codehaus.org/User+Guide.

The keywords:

  • Same as Java
  • def, it, is, as
  • for (in)

Some explanations:

  • Methods and classes are by default public
  • Inner classes are not supported
  • return and ; are optional

The full list of reserved keywords is available here.

Operators:

Use .intdiv() to divide integers.
def displayName = user.name ?: "Anonymous" // Anonymous when user.name is null
parent?.child to avoid if (parent != null) ...

The main classes

  • Standard Java classes
  • GString
  • GroovyServlet,SimpleTemplateEngine,GPath
  • AntBuilder,SwingBuilder,MarkupBuilder

Helloworld

Writing the app
In NetBeans File -> New Project -> Samples -> Groovy -> Groovy-Java Demo.
The demo can already be started.
Delete the Java file and rename the other file as Helloworld.groovy and write

package demo
import groovy.swing.SwingBuilder
import javax.swing.JFrame
def swing = new SwingBuilder()
def frame = swing.frame(title:'Helloworld', size:[250,80]) {
def hello = label(text:"Helloworld!")
hello.font = hello.font.deriveFont(16.0f)
}
frame.show()

Documentation
Javadoc: As for JavaFX, the documentation and the examples seem to skip this step.
In Netbeans you can right-click on the project and choose Generate Javadoc, this will leave an error No source files and no packages have been specified.

Distribution
In Groovy\embeddable you have a groovy-all-1.6.3.jar which contains the classes needed to run you Groovy application if you only use classes from JavaSE and Groovy.
The build.xml includes a jar target, execute it will put the application files in the dist directory. You may want to edit nbproject/project.properties with dist.jar=${dist.dir}/helloworld.jar and remove Swing layout from the libraries (as not use for helloworld).
You may also want to replace dist\lib\groovy-all-1.5.5.jar with 1.6.3 as NetBeans plug-in comes with 1.5.5.

Concepts

Closure

Closure allows to consider a function as a variable type (a bit like java.lang.reflect.Method).

def uppercaseClosure = { it.toUpperCase() }
def list = 'a'..'g'
def uppercaseList = []
list.collect( uppercaseList, uppercaseClosure )
def loginSA = database.login("sa", "")
loginSA()
def printSum = { a, b -> print a + b }
def printPlus1 = printSum.curry(1)
printPlus1(7) // prints 8

Builders in Groovy are based on closures.

Builders
Builders allows to create structure object using declaration instead of calling methods. The syntax is similar to JSON.

Example of builders in Groovy are SwingBuilder (used for helloworld), MarkupBuilder (for XML), ObjectGraphBuilder (for POJO), AntBuilder/Gant, GraphicsBuilder, HTTPBuilder.
You can of course create your own builder.

GString


def name = "James" // normal String
def text = """\
hello there ${name}
how are you today?
""" // GString because it uses ${} and multiline with the """

Templates

Templates allows to insert text and function calls in a text.


def joe = [name:"John Doe"]
def engine = new SimpleTemplateEngine()
template = engine.createTemplate(text).make(joe)
assert template.toString() == "\nhello John Doe\nhow are you today?\n"

Use <% code %> to execute code/functions in the template.

Regular expressions
You can use java.util.regex.Matcher and java.util.regex.Pattern classes as in Java.

def pattern = ~/foo/ // Same as new Pattern("foo")
def matcher = "cheesecheese" =~ /cheese/ // Same as new Pattern("cheese").matcher("cheesecheese")
def matches = "cheesecheese" ==~ /cheese/ // Same as new Pattern("cheese").matcher("cheesecheese").matches();

The occurence of the matcher can be accessed as are collections. e.g.

matcher[1]
for the second match or
matcher[0, 1..2]
for a collection of the first 3 matches.

Collections

def list1 = [1, 2, 3, 4]
def list2 = 5..10
println("second element: ${list2[1]}")
def list3 = list2.findAll{ i -> i >= 7 } // Using closure to create a subset of list2
def list4 = list2[2..5] // Getting the same subset, 2 and 5 are indexes not values
def map1 = [name:"Gromit", likes:"cheese", id:1234]
def map2 = [(map1):"mouse"]
def list5 = list2*.multiply(2) // list5 contains list2 items * 2

Lists can also be defined in for and switch statements: for (i in 1..10) or case 1,2,6..10:
<< seems to be used to add elements but I couldn't find it in the documentation.

Classes and functions

You don't have that much documentation on how to do it.

package mypackage
import java.io.File
import groovy.swing.SwingBuilder
/**
* My class.
* @author Me
*/
class MyClass {
// class variable
def myVar = ""
/**
* My method
* @param text
* Some text.
*/
String addText(String text) {
myVar += text
}
void main(String[] args) {
print addText("hello")
}
}

 

Grails

I cannot talk about Groovy without mentioning Grails.Grails is a Server - Database framework inspired by Ruby on Rails and based on Spring + Hibernate. Grails heavily uses Groovy in order to minimize the code to write to create a server - database application.It uses GROM (Grails Object Relational Mapping) which is based on Hibernate.

The domain classes are simple POJOs containing the objects to manage/store/show. e.g. User, Book, Car, ... Contraints can be defined in the constraints closure. e.g.def constraints = { firstName(blank:false) }

For relationship use static hasMany = [books: Book], static mappedBy, static belongsTo.
The controllers are the action classes, the classes methods will be called when a form is submitted. e.g. class UserController { def doLogin = { ... } }

In configuration you have BootStrap.groovy to manage the application life cycle and DataSource.groovy to specify the location of the database.
The i18n directory contains the error messages.
The view (HTML pages) uses per default GSP (Groovy Server Pages).
To release the project, right click on the project and select Create War File.
Grails release includes a Petclinic demo.
Getting started articles here and here
There is a video demo on netbeans.tv
The reference documentation is available at http://grails.org/doc/1.1.1/.

Other

There are no examples with the release (except for ActiveX with Scriptom), examples are online

Code completion in NetBeans was weak.
Groovy supports annotations.
Groovy has bindings with groovy.beans.Bindable.

@Bindable String prop
textField(text:bind(source:this, sourceProperty:'prop'))

Grape is a system to include libraries in a repository. Grape will download the dependency Jar files if needed when starting your application. For Swing development, you have doOutside { } to execute code outside the EDT and inside it you can have edt { } when a part of the code needs to be on the EDT. Griffon is a groovy desktop application framework.

Integration with Java

From Groovy to Java, just use the Java class as you would do in Java. Note that 10.0 is a BigDecimal, 10.0f is a java.lang.Float and 10.0d is a java.lang.Double.
From Java to Groovy, use the javax.script.* classes.

Conclusion

Groovy introduces new concepts making code smaller to write. You need to make sure that the code compactness will not come to the cost of code readability. Buying a book could be useful for more examples and more documentation. Groovy developers seem to agree that the best IDE for Groovy/Grails is IntelliJ IDEA.

Pro's

  • Builders
  • Useful for client and server side applications
  • Collection
  • Feature rich
  • Windows installer

Con's

  • More complicated to learn than Java
  • Examples are more code snippets than small applications. (More examples at sf.net)
  • Version numbers everywhere

From http://www.jroller.com/agoubard/

Published at DZone with permission of Anthony Goubard, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Andres Almiray replied on Mon, 2009/05/25 - 1:48am

Anthony, I'm not sure the language is actually that complicated to learn, it is actually quite simple, it adds a few keywords and supports most of the Java syntax (inner class definitions and array initializers being on the black list). Perhaps the library support that comes along is the complex one, Iwould argue that point too, jsut look at Swing!

Too much sweetness to take in just 8 hrs IMHO, but keep it going :-)

Anthony Goubard replied on Mon, 2009/05/25 - 3:26am in response to: Andres Almiray

Andres, what I meant was the language as I see Groovy = Java + closure + :? + ?. + """ + regexp + lists and maps creation. But at the end you benefit from these new features in the libraries such as Swing (Builder + binding) or Grails or list manipulation which are easier to use than the Java version.

Dean Del Ponte replied on Mon, 2009/05/25 - 9:31am

Groovy is more complicated to learn? I couldn't disagree more.

Sam Barnum replied on Tue, 2009/05/26 - 12:14am

Nice concise overview, although a few more code samples would have been nice. I'd like to see this "mile-high" view for more frameworks.

Jim Shingler replied on Tue, 2009/05/26 - 10:18am

Anthony,

 

Nice Article, and thank you for helping get the word out about the Groovy Technologies.

Based upon recent experiences by some associates, interns and new grads  were up to speed and productive quicker than they would have been in Java.

 I understand your point that it is like Java++ but the ++ part makes is significantly easier.

In some ways, Java 7 is trying to catchup to Groovy.  ;-)

 Jim

Mike P(Okidoky) replied on Fri, 2009/05/29 - 5:36pm

Groovy in one second flat: it's unacceptably slow.

Pratik Patel replied on Fri, 2009/06/05 - 12:50pm in response to: Mike P(Okidoky)

you're totally right. that's why I code everything in assembly language. Faster than anything on the planet.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.