Groovy in Action, Second Edition
Dierk König, Paul King, Guillaume Laforge, Hamlet D'Arcy, Cédric Champeau, Erik Pragt, and Jon Skeet
Foreword by James Gosling
  • June 2015
  • ISBN 9781935182443
  • 912 pages
  • printed in black & white

A clear and detailed exposition of what is groovy about Groovy. I'm glad to have it on my bookshelf.

From the Foreword to the First Edition, by James Gosling, Creator of Java
Groovy in Action, Second Edition is a thoroughly revised, comprehensive guide to Groovy programming. It introduces Java developers to the dynamic features that Groovy provides, and shows how to apply Groovy to a range of tasks including building new apps, integration with existing code, and DSL development. Covers Groovy 2.4.
Table of Contents show full

foreword to the first edition



about this book

about the authors

Part 1 The Groovy language

1. Your way to Groovy

1.1. The Groovy story

1.1.1. What is Groovy?

1.1.2. Playing nicely with Java: seamless integration

1.1.3. Power in your code: a feature-rich language

1.1.4. Community driven but corporate backed

1.2. What Groovy can do for you

1.2.1. Groovy for the busy Java professional

1.2.2. Groovy for the polyglot programmer

1.2.3. Groovy for pragmatic programmers, extremos, and agilists

1.3. Running Groovy

1.3.1. Using groovysh for a welcome message

1.3.2. Using groovyConsole

1.3.3. Using the groovy command

1.4. Compiling and running Groovy

1.4.1. Compiling Groovy with groovyc

1.4.2. Running a compiled Groovy script with Java

1.5. Groovy IDE and editor support

1.5.1. IntelliJ IDEA plug-in

1.5.2. NetBeans IDE plug-in

1.5.3. Eclipse plug-in

1.5.4. Groovy support in other editors

1.6. Summary

2. Overture: Groovy basics

2.1. General code appearance

2.1.1. Commenting Groovy code

2.1.2. Comparing Groovy and Java syntax

2.1.3. Beauty through brevity

2.2. Probing the language with assertions

2.3. Groovy at a glance

2.3.1. Declaring classes

2.3.2. Using scripts

2.3.3. GroovyBeans

2.3.4. Annotations

2.3.5. Using grapes

2.3.6. Handling text

2.3.7. Numbers are objects

2.3.8. Using lists, maps, and ranges

2.3.9. Code as objects: closures

2.3.10. Groovy control structures

2.4. Groovy’s place in the Java environment

2.4.1. My class is your class

2.4.2. GDK: the Groovy library

2.4.3. Groovy compiler lifecycle

2.5. Summary

3. Simple Groovy datatypes

3.1. Objects, objects everywhere

3.1.1. Java’s type system: primitives and references

3.1.2. Groovy’s answer: everything’s an object

3.1.3. Interoperating with Java: automatic boxing and unboxing

3.1.4. No intermediate unboxing

3.2. The concept of optional typing

3.2.1. Assigning types

3.2.2. Dynamic Groovy is type safe

3.2.3. Let the casting work for you

3.2.4. The case for optional typing

3.3. Overriding operators

3.3.1. Overview of overridable operators

3.3.2. Overridden operators in action

3.3.3. Making coercion work for you

3.4. Working with strings

3.4.1. Varieties of string literals

3.4.2. Working with GStrings

3.4.3. From Java to Groovy

3.5. Working with regular expressions

3.5.1. Specifying patterns in string literals

3.5.2. Applying patterns

3.5.3. Patterns in action

3.5.4. Patterns and performance

3.5.5. Patterns for classification

3.6. Working with numbers

3.6.1. Coercion with numeric operators

3.6.2. GDK methods for numbers

3.7. Summary

4. Collective Groovy datatypes

4.1. Working with ranges

4.1.1. Specifying ranges

4.1.2. Ranges are objects

4.1.3. Ranges in action

4.2. Working with lists

4.2.1. Specifying lists

4.2.2. Using list operators

4.2.3. Using list methods

4.2.4. Lists in action

4.3. Working with maps

4.3.1. Specifying maps

4.3.2. Using map operators

4.3.3. Maps in action

4.4. Notes on Groovy collections

4.4.1. Understanding concurrent modification

4.4.2. Distinguishing between copy and modify semantics

4.5. Summary

5. Working with closures

5.1. A gentle introduction to closures

5.2. The case for closures

5.2.1. Using iterators

5.2.2. Handling resources with a protocol

5.3. Declaring closures

5.3.1. Simple declaration

5.3.2. Using assignments for declaration

5.3.3. Referring to methods as closures

5.3.4. Comparing the available options

5.4. Using closures

5.4.1. Calling a closure

5.4.2. More closure capabilities

5.5. Understanding closure scope

5.5.1. Simple variable scope

5.5.2. Inspecting closure scope

5.5.3. Scoping at work: the classic accumulator test

5.6. Returning from closures

5.7. Support for design patterns

5.7.1. Relationship to the Visitor pattern

5.7.2. Relationship to the Builder pattern

5.7.3. Relationship to other patterns

5.8. Summary

6. Groovy control structures

6.1. Groovy truth

6.1.1. Evaluating Boolean tests

6.1.2. Assignments within Boolean tests

6.2. Conditional execution structures

6.2.1. The humble if statement

6.2.2. The conditional ?: operator and Elvis

6.2.3. The switch statement and the in operator

6.2.4. Sanity checking with assertions

6.3. Looping

6.3.1. Looping with while

6.3.2. Looping with for

6.4. Exiting blocks and methods

6.4.1. Normal termination: return/break/continue

6.4.2. Exceptions: throw/try-catch-finally

6.5. Summary

7. Object orientation, Groovy style

7.1. Defining classes and scripts

7.1.1. Defining fields and local variables

7.1.2. Methods and parameters

7.1.3. Safe dereferencing with the ?. operator

7.1.4. Constructors

7.2. Organizing classes and scripts

7.2.1. File to class relationship

7.2.2. Organizing classes in packages

7.2.3. Further classpath considerations

7.3. Advanced object-oriented features

7.3.1. Using inheritance

7.3.2. Using interfaces

7.3.3. Multimethods

7.3.4. Using traits

7.4. Working with GroovyBeans

7.4.1. Declaring beans

7.4.2. Working with beans

7.4.3. Using bean methods for any object

7.4.4. Fields, accessors, maps, and Expando

7.5. Using advanced syntax features

7.5.1. Querying objects with GPaths

7.5.2. Injecting the spread operator

7.5.3. Concise syntax with command chains

7.6. Summary

8. Dynamic programming with Groovy

8.1. What is dynamic programming?

8.2. Meta Object Protocol

8.3. Customizing the MOP with hook methods

8.3.1. Customizing methodMissing

8.3.2. Customizing propertyMissing

8.3.3. Using closures for dynamic hooks

8.3.4. Customizing GroovyObject methods

8.4. Modifying behavior through the metaclass

8.4.1. MetaClass knows it all

8.4.2. How to find the metaclass and invoke methods

8.4.3. Setting other metaclasses

8.4.4. Expanding the metaclass

8.4.5. Temporary MOP modifications using category classes

8.4.6. Writing extension modules

8.4.7. Using the @Category annotation

8.4.8. Merging classes with Mixins

8.5. Real-world dynamic programming in action

8.5.1. Calculating with metrics

8.5.2. Replacing constructors with factory methods

8.5.3. Fooling IDEs for fun and profit

8.5.4. Undoing metaclass modifications

8.5.5. The Intercept/Cache/Invoke pattern

8.6. Summary

9. Compile-time metaprogramming and AST transformations

9.1. A brief history

9.1.1. Generating bytecode, not source code

9.1.2. Putting the power of code generation in the hands of developers

9.2. Making Groovy cleaner and leaner

9.2.1. Code-generation transformations

9.2.2. Class design and design pattern annotations

9.2.3. Logging improvements

9.2.4. Declarative concurrency

9.2.5. Easier cloning and externalizing

9.2.6. Scripting support

9.2.7. More transformations

9.3. Exploring AST

9.3.1. Tools of the trade

9.3.2. Other tools

9.4. AST by example: creating ASTs

9.4.1. Creating by hand

9.4.2. AstBuilder.buildFromSpec

9.4.3. AstBuilder.buildFromString

9.4.4. AstBuilder.buildFromCode

9.5. AST by example: local transformations

9.6. AST by example: global transformations

9.7. Testing AST transformations

9.8. Limitations

9.8.1. It’s early binding

9.8.2. It’s fragile

9.8.3. It adds complexity

9.8.4. Its syntax is fixed

9.8.5. It’s not typed

9.8.6. It’s unhygienic

9.9. Next steps

9.10. Summary

10. Groovy as a static language

10.1. Motivation for optional static typing

10.1.1. The role of types in Groovy

10.1.2. Type checking a dynamic language?

10.2. Using @TypeChecked

10.2.1. Finding typos

10.2.2. Resolving method calls

10.2.3. Checking assignments

10.2.4. Type inference

10.2.5. Type-checked Grooviness

10.2.6. Type checking closures

10.2.7. Revisiting dynamic features in light of type checking

10.2.8. Mixing type-checked code with dynamic code

10.3. Flow typing

10.3.1. Least upper bound

10.3.2. Smart instanceof inference

10.3.3. Closure-shared variables

10.4. Static compilation

10.4.1. @CompileStatic

10.4.2. Method dispatch

10.5. Static type checking extensions

10.5.1. @DelegatesTo revisited

10.5.2. Type checking extension scripts

10.5.3. Limits

10.6. Summary

Part 2 Around the Groovy library

11. Working with builders

11.1. Learning by example: Using a builder

11.2. Building object trees with NodeBuilder

11.2.1. NodeBuilder in action: a closer look at builder code

11.2.2. Understanding the builder concept

11.2.3. Smart building with logic

11.3. Working with MarkupBuilder

11.3.1. Building XML

11.3.2. Building HTML

11.4. Working with StreamingMarkupBuilder

11.5. Task automation with AntBuilder

11.5.1. From Ant scripts to Groovy scripts

11.5.2. How AntBuilder works

11.5.3. Smart automation scripts with logic

11.6. Easy GUIs with SwingBuilder

11.6.1. Reading a password with SwingBuilder

11.6.2. Creating Swing widgets

11.6.3. Arranging your widgets

11.6.4. Referring to widgets

11.6.5. Using Swing actions

11.6.6. Using models

11.6.7. Binding made easy

11.6.8. Putting it all together

11.7. Modern UIs with GroovyFX SceneGraphBuilder

11.7.1. Application design with FXML

11.7.2. Properties and binding

11.7.3. Groovy desktop applications

11.8. Creating your own builder

11.8.1. Subclassing BuilderSupport

11.8.2. Subclassing FactoryBuilderSupport

11.8.3. Rolling your own

11.9. Summary

12. Working with the GDK

12.1. Working with objects

12.1.1. Interactive objects

12.1.2. Convenient Object methods

12.1.3. Iterative Object methods

12.2. Working with files and I/O

12.2.1. Traversing the filesystem

12.2.2. Reading from input sources

12.2.3. Writing to output destinations

12.2.4. Filters and conversions

12.2.5. Streaming serialized objects

12.2.6. temporary data and file copying

12.3. Working with threads and processes

12.3.1. Groovy multithreading

12.3.2. Integrating external processes

12.4. Working with templates

12.4.1. Understanding the template format

12.4.2. Templates in action

12.4.3. Advanced template issues

12.5. Working with Groovlets

12.5.1. Starting with "Hello world"

12.5.2. Groovlet binding

12.5.3. Templating Groovlets

12.6. Summary

13. Database programming with Groovy

13.1. Groovy SQL: a better JDBC

13.1.1. Setting up for database access

13.1.2. Executing SQL

13.2. Advanced Groovy SQL

13.2.1. Performing transactional updates

13.2.2. Working with batches

13.2.3. Working with pagination

13.2.4. Fetching metadata

13.2.5. Working with named and named-ordinal parameters

13.2.6. Using stored procedures

13.3. DataSets for SQL without SQL

13.3.1. Using DataSet operations

13.3.2. DataSets on database views

13.4. Organizing database work

13.4.1. Architectural overview

13.4.2. Specifying the application behavior

13.4.3. Implementing the infrastructure

13.4.4. Using a transparent domain model

13.4.5. Implementing the application layer

13.5. Groovy and NoSQL

13.5.1. MongoDB: A document-style database

13.5.2. Neo4J: A graph database

13.6. Other approaches

13.7. Summary

14. Working with XML and JSON

14.1. Reading XML documents

14.1.1. Working with a DOM parser

14.1.2. Reading with a Groovy parser

14.1.3. Reading with a SAX parser

14.1.4. Reading with a StAX parser

14.2. Processing XML

14.2.1. In-place processing

14.2.2. Streaming processing

14.2.3. Updating XML

14.2.4. Combining with XPath

14.3. Parsing and building JSON

14.3.1. Parsing JSON

14.3.2. Building JSON

14.4. Summary

15. Interacting with Web Services

15.1. An overview of Web Services

15.2. Reading RSS and ATOM

15.3. Using a REST-based API

15.4. Using XML-RPC

15.5. Applying SOAP

15.5.1. Doing SOAP with plain Groovy

15.5.2. Simplifying SOAP access using HTTPBuilder

15.5.3. Simplifying SOAP access using groovy-wslite

15.6. Summary

16. Integrating Groovy

16.1. Prelude to integration

16.1.1. Integrating appropriately

16.1.2. Setting up dependencies

16.2. Evaluating expressions and scripts with GroovyShell

16.2.1. Starting simply

16.2.2. Passing parameters within a binding

16.2.3. Generating dynamic classes at runtime

16.2.4. Parsing scripts

16.2.5. Running scripts or classes

16.2.6. Further parameterization of GroovyShell

16.3. Using the Groovy script engine

16.3.1. Setting up the engine

16.3.2. Running scripts

16.3.3. Defining a different resource connector

16.4. Working with the GroovyClassLoader

16.4.1. Parsing and loading Groovy classes

16.4.2. The chicken and egg dependency problem

16.4.3. Providing a custom resource loader

16.4.4. Playing it safe in a secured sandbox

16.5. Spring integration

16.5.1. Wiring GroovyBeans

16.5.2. Refreshable beans

16.5.3. Inline scripts

16.6. Riding Mustang and JSR-223

16.6.1. Introducing JSR-223

16.6.2. The script engine manager and its script engines

16.6.3. Compilable and invocable script engines

16.6.4. Polyglot programming

16.7. Mastering CompilerConfiguration

16.7.1. The import customizer

16.7.2. The source-aware customizer

16.7.3. Writing your own customizer

16.7.4. The configscript compilation option

16.8. Choosing an integration mechanism

16.9. Summary

Part 3 Applied Groovy

17. Unit testing with Groovy

17.1. Getting started

17.1.1. Writing tests is easy

17.1.2. GroovyTestCase: an introduction

17.1.3. Working with GroovyTestCase

17.2. Unit testing Groovy code

17.3. Unit testing Java code

17.4. Organizing your tests

17.4.1. Test suites

17.4.2. Parameterized or data-driven testing

17.4.3. Property-based testing

17.5. Advanced testing techniques

17.5.1. Testing made groovy

17.5.2. Stubbing and mocking

17.5.3. Using GroovyLogTestCase

17.5.4. Unit testing performance

17.5.5. Code coverage with Groovy

17.6. IDE integration

17.6.1. Using GroovyTestSuite

17.6.2. Using AllTestSuite

17.7. Testing with the Spock framework

17.7.1. Testing with mocks

17.7.2. Data-driven Spock tests

17.8. Build automation

17.8.1. Build integration with Gradle

17.8.2. Build integration with Maven

17.9. Summary

18. Concurrent Groovy with GPars

18.1. Concurrency for the rest of us

18.1.1. Concurrent != parallel

18.1.2. Introducing new concepts

18.2. Concurrent collection processing

18.2.1. Transparently concurrent collections

18.2.2. Available fork/join methods

18.3. Becoming more efficient with map/filter/reduce

18.4. Dataflow for implicit task coordination

18.4.1. Testing for deadlocks

18.4.2. Dataflow on sequential datatypes

18.4.3. Final thoughts on dataflow

18.5. Actors for explicit task coordination

18.5.1. Using the strengths of Groovy

18.6. Agents for delegated task coordination

18.7. Concurrency in action

18.8. Summary

19. Domain-specific languages

19.1. Groovy’s flexible nature

19.1.1. Back to omitting parentheses

19.2. Variables, constants, and method injection

19.2.1. Injecting constants through the binding

19.2.2. Injecting methods into a script

19.2.3. Adding imports and static imports automatically

19.2.4. Injecting methods (revisited)

19.2.5. Adding closures to the binding

19.3. Adding properties to numbers

19.4. Leveraging named arguments

19.5. Command chains

19.6. Defining your own control structures

19.7. Context switching with closures

19.8. Another technique for builders

19.9. Securing your DSLs

19.9.1. Introducing SecureASTCustomizer

19.9.2. The ArithmeticShell

19.9.3. Stopping the execution of your programs

19.9.4. Preventing cheating with metaprogramming

19.10. Testing and error reporting

19.11. Summary

20. The Groovy ecosystem

20.1. Groovy Grapes for self-contained scripts

20.2. Scriptom for Windows automation

20.3. GroovyServ for quick startup

20.4. Gradle for project automation

20.5. CodeNarc for static code analysis

20.6. GContracts for improved design

20.7. Grails for web development

20.8. Griffon for desktop applications

20.9. Gaelyk for Groovy in the cloud

20.10. Summary

Appendix A: Installation and documentation

A.1. Installing Groovy

A.2. Obtaining up-to-date documentation

A.2.1. Using online resources

A.2.2. Connecting to the book’s forum

Appendix B: Groovy language information

B.1. Operator precedence

B.2. Keyword list

B.3. Modules

Appendix C: GDK API quick reference

C.1. Array of primitives

C.2. The groovy.lang package

C.3. The groovy.sql package

C.4. The java.awt package

C.5. The package

C.6. The java.lang package

C.7. The java.math package

C.8. The package

C.9. The java.nio.file package

C.10. The java.sql package

C.11. The java.util package

C.12. The java.util.concurrent package

C.13. The java.util.regex package

C.14. The javax.swing package

C.15. The javax.swing.table package

C.16. The javax.swing.tree package

C.17. The org.w3c.dom package

Appendix D: Cheat sheets

D.1. GStrings

D.2. Lists

D.3. Closures

D.4. Regular expressions

D.5. XML GPath notation

Appendix E: Annotation parameters

Appendix F: Compiler phases

Appendix G: AST visitors

G.1. Walking and reading a tree

G.1.1. Wiring in a Visitor

Appendix H: Type checking extensions

H.1. Type checking extension API

H.1.1. The GroovyTypeCheckingExtensionSupport class

H.1.2. Virtual methods

H.1.3. Type-checking extension scope

H.2. Type checking events

H.2.1. setup

H.2.2. finish

H.2.3. unresolvedVariable

H.2.4. unresolvedProperty

H.2.5. unresolvedAttribute

H.2.6. beforeMethodCall

H.2.7. afterMethodCall

H.2.8. onMethodSelection

H.2.9. methodNotFound

H.2.10. beforeVisitMethod

H.2.11. afterVisitMethod

H.2.12. beforeVisitClass

H.2.13. afterVisitClass

H.2.14. incompatibleAssignment

H.2.15. ambiguousMethods

H.2.16. incompatibleReturnType

H.3. Extensions aren’t AST transformations

Appendix I: Android support


About the Technology

In the last ten years, Groovy has become an integral part of a Java developer's toolbox. Its comfortable, common-sense design, seamless integration with Java, and rich ecosystem that includes the Grails web framework, the Gradle build system, and Spock testing platform have created a large Groovy community

About the book

Groovy in Action, Second Edition is the undisputed definitive reference on the Groovy language. Written by core members of the Groovy language team, this book presents Groovy like no other can—from the inside out. With relevant examples, careful explanations of Groovy’s key concepts and features, and insightful coverage of how to use Groovy in-production tasks, including building new applications, integration with existing code, and DSL development, this is the only book you’ll need. Updated for Groovy 2.4.

What's inside

  • Comprehensive coverage of Groovy 2.4 including language features, libraries, and AST transformations
  • Dynamic, static, and extensible typing
  • Concurrency: actors, data parallelism, and dataflow
  • Applying Groovy: Java integration, XML, SQL, testing, and domain-specific language support
  • Hundreds of reusable examples

About the reader

Some experience with Java or another programming language is helpful. No Groovy experience is assumed.

About the authors

Authors Dierk König, Paul King, Guillaume Laforge, Hamlet D’Arcy, Cédric Champeau, Erik Pragt, and Jon Skeet are intimately involved in the creation and ongoing development of the Groovy language and its ecosystem.

combo $59.99 pBook + eBook
eBook $47.99 pdf + ePub + kindle

FREE domestic shipping on three or more pBooks

Groovy lies between light scripting and heavier enterprise languages—this book will help you master the sweet spot.

Rick Wagner, Red Hat

The most valuable Groovy resource, written by the most valuable members of the Groovy community.

Vladimir Orany, Metadata Consulting Ltd.

The long-awaited and excellent successor to the first edition.

Dave McFarland, Instil Software Ltd.