Java Enterprise Java Learning Groovy for Java Programmers Tutorial

Learning Groovy for Java Programmers Tutorial

Depending on your background and experience, you are probably interested in
different features of Groovy. It is unlikely that anyone will require every aspect of
Groovy in their day-to-day work, just as no one uses the whole of the mammoth
framework provided by the Java standard libraries. To get a clear idea of why Groovy was developed and what drives its design see our earlier article, Your Way to Groovy.

This section presents interesting Groovy features and areas of applicability for
Java professionals, script programmers, and pragmatic, extreme, and agile programmers.

We recognize that developers rarely have just one role within their
jobs and may well have to take on each of these identities in turn. However, it is
helpful to focus on how Groovy helps in the kinds of situations typically associated
with each role.

Groovy for Java professionals

If you consider yourself a Java professional, you probably have years of experience
in Java programming. You know all the important parts of the Java Runtime
API and most likely the APIs of a lot of additional Java packages.

But-be honest-there are times when you cannot leverage this knowledge,
such as when faced with an everyday task like recursively searching through all
files below the current directory. If you’re like us, programming such an ad-hoc
task in Java is just too much effort.

But as you will learn in this book, with Groovy you can quickly open the console
and type

groovy -e "new File('.').eachFileRecurse { println it }"

to print all filenames recursively.

Even if Java had an eachFileRecurse method and a matching FileListener
interface, you would still need to explicitly create a class, declare a main method,
save the code as a file, and compile it, and only then could you run it. For the sake
of comparison, let’s see what the Java code would look like, assuming the existence
of an appropriate eachFileRecurse method:

Notice how the intent of the code (printing each file) is obscured by the scaffolding
code Java requires you to write in order to end up with a complete program.

Besides command-line availability and code beauty, Groovy allows you to bring
dynamic behavior to Java applications, such as through expressing business rules,
allowing smart configurations, or even implementing domain specific languages.

You have the options of using static or dynamic types and working with precompiled
code or plain Groovy source code with on-demand compiling. As a
developer, you can decide where and when you want to put your solution “in
stone” and where it needs to be flexible. With Groovy, you have the choice.

This should give you enough safeguards to feel comfortable incorporating
Groovy into your projects so you can benefit from its features.

Groovy for script programmers

As a script programmer, you may have worked in Perl, Ruby, Python, or other
dynamic (non-scripting) languages such as Smalltalk, Lisp, or Dylan.

But the Java platform has an undeniable market share, and it’s fairly common
that folks like you work with the Java language to make a living. Corporate clients
often run a Java standard platform (e.g. J2EE), allowing nothing but Java to be
developed and deployed in production. You have no chance of getting your ultraslick
scripting solution in there, so you bite the bullet, roll up your sleeves, and
dig through endless piles of Java code, thinking all day, “If I only had [your language
here
], I could replace this whole method with a single line!” We confess to
having experienced this kind of frustration.

Groovy can give you relief and bring back the fun of programming by providing
advanced language features where you need them: in your daily work. By
allowing you to call methods on anything, pass blocks of code around for immediate
or later execution, augment existing library code with your own specialized
semantics, and use a host of other powerful features, Groovy lets you express
yourself clearly and achieve miracles with little code.

Just sneak the groovy-all-*.jar file into your project’s classpath, and
you’re there.

Today, software development is seldom a solitary activity, and your teammates
(and your boss) need to know what you are doing with Groovy and what Groovy is
about. This book aims to be a device you can pass along to others so they can
learn, too. (Of course, if you can’t bear the thought of parting with it, you can tell
them to buy their own copies. We won’t mind.)

Groovy for pragmatic programmers, extremos, and agilists

If you fall into this category, you probably already have an overloaded bookshelf,
a board full of index cards with tasks, and an automated test suite that threatens
to turn red at a moment’s notice. The next iteration release is close, and there is
anything but time to think about Groovy. Even uttering the word makes your
pair-programming mate start questioning your state of mind.

One thing that we’ve learned about being pragmatic, extreme, or agile is that
every now and then you have to step back, relax, and assess whether your tools
are still sharp enough to cut smoothly. Despite the ever-pressing project schedules,
you need to sharpen the saw regularly. In software terms, that means having
the knowledge and resources needed and using the right methodology, tools,
technologies, and languages for the task at hand.

Groovy will be an invaluable tool in your box for all automation tasks that you
are likely to have in your projects. These range from simple build automation,
continuous integration, and reporting, up to automated documentation, shipment,
and installation. The Groovy automation support leverages the power of
existing solutions such as Ant and Maven, while providing a simple and concise
language means to control them. Groovy even helps with testing, both at the unit
and functional levels, helping us test-driven folks feel right at home.

Hardly any school of programmers applies as much rigor and pays as much
attention as we do when it comes to self-describing, intention-revealing code. We
feel an almost physical need to remove duplication while striving for simpler
solutions. This is where Groovy can help tremendously.

Before Groovy, I (Dierk) used other scripting languages (preferably Ruby) to
sketch some design ideas, do a spike-a programming experiment to assess the
feasibility of a task-and run a functional prototype. The downside was that I was
never sure if what I was writing would also work in Java. Worse, in the end I had
the work of porting it over or redoing it from scratch. With Groovy, I can do all
the exploration work directly on my target platform.

EXAMPLE

Recently, Guillaume and I did a spike on prime number disassembly.¹ We
started with a small Groovy solution that did the job cleanly but not efficiently.
Using Groovy’s interception capabilities, we unit-tested the solution
and counted the number of operations. Because the code was clean,
it was a breeze to optimize the solution and decrease the operation count.
It would have been much more difficult to recognize the optimization
potential in Java code. The final result can be used from Java as it stands,
and although we certainly still have the option of porting the optimized
solution to plain Java, which would give us another performance gain, we
can defer the decision until the need arises.

The seamless interplay of Groovy and Java opens two dimensions of optimizing
code: using Java for code that needs to be optimized for runtime performance, and
using Groovy for code that needs to be optimized for flexibility and readability.

Along with all these tangible benefits, there is value in learning Groovy for its
own sake. It will open your mind to new solutions, helping you to perceive new
concepts when developing software, whichever language you use.

No matter what kind of programmer you are, we hope you are now eager to
get some Groovy code under your fingers.

Running Groovy

First, we need to introduce you to the tools you’ll be using to run and optionally
compile Groovy code. If you want to try these out as you read, you’ll need
to have Groovy installed, of course.

There are three commands to execute Groovy code and scripts, as shown in
Table 1. Each of the three different mechanisms of running Groovy is demonstrated
in the following sections with examples and screenshots. Groovy can also
be “run” like any ordinary Java program, as you will see in the section “Running a compiled Groovy script with Java”, and there
also is a special integration with Ant that is explained in the section “Compiling and running with Ant”.

Table 1 Commands to execute Groovy

Using groovysh for “Hello World”

Let’s look at groovysh first because it is a handy tool for running experiments
with Groovy. It is easy to edit and run Groovy iteratively in this shell, and
doing so facilitates seeing how Groovy works without creating and editing
script files.

To start the shell, run groovysh (UNIX) or groovysh.bat (Windows) from the
command line. You should then get a command prompt like this:

Lets get Groovy!
================
Version: 1.0-RC-01-SNAPSHOT JVM: 1.4.2_05-b04
Type 'exit' to terminate the shell
Type 'help' for command help
Type 'go' to execute the statements

groovy>

The traditional “Hello World!” program can be written in Groovy with one line
and then executed in groovysh with the go command:

groovy> "Hello, World!"
groovy> go

===> Hello, World!

The go command is one of only a few commands the shell recognizes. The rest
can be displayed by typing help on the command line:

groovy> help
Available commands (must be entered without extraneous characters):
exit/quit - terminates processing
help - displays this help text
discard - discards the current statement
display - displays the current statement
explain - explains the parsing of the current statement (currently
disabled)
execute/go - temporary command to cause statement execution
binding - shows the binding used by this interactive shell
discardclasses - discards all former unbound class definitions
inspect - opens ObjectBrowser on expression returned from
previous "go"

The go and execute commands are equivalent. The discard command tells Groovy to forget the last line typed, which is useful when you’re typing in a long script, because the command facilitates clearing out the small sections of code rather than having to rewrite an entire script from the top. Let’s look at the other commands.

Display command

The display command displays the last noncommand statement entered:

    groovy> display
1>	"Hello World!"
Binding command

The binding command displays variables utilized in a groovysh session. We haven’t used any variables in our simple example, but, to demonstrate, we’ll alter our “Hello World!” using the variable greeting to hold part of the message we
print out:

groovy> greeting = "Hello"
groovy> "${greeting}, World!"
groovy> go

===> Hello, World!

groovy> binding
Available variables in the current binding
greeting = Hello

The binding command is useful when you’re in the course of a longer groovysh session and you’ve lost track of the variables in use and their current values.

To clear the binding, exit the shell and start a new one.

Inspect command

The inspect command opens the Groovy Object Browser on the last evaluated
expression. This browser is a Swing user interface that lets you browse through an
object’s native Java API and any additional features available to it via Groovy’s
GDK. Figure 1 shows the Object Browser inspecting an instance of String. It
contains information about theString class in the header and two tables showing
available methods and fields.

Figure 1: The Groovy Object Browser when opened on an object of type
String, displaying the table of available methods in its bytecode and registered Meta methods
.

Look at the second and third rows. A method with the name center is available
on a String object. It takes a Number parameter (second row) and an optional
String parameter (third row). The method’s return type is a String. Groovy
defined this new public method on the String class.

If you are anything like us, you cannot wait to try that new knowledge in the
groovysh and type

groovy> 'test'.center 20, '-'
groovy> go

===> --------test--------

That’s almost as good as IDE support!

For easy browsing, you can sort columns by clicking the headers and reverse the
sort with a second click. You can sort by multiple criteria by clicking column headers
in sequence, and rearrange the columns by dragging the column headers.

Future versions of the Groovy Object Browser may provide even more sophisticated
features.

Using groovyConsole

The groovyConsole is a Swing interface that acts as a minimal Groovy interactive
interpreter. It lacks support for the command-line options supported by
groovysh; however, it has a File menu to allow Groovy scripts to be loaded, created,
and saved. Interestingly, groovyConsole is written in Groovy.

The groovyConsole takes no arguments and starts a two-paned Window like
the one shown in figure 5. The console accepts keyboard input in the upper
pane. To run a script, either key in Ctrl+R, Ctrl+Enter or use the Run command
from the Action menu to run the script. When any part of the script code is
selected, only the selected text is executed. This feature is useful for simple
debugging or single stepping by successively selecting one or multiple lines.

The groovyConsole's File menu has New, Open, Save, and Exit commands.
New opens a new groovyConsole window. Open can be used to browse to a
Groovy script on the file system and open it in the edit pane for editing and running.
Save can be used to save the current text in the edit pane to a file. Exit
quits the groovyConsole.

The Groovy Object Browser as shown in figure 2 is equally available in
groovyConsole and also operates on the last evaluated expression. To open the
browser, press Ctrl+I (for inspect) or choose Inspect from the Actions menu.

Figure 2: The groovyConsole with a simple script in the edit pane that calculates the circumference of a circle based on its diameter. The result is in the output pane.

That’s it for groovyConsole. Whether you prefer working in groovysh or groovyConsole is a personal choice. Script programmers who perform their work in command shells tend to prefer the shell.

AUTHOR’S CHOICE

I (Dierk) personally changed my habits to use the console more often for
the sake of less typing through cut-and-paste in the edit pane.

Unless explicitly stated otherwise, you can put any code example in this article
directly into groovysh or groovyConsole and run it there. The more often you do that, the earlier you will get a feeling for the language.

Using groovy

The groovy command is used to execute Groovy programs and scripts. For example,
Listing 1 shows the obligatory Fibonacci² number sequence Groovy program
that prints the first 10 Fibonacci numbers. The Fibonacci number sequence
is a pattern where the first two numbers are 1 and 1, and every subsequent number
is the sum of the preceding two.

If you’d like to try this, copy the code into a file, and save it as Fibonacci.
groovy. The file extension does not matter much as far as the groovy executable is
concerned, but naming Groovy scripts with a .groovy extension is conventional.
One benefit of using an extension of .groovy is that you can omit it on the command
line when specifying the name of the script-instead of groovy MyScript.
Groovy
, you can just run groovy MyScript.

Listing 1 Fibonacci.groovy

Run this file as a Groovy program by passing the file name to the groovy command.
You should see the following output:

> groovy Fibonacci
1 1 2 3 5 8 13 21 34 55

The groovy command has many additional options that are useful for commandline
scripting. For example, expressions can be executed by typing groovy -e
"println 1+1"
, which prints 2 to the console.

In this section, we have dealt with Groovy's support for simple ad-hoc scripting,
but this is not the whole story. The next section expands on how Groovy fits
into a code-compile-run cycle.

Compiling and running Groovy

So far, we have used Groovy in direct mode, where our code is directly executed
without producing any executable files. In this section, you will see a second way
of using Groovy: compiling it to Java bytecode and running it as regular Java
application code within a Java Virtual Machine (JVM). This is called precompiled
mode. Both ways execute Groovy inside a JVM eventually, and both ways compile
the Groovy code to Java bytecode. The major difference is when that compilation
occurs and whether the resulting classes are used in memory or stored on disk.

Compiling Groovy with groovyc

Compiling Groovy is straightforward, because Groovy comes with a compiler
called groovyc. The groovyc compiler generates at least one class file for each Groovy source file compiled. As an example, we can compile Fibonacci.groovy
from the previous section into normal Java bytecode by running groovyc on the
script file like so:

> groovyc -d classes Fibonacci.groovy

In our case, the Groovy compiler outputs two Java class files to a directory named
classes, which we told it to do with the -d flag. If the directory specified with -d does not exist, it is created. When you're running the compiler, the name of each
generated class file is printed to the console.

For each script, groovyc generates a class that extends groovy.lang.Script, which contains a main method so that java can execute it. The name of the compiled class matches the name of the script being compiled.

More classes may be generated, depending on the script code; however, we
don't really need to care about that because that is a Java platform topic. In
essence, groovyc works the same way that javac compiles nested classes.

NOTE

The Fibonacci script contains the 10.times{} construct that causes
groovyc to generate a class of type closure, which implements what is
inside the curly braces. This class is nested inside the Fibonacci class. If you find this confusing, you
can safely ignore it for the time being.

The mapping of class files to implementations is shown in Table 1, with the purpose
of each explained.

Table 1 Classes generated by groovyc for the Fibonacci.groovy file

Now that we've got a compiled program, let's see how to run it.

Running a compiled Groovy script with Java

Running a compiled Groovy program is identical to running a compiled Java program,
with the added requirement of having the embeddable groovy-all*.jar file in
your JVM's classpath, which will ensure that all of Groovy's third-party dependencies
will be resolved automatically at runtime. Make sure you add the directory in which
your compiled program resides to the classpath, too. You then run the program in
the same way you would run any other Java program, with the java command.³

> java -cp %GROOVY_HOME%/embeddable/groovy-all-1.0.jar;classes Fibonacci
1 1 2 3 5 8 13 21 34 55

Note that the .class file extension for the main class should not be specified when
running with java.

All this may seem like a lot of work if you're used to building and running your
Java code with Ant at the touch of a button. We agree, which is why the developers
of Groovy have made sure you can do all of this easily in an Ant script.

Compiling and running with Ant

An Ant task is shipped with Groovy for running the groovyc compiler in an Ant
build script. To use it, you need to have Ant installed.&sup4; We recommend version 1.6.2
or higher.

Listing 2 shows an Ant build script, which compiles and runs the
Fibonacci.groovy script as Java bytecode.

Listing 2 build.xml for compiling and running a Groovy program as Java bytecode

Store this file as build.xml in your current directory, which should also contain
the Fibonacci.groovy script, and type ant at the command prompt.

The build will start at the run target, which depends on the compile target
and therefore calls that one first. The compile target is the one that uses the
groovyc task. In order to make this task known to Ant, the
taskdef is used.
It finds the implementation of the groovyc task by referring to the groovy.
classpath in the path definition.

When everything compiles successfully in the compile target, the run target calls the java task on the compiled classes.

You will see output like this:

> ant
Buildfile: build.xml

compile:
     [mkdir] Created dir: …classes
   [groovyc] Compiling 1 source file to …classes
run:

      [java] 1 1 2 3 5 8 13 21 34 55

BUILD SUCCESSFUL
Total time: 2 seconds

Executing ant a second time shows no compile output, because the groovyc task is smart enough to compile only when necessary. For a clean compile, you have to
delete the destination directory before compiling.

The groovyc Ant task has a lot of options, most of which are similar to those in
the javac Ant task. The srcdir and destdir options are mandatory.

Using groovyc for compilation can be handy when you're integrating Groovy
in Java projects that use Ant (or Maven) for build automation..

Groovy IDE and editor support

If you plan to code in Groovy often, you should look for Groovy support for your
IDE or editor of choice. Some editors only support syntax highlighting for
Groovy at this stage, but even that can be useful and can make Groovy code more
convenient to work with. Some commonly used IDEs and text editors for Groovy
are listed in the following sections.

This section is likely to be out of date as soon as it is printed. Stay tuned for
updates for your favorite IDE, because improved support for Groovy in the major
Java IDEs is expected in the near future. Sun Microsystems recently announced
Groovy support for its NetBeans coyote project (https://coyote.dev.java.net/), which
is particularly interesting because it is the first IDE support for Groovy that is
managed by the IDE's own vendor itself.

IntelliJ IDEA plug-in

Within the Groovy community, work is ongoing to develop an open-source plugin
called GroovyJ. With the help of this plug-in and IDEA's built-in features, a
Groovy programmer can benefit from the following:

  • Simple syntax highlighting based on user preferences: GroovyJ currently
    uses Java 5's syntax highlighter, which covers a large proportion of the
    Groovy syntax. Version 1.0 will recognize the full Groovy syntax and allow
    customization of the highlighting through the Colors & Fonts panel, just as
    it is possible with the Java syntax.

  • Code completion: To date, code completion is limited to word completion,
    leveraging IDEA's word completion based on an on-the-fly dictionary for
    the current editor only.

  • Tight integration with IDEA's compile, run, build, and make configuration as
    well as output views.

  • Lots of advanced editor actions that can be used as in Java.
  • Efficient lookup for all related Java classes in the project or dependent
    libraries.

  • Efficient navigation between files, including .groovy files.
  • A Groovy file-type icon.

GroovyJ has a promising future, which is greatly dependent on its implementation
of IDEA's Program Structure Interface (PSI) for the Groovy language. It will do
so by specializing the Groovy grammar file and generating a specialized parser
for this purpose. Because IDEA bases all its advanced features (such as refactoring
support, inspections, navigation, intentions, and so forth) on the PSI, it seems to
be only a matter of time before we will see these features for Groovy.

GroovyJ is an interesting project, mindfully led by Franck Rasolo. This plug-in
is one of the most advanced ones available to Groovy at this point. For more information,
see http://groovy.codehaus.org/GroovyJ+Status.

Eclipse plug-in

The Groovy plug-in for Eclipse requires Eclipse 3.1.1 or newer. The plug-in will
also run in Eclipse 3.x-derived tools such as IBM Rational's Rational Application
Developer and Rational Software Architect. As of this writing, the Groovy Eclipse
plug-in supports the following features:

  • Syntax highlighting for Groovy files
  • A Groovy file decorator (icon) for Groovy files in the Package Explorer and
    Resources views

  • Running Groovy scripts from within the IDE
  • Auto-build of Groovy files
  • Debugger integration

The Groovy Eclipse plug-in is available for download at http://groovy.codehaus.org/
Eclipse+Plugin.

Groovy support in other editors

Although they don't claim to be full-featured development environments, a lot of
all-purpose editors provide support for programming languages in general and
Groovy in particular.

UltraEdit can easily be customized to provide syntax highlighting for Groovy
and to start or compile scripts from within the editor. Any output goes to an integrated
output window. A small sidebar lets you jump to class and method declarations
in the file. It supports smart indentation and brace matching for Groovy.
Besides the Groovy support, it is a feature-rich, quick-starting, all-purpose editor.
Find more details at http://groovy.codehaus.org/UltraEdit+Plugin.

The JEdit plug-in for Groovy supports executing Groovy scripts and code snippets
from within the editor. A syntax-highlighting configuration is available separately.
More details are available here: http://groovy.codehaus.org/JEdit+Plugin.
Syntax highlighting configuration files for TextPad, Emacs, Vim, and several
other text editors can be found on the Groovy web site at http://groovy.codehaus.org/Other+Plugins.

When programming small ad-hoc Groovy scripts, I (Dierk) personally use
UltraEdit on Windows and Vim on Linux. For any project of some size, I
use IntelliJ IDEA with the GroovyJ plug-in.

AUTHOR'S CHOICE

As Groovy matures and is adopted among Java programmers, it will continue to
gain support in Java IDEs with features such as debugging, unit testing, and
dynamic code-completion.

Summary

We hope that by now we've convinced you that you really want Groovy in your life.
As a modern language built on the solid foundation of Java and with support
from Sun, Groovy has something to offer for everyone, in whatever way they
interact with the Java platform.

With a clear idea of why Groovy was developed and what drives its design, you
should have been able to see where features fit into the bigger picture. Keep in mind the principles of Java integration and feature richness, making common tasks simpler and your code more expressive.

Once you have Groovy installed, you can run it both directly as a script and
after compilation into classes. If you have been feeling energetic, you may even
have installed a Groovy plug-in for your favorite IDE. With this preparatory work
complete, you are ready to see (and try!) more of the language itself.

References

  • ¹ Every ordinal number N can be uniquely disassembled into factors that are prime numbers: N =
    p1*p2*p3. The disassembly problem is known to be "hard." Its complexity guards cryptographic algorithms
    like the popular Rivest-Shamir-Adleman (RSA) algorithm.

  • ² Leonardo Pisano (1170..1250), aka Fibonacci, was a mathematician from Pisa (now a town in Italy). He
    introduced this number sequence to describe the growth of an isolated rabbit population. Although this
    may be questionable from a biological point of view, his number sequence plays a role in many different
    areas of science and art. For more information, you can subscribe to the Fibonacci Quarterly.

  • ³ The command line as shown applies to Windows shells. The equivalent on Linux/Solaris/UNIX/Cygwin
    would be java -cp $GROOVY_HOME/embeddable/groovy-all-1.0.jar:classes Fibonacci

  • &sup4; Groovy ships with its own copy of the Ant jar files that could also be used for this purpose, but it is
    easier to explain with a standalone installation of Ant.

About the Authors

Dierk Koenig is a senior software developer, mentor and coach. He publishes in leading German magazines on software development and speaks at international conferences. He works at Canoo Engineering AG, Basel, Switzerland, where he is the founding partner and member of the executive board. He joined the Groovy project in 2004 working as a committer ever since.

Andrew Glover is the President of Stelligent Incorporated which helps companies address software quality with effective developer testing strategies and continuous integration techniques that enable teams to monitor code quality early and often. He actively blogs about software quality at thediscoblog.com and testearly.com.

Dr Paul King is Managing Director and Principal Consultant for ASERT, an Australian company specialising in helping its customers leverage emerging technologies. He has provided technical and strategic consulting to hundreds of organizations throughout the U.S. and Asia Pacific and is an active contributor to many open source projects. When not being a taxi service for his seven children, you will find Paul tinkering with the latest Agile or enterprise technologies.

As the official Groovy Project Manager and member of the JSR-241 Expert Group standardizing the Groovy Scripting Language, Guillaume Laforge is a passionate Groovy developer. In his professional career, Guillaume is a software architect and Open Source consultant, working for OCTO Technology, a company focusing on architecture of software and information systems

Jon Skeet is a software engineer and inveterate technological dabbler who happens to specialise in Java and C# development. A recent convert to Groovy, Jon is fanatical about using smarter ways to write cleaner, more readable code.

Source of This Material

Groovy in Action
By Dierk Koenig with Andrew Glover, Paul King, Guillaume Laforge & Jon Skeet

Published: January, 2007, Paperback: 696 pages
Published by Manning Publications
ISBN: 1932394842
Retail price: $44.99 for the Softbound print book + PDF ebook or $25.00 for the PDF ebook both through www.manning.com.

This material is from Chapter 1 of the book.

Latest Posts

Related Stories