Groovy 2 Cookbook

Groovy 2 Cookbook
eBook: $29.99
Formats: PDF, PacktLib, ePub and Mobi formats
save 15%!
Print + free eBook + free PacktLib access to the book: $79.98    Print cover: $49.99
save 37%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Table of Contents
Sample Chapters
  • Simple and more advanced recipes to cover a broad number of topics and challenges
  • With scores of practical examples, this book will help you to build efficient, flexible, and well-integrated systems
  • Solve everyday programming problems with the elegance and simplicity of Groovy 2

Book Details

Language : English
Paperback : 394 pages [ 235mm x 191mm ]
Release Date : October 2013
ISBN : 1849519366
ISBN 13 : 9781849519366
Author(s) : Andrey Adamovich, Luciano Fiandesio
Topics and Technologies : All Books, Application Development, Cookbooks, Java, Open Source

Table of Contents

Chapter 1: Getting Started with Groovy
Chapter 2: Using Groovy Ecosystem
Chapter 3: Using Groovy Language Features
Chapter 4: Working with Files in Groovy
Chapter 5: Working with XML in Groovy
Chapter 6: Working with JSON in Groovy
Chapter 7: Working with Databases in Groovy
Chapter 8: Working with Web Services in Groovy
Chapter 9: Metaprogramming and DSLs in Groovy
Chapter 10: Concurrent Programming in Groovy
Chapter 11: Testing with Groovy

  • Chapter 1: Getting Started with Groovy
    • Introduction
    • Installing Groovy on Windows
    • Installing Groovy on Linux and OS X
    • Executing Groovy code from the command line
    • Using Groovy as a command-line text file editor
    • Using Groovy to start a server on the command line
    • Running Groovy with invokedynamic support
    • Building Groovy from source
    • Managing multiple Groovy installations on Linux
    • Using groovysh to try out Groovy commands
    • Starting groovyConsole to execute Groovy snippets
    • Configuring Groovy in Eclipse
    • Configuring Groovy in IntelliJ IDEA
  • Chapter 2: Using Groovy Ecosystem
    • Introduction
    • Using Java classes from Groovy
    • Embedding Groovy into Java
    • Compiling Groovy code
    • Simplifying dependency management with Grape
    • Integrating Groovy into the build process using Ant
    • Integrating Groovy into the build process using Maven
    • Integrating Groovy into the build process using Gradle
    • Generating documentation for Groovy code
    • Checking Groovy code's quality with CodeNarc
  • Chapter 3: Using Groovy Language Features
    • Introduction
    • Searching strings with regular expressions
    • Writing less verbose Java Beans with Groovy Beans
    • Inheriting constructors in Groovy classes
    • Adding the cloning functionality to Groovy Beans
    • Defining code as data in Groovy
    • Defining data structures as code in Groovy
    • Implementing multiple inheritance in Groovy
    • Adding a functionality to the existing Java/Groovy classes
    • Defining type-checking rules for dynamic code
    • Adding automatic logging to Groovy classes
  • Chapter 4: Working with Files in Groovy
    • Introduction
    • Reading from a file
    • Reading a text file line by line
    • Processing every word in a text file
    • Writing to a file
    • Replacing tabs with spaces in a text file
    • Filtering a text file's content
    • Deleting a file or directory
    • Walking through a directory recursively
    • Searching for files
    • Changing file attributes on Windows
    • Reading data from a ZIP file
    • Reading an Excel file
    • Extracting data from a PDF
  • Chapter 5: Working with XML in Groovy
    • Introduction
    • Reading XML using XmlSlurper
    • Reading XML using XmlParser
    • Reading XML content with namespaces
    • Searching in XML with GPath
    • Searching in XML with XPath
    • Constructing XML content
    • Modifying XML content
    • Sorting XML nodes
    • Serializing Groovy Beans to XML
  • Chapter 6: Working with JSON in Groovy
    • Introduction
    • Parsing JSON messages with JsonSlurper
    • Constructing JSON messages with JsonBuilder
    • Modifying JSON messages
    • Validating JSON messages
    • Converting JSON message to XML
    • Converting JSON message to Groovy Bean
    • Using JSON to configure your scripts
  • Chapter 7: Working with Databases in Groovy
    • Introduction
    • Creating a database table
    • Connecting to an SQL database
    • Querying an SQL database
    • Modifying data in an SQL database
    • Calling a stored procedure
    • Reading BLOB/CLOB from a database
    • Building a simple ORM framework
    • Using Groovy to access Redis
    • Using Groovy to access MongoDB
    • Using Groovy to access Apache Cassandra
  • Chapter 8: Working with Web Services in Groovy
    • Introduction
    • Downloading content from the Internet
    • Executing an HTTP GET request
    • Executing an HTTP POST request
    • Constructing and modifying complex URLs
    • Issuing a REST request and parsing a response
    • Issuing a SOAP request and parsing a response
    • Consuming RSS and Atom feeds
    • Using basic authentication for web service security
    • Using OAuth for web service security
  • Chapter 9: Metaprogramming and DSLs in Groovy
    • Introduction
    • Querying methods and properties
    • Dynamically extending classes with new methods
    • Overriding methods dynamically
    • Adding performance logging to methods
    • Adding a caching functionality around methods
    • Adding transparent imports to a script
    • DSL for executing commands over SSH
    • DSL for generating reports from logfiles
  • Chapter 10: Concurrent Programming in Groovy
    • Introduction
    • Processing collections concurrently
    • Downloading files concurrently
    • Splitting a large task into smaller parallel jobs
    • Running tasks in parallel and asynchronously
    • Using actors to build message-based concurrency
    • Using STM to atomically update fields
    • Using dataflow variables for lazy evaluation

Andrey Adamovich

Andrey Adamovich is a software craftsman with many years of experience in different lifecycle phases of software creation. He is passionate about defining good development practices, documenting and presenting architecture, the reuse of code and design patterns, the profiling and analysis of application performance, as well as extreme automation of development and operations activities. He is a longtime Groovy user and has a deep knowledge of the language internals. He uses Groovy in his day-to-day development job for simplifying the development process, which includes: code generation, super cool DSLs, and rapid prototyping. He has Master's degree in Computer Science from the Latvian State University.

Luciano Fiandesio

Luciano Fiandesio is a programmer, technology enthusiast, and entrepreneur living in Zurich, Switzerland. Luciano has been working for the last 18 years in 12 different countries as an architect and developer for large corporations and small start-ups: Nokia, European Central Bank, BNP Paribas, and Ericsson are among his clients. He loves coding and designing solutions that are both elegant and rock solid. When not busy learning the next big thing, he likes playing with his analog cameras and cooking Italian food. Two years ago, he started a consulting company focused on software factory automation, Aestas IT, where Groovy plays a big role. He holds a Master's degree in Literature and Philosophy from Rome University.

The authors have created support website for the book -

Code Downloads

Download the code and support files for this book.

Submit Errata

Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


- 5 submitted: last submission 08 May 2014

The authors have created support website for the book -



Errata type: Code related


Page number: 24


It is: groovy:000> helloClosure = { println ""Hello $it"" } ===> groovysh_evaluate$_run_closure1@7301061

It should be: groovy:000> helloClosure = { println "Hello $it" } ===> groovysh_evaluate$_run_closure1@7301061


Errata type: Code related


Page number: 106


It is: def e = new ExpensiveResource() 

try {
} finally {

It should be: def e = new ExpensiveResource() 

try {
e.writeData('Any String')
} finally {

Errata type: Typo | Page number: 187

The code:

def carXml = '''
<?xml version="1.0" ?>

Should be:

def carXml = '''<?xml version="1.0" ?>

The general syntax to be followed throughout the book is:
def todos = '''<?xml version="1.0" ?>
<task created...

Errata type: Code related | Page number: 249


It is:

jedis.rpush('myList', 'a', 'b', 'c')

assert 3 == jedis.llen('myList')

assert '1' == jedis.lrange('myList', 0,0)[0]

jedis.lpush('myList', '3', '2', '1')

assert 6 == jedis.llen('myList') 


It should be: 

jedis.del ("myList")
jedis.rpush('myList', 'a', 'b', 'c')
assert 3 == jedis.llen('myList')
jedis.lpush('myList', '3', '2', '1')
assert '1' == jedis.lrange('myList', 0,0)[0]
assert 6 == jedis.llen('myList')



Sample chapters

You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

Frequently bought together

Groovy 2 Cookbook +    Entity Framework 4.1: Expert’s Cookbook =
50% Off
the second eBook
Price for both: £29.05

Buy both these recommended eBooks together and get 50% off the cheapest eBook.

What you will learn from this book

  • Use Groovy with different IDEs and Operating Systems
  • Integrate Groovy with Java and understand the peculiar features of the language
  • Work with files of different formats, like PDF, Excel, and Zip
  • Manipulate XML and work with JSON
  • Access databases using the elegant Groovy API
  • Unleash the power of asynchronous programming using the advanced features of the GPars API
  • Learn how to use Groovy to test your Java code and other testing techniques
  • Master the metaprogramming capabilities of the language and learn how to write Domain Specific Languages

In Detail

Get up to speed with Groovy, a language for the Java Virtual Machine (JVM) that integrates features of both object-oriented and functional programming. This book will show you the powerful features of Groovy 2 applied to real-world scenarios and how the dynamic nature of the language makes it very simple to tackle problems that would otherwise require hours or days of research and implementation.

Groovy 2 Cookbook contains a vast number of recipes covering many facets of today's programming landscape. From language-specific topics such as closures and metaprogramming, to more advanced applications of Groovy flexibility such as DSL and testing techniques, this book gives you quick solutions to everyday problems.

The recipes in this book start from the basics of installing Groovy and running your first scripts and continue with progressively more advanced examples that will help you to take advantage of the language's amazing features.

Packed with hundreds of tried-and-true Groovy recipes, Groovy 2 Cookbook includes code segments covering many specialized APIs to work with files and collections, manipulate XML, work with REST services and JSON, create asynchronous tasks, and more. But Groovy does more than just ease traditional Java development: it brings modern programming features to the Java platform like closures, duck-typing, and metaprogramming.

In this new book, you'll find code examples that you can use in your projects right away along with a discussion about how and why the solution works. Focusing on what's useful and tricky, Groovy 2 Cookbook offers a wealth of useful code for all Java and Groovy programmers, not just advanced practitioners.


This book follows a Cookbook style and is packed with intermediate and advanced level recipes.

Who this book is for

This book is for Java developers who have an interest in discovering new ways to quickly get the job done using a new language that shares many similarities with Java. The book’s recipes start simple, therefore no previous Groovy experience is required to understand the code and the explanations accompanying the examples.

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software