Programming Groovy 2 free ebook download

  

What readers are saying about

Programming Groovy 2

  If you ever wondered why dynamic languages in general, and Groovy in particular, are so popular and how you can leverage them in your own work, this is the book for you. ➤ Joe McTee

  Developer, JEKLsoft Whether you’re a Java developer starting to dabble with Groovy, an intermediate Groovy developer looking to improve your understanding of the language, or an experienced Groovy developer looking for an introduction to the latest features in Groovy 2, this book is the perfect way to take your skills to the next level. ➤ Peter Bell hackNY In this update for Groovy 2, Venkat has done a great job showing you both the theory and the practice of using Groovy. From basic, everyday tasks to advanced usage like compile-time metaprogramming and AST transforms, method intercep- tion and synthesis, and creating DSLs, you’ll find a ton packed into this relatively thin book. Best, it won’t become a desk anchor since you’ll constantly refer to its many great examples! ➤ Scott Leberknight Co-founder and senior software architect, Near Infinity Corp. I’m delighted that Venkat has revised this essential Groovy tutorial to reflect the developments in the language and ecosystem since the first edition. Everyone learning Groovy should have this book in the library. ➤ Tim Berglund

  GitHub trainer and evangelist Many other programming books assume too much. What makes Venkat’s books unique is that they welcome various levels of readers without insulting their intel- ligence. Programming Groovy 2 is no exception—it is crafted with small palatable examples that guide the reader in a natural and incremental learning experience from novice to expert. ➤ Daniel Hinojosa

  Consultant, programmer, speaker, author of Testing in Scala

  Programming Groovy 2

Dynamic Productivity for the Java Developer

  Venkat Subramaniam The Pragmatic Bookshelf

  Dallas, Texas • Raleigh, North Carolina

  

Many of the designations used by manufacturers and sellers to distinguish their products

are claimed as trademarks. Where those designations appear in this book, and The Pragmatic

Programmers, LLC was aware of a trademark claim, the designations have been printed in

initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,

Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-

marks of The Pragmatic Programmers, LLC.

  

Every precaution was taken in the preparation of this book. However, the publisher assumes

no responsibility for errors or omissions, or for damages that may result from the use of

information (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team create

better software and have more fun. For more information, as well as the latest Pragmatic

. The team that produced this book includes: Brian P. Hogan (editor) Potomac Indexing, LLC (indexer) Candace Cunningham (copyeditor) David J Kelly (typesetter) Janet Furlow (producer) Juliet Benda (rights) Ellie Callahan (support) No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, All rights reserved. Copyright © 2013 The Pragmatic Programmers, LLC . Encoded using the finest acid-free high-entropy binary digits. ISBN-13: 978-1-937785-30-7 Printed in the United States of America. recording, or otherwise, without the prior consent of the publisher.

  Book version: P1.0—July 2013

  

To Mythili and Balu—for being much more

than an aunt and an uncle—for being there

when I needed them most.

  Contents . . . . . . . . . . . . . xv

  33

  25

  2.6

  26

  2.7

  30

  2.8

  31

  2.9

  2.10

  24

  40

  2.11 46 3. . . . . . . . . . . . .

  53

  53

  3.1

  3.2

  54

  3.3

  2.5

  2.4

  

Part I — Beginning Groovy

1. . . . . . . . . . . . .

  6

  3

  3

  1.1

  1.2

  5

  1.3

  5

  1.4

  1.5

  22

  7

  1.6 8 2. . . . . . . . . . .

  11

  11

  2.1

  2.2

  19

  2.3

  55

  3.4

  

  89

  4.11

  92 5. . . . . . . . . . .

  97

  97

  5.1

  5.2 100

  5.3 103

  5.4 105

  5.5 106

  6. . . . . . . . . . 109

  109

  86

  6.1

  6.2 111

  6.3 113

  6.4 115

  6.5 118

  6.6 120

  6.7 122

  

Part II — Using Groovy

  7. . . . . . . . . . . . 127

  7.1 128

  7.2 133

  4.10

  4.9

  56

  4.2

  3.5

  61

  3.6

  62

  3.7

  65

  3.8

  65 4. . . . . . . . . . . . .

  71

  72

  4.1

  75

  84

  4.3

  75

  4.4

  77

  4.5

  78

  4.6

  80

  4.7

  82

  4.8

  7.3 139

  8. . . . . . . . . . . . 143

  12. . . . . . . . 185

  10.9 169

  

Part III — MOPping Groovy

  11. . . . . . . 175

  11.1 176

  11.2 180

  11.3 182

  12.1 185

  10.7 166

  12.2 188

  13. . . . . . . . . . . 193

   193

  13.1

  13.2 198

  13.3 203

  13.4 206

  10.8 167

  10.6 165

  8.1 143

  9.5 155

  8.2 148

  9. . . . . . . . . . 151

   151

  9.1

  9.2 152

  9.3 153

  9.4 154

  9.6 156

  10.5 163

  9.7 156

  10. . . . . . . . 159

   159

  10.1

  10.2 160

  10.3 161

  10.4 162

  13.5 208

  14. . . . . . . . . . . 215

  18.7 284

   271

  18.1

  18.2 272

  18.3 277

  18.4 277

  18.5 280

  18.6 283

  18.8 285

  17.6 266

  18.9 288

  18.10 289

  19. . . . . . . . . . 295

  

  295

  19.1

  19.2 297

  18. . . . . . . . . . 271

  17.5 262

  14.1 216

  16.1 236

  14.2 220

  14.3 222

  15. . . . . . . . . . . . . 225

  15.1 225

  15.2 227

  15.3 231

  16. . . . . . 235

  16.2 241

  17.4 260

  16.3 246

  

Part IV — Using Metaprogramming

  17. . . . . . . . . . . . 253

  

  253

  17.1

  17.2 256

  17.3 258

  19.3 298

  19.4 298

  19.5 299

  19.6 299

  19.7 301

  19.8 302

  19.9 303

  19.10 305

  19.11 307 A1. . . . . . . . . . . . . 309 A2. . . . . . . . . . . . . 315

   . . . . . . . . . . . . . . 317

  

Foreword to the Second Edition

  As the saying goes, time flies. In the first edition of this book, Venkat guided you through all the nice features of Groovy 1.5 and turned you into a proficient “

  Groovy-ist,” but it’s now time to discover what Groovy 2 has in store. Of course, your favorite author has you covered! The Groovy team worked on three major themes for the 2.0 version. First of all, we brought Groovy in line with JDK 7: we added the Java 7 “Project Coin” syntax enhancements, and we also powered Groovy’s runtime with the “invoke dynamic” bytecode instruction and APIs under the hood. That way, you can use the latest syntax additions in Groovy even on older JDKs, but by running JDK 7 you’ll benefit from performance improvements. Secondly, we broke up Groovy into smaller modules, a core and several API- related ones, so you can pick the pieces you are interested in to compose your application. We also extended the Groovy Development Kit to allow you to create your own extension methods—just like Groovy does with its enriched JDK with the famous DefaultGroovyMethods class! Last but not least, we introduced a “static” theme with two key novelties: static type-checking and static compilation. With the former, you can catch typos and other errors easily at compile time and even allow your domain-specific languages to be type-checked, while with the latter you can get the same performance as Java for critical parts of your application that request the highest level of speed. With all those additions to the language and APIs, Groovy continues to mature like good wine, and just as a sommelier would share his expertise, Venkat dispenses his knowledge of all the power features of Groovy through the nice flavors of the chapters you are going to read, helping you get up to speed with the language and transport you to the next level. Guillaume Laforge Groovy project manager June 2013

  Introduction

  The Java platform is arguably one of the most powerful and widely adopted ecosystems today. It has three significant pieces: The Java Virtual Machine (JVM), which has become increasingly powerful

  • and more performant over the years The Java Development Kit (JDK), the rich set of third-party libraries and
  • frameworks that help us effectively leverage the power of the platform The set of languages on the JVM—the Java language being the first—that
  • help us program the platform

  Languages are like vehicles that let us navigate the platform. They let us reach into various parts of this landscape with ease. The Java language has come a long way; its libraries have been refactored and expanded. It’s gotten us this far, but we need to look beyond the Java language to languages that are lightweight and that can make us more productive. When used correctly, dynamic languages, the functional style of programming, and metaprogram- ming capabilities can help us navigate the landscape much faster. When viewed as vehicles, these newer languages aren’t faster cars; they’re flying machines, giving us the capability to be several orders of magnitude more productive.

  The Java language has been flirting with metaprogramming and the functional style of programming for a while and will support some of these features to various degrees in future versions. We don’t have to wait for that day, however. We can build performant JVM applications with all the dynamic capabilities today, right now, using Groovy.

  What’s Groovy?

  Merriam-Webster defines groovy as “marvelous, wonderful, excellent, hip, trendy.” The Groovy language is all of that—it’s lightweight, low-ceremony, dynamic, object-oriented, and runs on the JVM. Groovy is open sourced under the Apache License, version 2.0. It derives strength from various languages, such as Smalltalk, Python, and Ruby, while retaining a syntax familiar to Java programmers. Groovy compiles into Java bytecode and extends the Java API and libraries. It runs on Java 1.5 and newer. For deployment, all we need is a Groovy Java archive (JAR) in addition to the regular Java stuff, and we’re all set. 1 Groovy is a “language that has been reborn several times.” James Strachan and Bob McWhirter started it in 2003, and it was commissioned into Java

  Specification Request (JSR) 241 in March 2004. Soon afterward, it was almost abandoned because of difficulties and issues. Guillaume Laforge and Jeremy Rayner decided to rekindle the efforts and bring Groovy back to life. Their first effort was to fix bugs and stabilize the language features. The uncertainty lingered for a while. A number of people, including committers and users, simply gave up on the language. Finally, a group of smart and enthusiastic developers joined forces with Guillaume and Jeremy, and a vibrant developer community emerged.

  The release of Groovy version 1.0 was announced on January 2, 2007. It was encouraging to see that, well before it reached 1.0, Groovy was put to use on commercial projects in a handful of organizations in the United States and Europe. Organizations and developers are beginning to use Groovy at various levels on their projects, and the time is ripe for major Groovy adoption in the industry. Groovy version 2.0 was released in mid 2012. Groovy shines in tools and frameworks like Grails, CodeNarc, easyb, Gradle, and Spock. Grails, a dynamic web-development framework based on “coding 2 by convention,” exploits Groovy metaprogramming. Using Grails, we can quickly build web applications on the JVM using Groovy, Spring, Hibernate, and other Java frameworks.

  Why Dynamic Languages?

  Dynamic languages have the ability to extend a program at runtime, including changing types, behaviors, and object structures. With these languages, we can do things at runtime that static languages do at compile time; we can even execute program statements that are created on the fly at runtime.

  For example, if we want to compute a five percent raise on an $80,000 salary, we could simply write the following:

1. See “A bit of Groovy history,” a blog post by Guillaume Laforge at http://glaforge.free.fr/

  

  2.

  5.percentRaise(80000) Yes, that’s the friendly java.lang.Integer responding to our own dynamic method, which we can add quite easily, like so:

  Integer .metaClass.percentRaise = { amount -> amount * (1 + delegate / 100.0) }

  As we see here, it’s easy to add dynamic methods to classes in Groovy. The dynamic method we added to the instance, referred using the

  Integer delegate variable, returns the dollar amount increased by the appropriate percentage.

  The flexibility of dynamic languages gives us the advantage of evolving pro- grams as the applications execute. This goes far beyond code generation. We should consider code generation to be soooo twentieth century. In fact, gen- erated code is like an incessant itch; if we keep scratching it, it turns into a sore. With dynamic languages, there are better ways. Dynamic languages make it easier to prefer code synthesis, which is in-memory code-creation at runtime. The code is synthesized based on the flow of logic through the application and becomes active just in time.

  By carefully applying dynamic languages’ capabilities, we can be more pro- ductive as application developers. This greater productivity means we can easily create higher levels of abstractions in shorter amounts of time. We can also use a smaller yet more capable set of developers to create applications. In addition, greater productivity means we can create parts of our application quickly and get feedback from our fellow developers, testers, domain experts, and customer representatives. And all this leads to greater agility. Tim O’Reilly observes the following about developing web applications: “Rather than being finished paintings, they are sketches, continually being redrawn in response to new data.” He also makes the point that dynamic languages are better suited to web development in “Why Scripting Languages Matter” Dynamic languages have been around for a long time, so why is now a great time to get excited about them? There are at least four reasons:

  Machine speed

  • Availability •
  • Awareness of unit testing Killer applications
  • Let’s start by talking about machine speed. Doing at runtime what other languages do at compile time raises a concern about dynamic languages’ speed. Interpreting code at runtime rather than simply executing compiled code adds to that concern. Fortunately, machine speed has consistently
increased over the years—handhelds have more computing power and mem- ory today than large computers had decades ago. Tasks that were quite unimaginable using a 1980s processor are easy to achieve today. The perfor- mance concerns of dynamic languages are greatly eased because of processor speeds and other improvements in our field, including better just-in-time compilation techniques and JVM support for dynamic languages.

  Now let’s talk about availability. The Internet and active “public” community- based development have made recent dynamic languages easily accessible and available. Developers can now easily download languages and tools and play with them. They can even participate in community forums to influence the evolution of these languages. The Groovy users mailing list is very active, with constant discussions from passionate users expressing opinions of, ideas 3 about, and criticisms of current and future features. This is leading to greater experimentation, learning, and adaptation of languages than in the past. Next let’s look at awareness of unit testing. Most dynamic languages are dynamically typed. The types are often inferred based on the context. There are no compilers to flag type-casting violations at compile time. Since quite a bit of code may be synthesized and our program can be extended at runtime, we can’t rely upon coding-time verification alone. From the testing point of view, writing code in dynamic languages requires greater discipline than writing in statically typed languages. Over the past few years, we’ve seen increased awareness among programmers (though not sufficiently greater adoption yet) in the area of testing in general and unit testing in particular. Most of the programmers who have taken advantage of these dynamic lan- guages for commercial application development have also embraced testing and unit testing. Finally, many developers have in fact been using dynamic languages for decades. However, for the majority of the industry to be excited about them, we had to have killer applications—compelling stories to share with our developers and managers. That tipping point, for Ruby in particular and for 4 dynamic languages in general, came in the form of Rails. It showed struggling web developers how they could quickly develop applications using Ruby’s dynamic capabilities. In the same vein came Grails, a web framework written 5 in Groovy and Java that offers the same productivity and ease.

3. Visit http://groovy.codehaus.org/Mailing+Lists and http://groovy.markmail.org to see.

   4.

  5.

  These frameworks have caused enough stir in the development community to make the industrywide adoption of dynamic languages highly probable. Dynamic languages, along with metaprogramming capabilities, make simple things simpler and hard things manageable. We still have to deal with the inherent complexity of our application, but dynamic languages let us focus our effort where it’s deserved. When I got into Java after years of C++, features such as reflection, a good set of libraries, and evolving framework support made me productive. The JVM, to a certain extent, provided me with the ability to take advantage of metaprogramming. However, I had to use some- thing in addition to Java to tap into that potential—heavyweight tools such as AspectJ. Like several other productive programmers, I found myself left with two options: use the exceedingly complex and not-so-flexible Java along with heavyweight tools, or move on to using dynamic languages such as Ruby that are object-oriented and have metaprogramming capabilities built in. (For instance, it takes only a couple of lines of code to do aspect-oriented program- ming—AOP—in Ruby and Groovy.) A few years ago, taking advantage of dynamic capabilities and metaprogramming while being productive meant leaving behind the Java platform. (After all, we use these features to be pro- ductive and can’t let them slow us down, right?) That is not the case anymore. Languages such as Groovy, JRuby, and Clojure are dynamic and run on the JVM. Using these languages, we can take full advantage of both the rich Java platform and dynamic-language capabilities.

  Why Groovy?

  As Java programmers, we don’t have to switch completely to a different language. Groovy feels like the Java language we already know, with a few augmentations. Dozens of scripting languages can run on the JVM—Groovy, JRuby, BeanShell, Scheme, Jaskell, Jython, JavaScript, and others. The list could go on and on. Our language choice should depend on a number of criteria: our needs, our preferences, our background, the projects we work with, our corporate technical environment, and so on. In this section, we discuss when Groovy is the right language to use. Groovy is an attractive language for a number of reasons: It has a flat learning curve.

  • It follows Java semantics.
  • It bestows dynamic love.
  • >It extends the JDK.
Let’s explore these in detail. First, we can run almost any Java code as Groovy for known problem areas), which means a flat learning curve. We can start writing code in Groovy and, if we’re stuck, simply switch gears and write the Java code we’re familiar with. We can later refactor that code and make it groovier.

  For example, Groovy understands the traditional for loop. So, we can write this:

  // Java Style for ( int i = 0; i < 10; i++) { //...

  } As we learn Groovy, we can change that to the following code or one of the other flavors for looping in Groovy (don’t worry about the syntax right now; after all, we’re just getting started, and very soon you’ll be a pro at it): 10.times { //... } Second, when programming in Groovy we can expect almost everything we

  java.lang.Object

  — expect in Java. Groovy classes extend the same good old Groovy

  classes are Java classes. The object-oriented paradigm and Java semantics are preserved, so when we write expressions and statements in Groovy, we already know what those mean to us as Java programmers. Here’s a little example to show that Groovy classes are Java classes:

  

  println XmlParser.class println XmlParser.class.superclass If we run groovy UseGroovyClass , we’ll get the following output: class groovy.util.XmlParser class java.lang.Object Now let’s talk about the third reason to love Groovy. Groovy is dynamic, and it is optionally typed. If we’ve enjoyed the benefits of other dynamically typed languages, such as Smalltalk, Python, JavaScript, and Ruby, we can also enjoy those in Groovy. For instance, if we want to add the method isPalindrome()

  — to String a method that tells whether a word is spelled the same forward and backward—we can add that easily with only a couple of lines of code (again, don’t try to figure out all the details of how this works right now; we have the rest of the book for that):

   String .metaClass.isPalindrome = {->

  delegate == delegate.reverse() } word = 'tattarrattat' println " $word is a palindrome? ${word.isPalindrome()} " word =

  'Groovy'

  println " $word is a palindrome? ${word.isPalindrome()} " Let’s look at the output to see how the previous code works: tattarrattat is a palindrome? true Groovy is a palindrome? false That’s how easy it is to extend a class—even the sacred

  java.lang.String class—with convenient methods, without intruding into its source code.

  Finally, as Java programmers, we rely heavily on the JDK and the API to get our work done. These are available in Groovy. In addition, Groovy extends the JDK with convenience methods and closure support through the Groovy JDK (GDK). Here’s a quick example of a GDK extension to the java.util.ArrayList class: lst = [ 'Groovy' , 'is' , 'hip' ] println lst.join( ' ' ) println lst.getClass() From the output of the previous code, we can confirm that the JDK is being used, but in addition we’re able to use the Groovy-added method to

  join()

  concatenate the elements in the ArrayList : Groovy is hip class java.util.ArrayList Groovy augments the Java we know. If a project team is familiar with Java, is using it for most of the organization’s projects, and has a lot of Java code to integrate and work with, then Groovy is a nice path toward productivity gains.

  What’s in This Book?

  This book is about programming with Groovy; it is aimed at Java programmers who already know the JDK well but are interested in learning the Groovy language and its dynamic capabilities. Throughout this book we’ll explore the Groovy language’s features with many practical examples. The objective is to make programmers quickly productive with this interesting and powerful language.

  The rest of this book is organized into four parts, as follows: In the chapters in Part I, “Beginning Groovy,” we focus on the whys and whats of Groovy—the fundamentals that’ll help us get comfortable with general programming in Groovy. This book is for experienced Java programmers, so we won’t spend any time with programming basics, like what an statement

  if

  is or how to write it. Instead, we directly dive into the similarities of Groovy and Java, and topics that are specific to Groovy. In Part II, “Using Groovy,” we’ll see how to use Groovy for everyday cod- ing—working with XML, accessing databases, and working with multiple Java/Groovy classes and scripts—so we can put Groovy to use right away for the day-to-day tasks. We’ll also discuss the Groovy extensions and addi- tions to the JDK so we can take advantage of both the power of Groovy and the JDK at the same time. In Part III, “MOPping Groovy,” we dive into Groovy’s metaprogramming capabilities. We’ll see Groovy really shine in these chapters and you’ll learn how to take advantage of its dynamic nature. We’ll start with the fundamentals of the metaobject protocol (MOP), cover how to do AOP-like operations in Groovy, and discuss dynamic method/property discovery and dispatching. We will also explore the compile-time metaprogramming capability and see how it can help extend and transform code during the compilation phase. In the last part, “Using Metaprogramming,” we’ll apply Groovy metaprogram- ming right away to create and use builders and domain-specific languages (DSLs). Unit testing is not only necessary in Groovy because of its dynamic nature, but it’s also easy to do—we can use Groovy to unit-test Java and Groovy code, as you’ll see in this part of the book. You’re reading the introduction now, of course. Here’s what’s in the rest of the book: In

Chapter 1, Getting Started, on page 3 , we’ll download and install Groovy

  and take it for a test-drive using and . We’ll also see how

  groovysh groovyConsole

  to run Groovy without these tools—from the command line and within an integrated development environment.

Chapter 2, Groovy for Java Eyes, on page 11 , we’ll start with familiar Java

  code and refactor that to Groovy. After a quick tour of Groovy features that improve our everyday Java coding, we’ll talk about Groovy’s support for Java 5 features. Groovy follows Java semantics, except in places it does not—we’ll also discuss gotchas that’ll help avoid surprises.

  In

  we’ll see how Groovy’s typing is

  similar to and different from Java’s typing, what Groovy really does with the type information we provide, and when to take advantage of dynamic typing versus optional typing. We’ll also cover how to take advantage of Groovy’s dynamic typing, design by capability, and multimethods. For tasks that need better performance than we can get from dynamic typing, we’ll see how we can instruct Groovy to statically type parts of code.

  In

   , you’ll learn all about the exciting Groovy feature called closures, including what they are, how they work, and

  when and how to use them. Groovy closures go beyond simple lambda expressions; they facilitate trampoline calls and memoization.

  we’ll explore Groovy’s

  support for Java collections—lists and maps. We’ll explore various convenience methods on collections, and we’ll never again want to use collections the old way. Groovy embraces and extends the JDK. We’ll explore the GDK and see the extensions to and other Java classes

Chapter 7, Exploring the GDK, Object on page 127 . Groovy has pretty good support for working with XML, including parsing and

  creating XML documents, as we’ll see in

   , presents Groovy’s SQL support, which will make our database-related programming easy and fun. In this chapter, we’ll cover iterators, data sets, and how to perform regular

  database operations using simpler syntax and closures. We’ll also see how to get data from Microsoft Excel documents. One of Groovy’s key strengths is its integration with Java. In

  we’ll investigate ways to

  closely interact with multiple Groovy scripts, Groovy classes, and Java classes from within our Groovy and Java code. Metaprogramming is one of the biggest benefits of dynamic languages in general, and Groovy in particular; with this feature we can inspect classes at runtime and dynamically dispatch method calls. We’ll explore Groovy’s support for metaprogramming

   , beginning with the fundamentals of how Groovy handles method calls to Groovy objects and Java objects.

  With Groovy we can perform AOP-like method interceptions using

  GroovyInter- ceptable and ExpandoMetaClass , as we’ll see in

   , covers how to synthesize classes

  dynamically, how to use metaprogramming to delegate method calls, and how to choose between the metaprogramming techniques from the previous three chapters. Groovy goodness does not end with runtime metaprogramming. Groovy now offers some of the same benefits at compile time, using abstract syntax tree (AST) transformation techniques, as we’ll see

  a nested hierarchy. We discuss how to use them and how to create our own

  dynamic nature requires unit testing. Fortunately, Groovy facilitates writing tests and creating mock objects, as we’ll cover in

   . We will play with techniques that will help us use Groovy to unit-test our Java code and our Groovy code.

  We can apply Groovy’s metaprogramming capabilities to build internal DSLs using the techniques in

   , you’ll find all the references to web articles and books cited throughout this book.

  Changes Since This Book’s First Edition

  This book’s first edition covered Groovy version 1.5. Groovy has come a long way since then. This second edition is up to date with Groovy 2.1. Here’s how the updates in this edition will help you: You’ll learn Groovy 2.x features.

  • You’ll learn about Groovy code-generation transformations like ,

  @Delegate

  • @Immutable , and so on.

  You’ll learn the benefits of the new Groovy 2.x static type-checking and

  • static compilation facilities. You will pick up tips for creating your own extension methods with the
  • new support for extension modules in Groovy 2.x.
  • Closures in Groovy are quite exceptional, and you’ll learn about their new support for tail-call optimization and memoization. You’ll learn how to integrate Java and Groovy effectively, pass Groovy • closures from Java, and even invoke dynamic Groovy methods from Java. You’ll find new examples to learn about the enhancements to the
  • metaprogramming API. You’ll learn how to use s and implement some elegant patterns with
  • them. In addition to runtime metaprogramming, you can grasp compile-time

  Mixin

  • metaprogramming and abstract syntax tree (AST) transformations. You’ll see the details for building and reading JSON data.
  • Additionally, you’ll learn the Groovy syntax that facilitates fluent creation
  • of DSLs.

  Who Is This Book For?

  This book is for developers working on the Java platform. It is best suited to programmers (and testers) who understand the Java language fairly well. Developers who understand programming in other languages can use this book as well, but they should supplement it with books that provide them with an in-depth understanding of Java and the JDK. For

   and are good resources for Java.

  Programmers who are somewhat familiar with Groovy can use this book to learn some tips and tricks that they may not have the opportunity to discover otherwise. Finally, those already familiar with Groovy may find this book useful for training or coaching fellow developers in their organizations.

  Online Resources

  Web resources referenced throughout the book are collected in

   . Here are two that will help you get started:

  The Groovy website for downloading the version of Groovy used in this

  • . The official homepage for this book at the Pragmatic Bookshelf website:
  • From there you can download all the

  example source code for this book. You can also offer feedback by submit- ting errata entries or posting your comments and questions in the forum for the book. If you’re reading the book in ebook form, you can click on the link above a code listing to view or download the specific example.

  Acknowledgments

  It’s been a real pleasure watching the Groovy ecosystem grow over the past four years. I thank the Groovy committers for creating a language and a set of tools that help programmers to be productive and have fun at the same time.

  I’d like to thank everyone who read the first edition of this book. Special thanks to Norbert Beckers, Giacomo Cosenza, Jeremy Flowers, Ioan Le Gu é,

  Fred Janon, Christopher M. Judd, Will Krespan, Jorge Lee, Rick Manocchi, Andy O’Brien, Tim Orr, Enio Pereira, David Potts, Srivaths Sankaran, Justin Spradlin, Fabian Topfstedt, Bryan Young, and Steve Zhang for taking the time to report errors on the book’s errata page.

  My sincere thanks and appreciation go to the technical reviewers of the second edition of this book. They were kind enough to give their time and attention to read through the concepts, try out the examples, and provide me valuable feedback, corrections, and encouragements along the way. Thank you, Tim Berglund, Mike Brady, Hamlet D’arcy, Scott Davis, Jeff Holland, Michael Kimsal, Scott Leberknight, Joe McTee, Al Scherer, and Eitan Suez.

  A few more people deserve to be called out. I thank Guillaume Laforge for his encouragement and for taking the time to write the foreword. C édric Champeau and Chris Reigrut were generous to quickly read through the beta of the second edition and provide valuable feedback. I am indebted to you; thank you. I also thank Thilo Maier for reporting errors on the errata page for the second edition. Special thanks to Brian Hogan, editor for the second edition, for his reviews, comments, suggestions, and encouragement. He provided much-needed guidance throughout the creation of this edition. Thanks to the entire Pragmatic Programmers team for taking up this edition and for their support throughout the production process.

  

Part I

Beginning Groovy

  CHAPTER

  1 Getting Started Before we can crank out some Groovy code, we need to get Groovy installed.

  In this chapter you’ll learn how to quickly install Groovy and make sure everything is working well. Taking care of these basics now will help us move quickly to the fun things ahead.

1.1 Installing Groovy

  Getting a stable working copy of Groovy is really simple: just visit the Groovy home page at and click the Download link. We can

  

  download either the binary release or the source release. Download the source release to build Groovy locally or to explore the source code. Otherwise, download the binary release. For Windows, we can also get the Windows Installer version. While we’re there, let’s also grab the documentation for Groovy.

  For programmers on the Groovy users mailing list who’re bleeding-edge types, the previously mentioned releases will not suffice. They’ll want the latest prerelease version of the language implementation. We can get the snapshot .

  We also need the JDK 1.5 or newer, so we need to make sure Java is installed 1 on the local system.

  Let’s get Groovy installed.

  Installing Groovy on Windows

  We can use the one-click installer for Windows—simply run it and follow the instructions. Programmers who prefer more control over the installation can use the binary distribution package.

  1.

  Next we have to set the GROOVY_HOME environment variable and the path. Edit the system-environment variables (by going into Control Panel and opening the System application). Create an environment variable named ,

GROOVY_HOME

  and set it to the location of the Groovy directory (for example, I set it to ). Also, add to the environment

  C:\programs\groovy\groovy-2.1.0 %GROOVY_HOME%\bin Path

  variable to set the location of the Groovy bin directory in the path. Remember to separate directories in the path using a semicolon ( ).

  ;

  Next, confirm that the environment variable is pointing to the location

  

JAVA_HOME

of the Java Development Kit (JDK) directory (if it’s not present, set it).

  That’s pretty much all we have to do. Remember to close any open command window, because the changes to environment variables don’t take effect until we reopen command windows. In a new command window, type , and

  groovy -v make sure it reports the correct version.

  Installing Groovy on Unix-like Systems

  Unzip the downloaded binary distribution. to see if there are special distributions and instructions for different flavors of Unix. Move the directory to a desired location. For instance, on

  groovy-2.1.0 my Mac system, I have it in the /opt/groovy directory.

  Next, set the environment variable and the path. Depending on

GROOVY_HOME

  the shell you use, you have to edit different profile files. You probably know where to go—refer to the appropriate documentation if you need help figuring out what to edit. I use bash on OS X, so I edited the ~/.bash_profile file. In that file, I added an entry export GROOVY_HOME="/opt/groovy/groovy-2.1.0" to set the environment variable . Also add to the envi-

  

GROOVY_HOME $GROOVY_HOME/bin path

ronment variable.

  Next, confirm that the environment variable is pointing to the location

JAVA_HOME

  of the JDK directory (if it’s not present, set it). ls -l `which java` should help determine the location of the Java installation. Installation of Groovy is complete and we’re ready to use the language. Close any open terminal windows—changes to environment variables don’t take effect until we reopen the windows. We may source the profile file instead, but it’s simple and easy to open a new terminal. In a new terminal window, type the command , and make sure it reports the correct version.

  groovy -v

  That’s all there is to it!

  1.2 Installing and Managing Groovy Versions

  We often have to work with multiple versions of the language for various projects. The task of managing the right version for a project can quickly turn into a time sink if we’re not careful. GVM, the Groovy environment manager, can manage not only the versions of the Groovy language, but also versions of Groovy-related libraries and tools, like Grails, Griffon, Gradle, and so on. The tool is a breeze to install and is supported on various flavors of xnix and 2 on Windows through Cygwin. Once you install GVM, you can see a list of available and installed versions of the language by simply running the com- mand . If you want to use a particular version of Groovy, say

  gvm list groovy

  version 2.1.1, you can specify that. For instance, to run the examples in this book, we can type the command gvm install groovy 2.1.1 . GVM will then download the version and install it for use. If we have installed multiple versions of Groovy and want to switch to version 2.1.1, for example, we can use the command .

  gvm use groovy 2.1.1

  1.3 Test-Drive Using groovysh

  We’ve installed Groovy and checked the version—it’s time to take it for a test- drive. Using the command-line tool is one of the quickest ways to play

  groovysh

  with Groovy. Open a terminal window, and type groovysh ; we’ll see a shell, as shown next. Type some Groovy code to see how it works.

  > groovysh Groovy Shell (2.1.1, JVM: 1.7.0_04-ea) Type 'help' or '\h' for help.

  • groovy:000> Math.sqrt(16)

  ===> 4.0

  groovy:000> println 'Test drive Groovy'

  Test drive Groovy ===> null

  groovy:000> String.metaClass.isPalindrome = { groovy:001> delegate == delegate.reverse() groovy:002> }

  ===> groovysh_evaluate$_run_closure1@64b99636

  groovy:000> 'mom'.isPalindrome()

  ===> true

  groovy:000> 'mom'.l

  lastIndexOf( leftShift( length()

  groovy:000> 'mom'.l 2. groovysh is a good tool for interactively trying out small Groovy code examples.

  It is also useful for experimenting with some code while we’re in the middle of coding. Be aware, however, that has some idiosyncrasies. If we run

  groovysh

  into problems with it, we can use the save command to save the code to a file and then try running from the command line using the command to

  groovy

  get around any tool-related issues. The groovysh command compiles and exe- cutes completed statements as soon as we press the key, and

  Enter/Return

  prints the result of that statement execution along with any output from the execution. If we type , for example, it prints the result, . However, if we type

  Math.sqrt(16)

  4.0 println 'Test drive Groovy' , it prints the words in quotes followed by null , indicating

  that returned nothing.

  println()

  We can also type code that spans multiple lines—simply use a semicolon at the end of the line if it complains, as in the line defining the dynamic method . When we type a class, a method, or even an statement,

  isPalindrome() if groovysh

  waits until we finish to execute that code. Next to the groovy: prompt it tells us how many lines it has accumulated for execution. If we’re not sure what command to type, we can type as much as we know and press the key. The shell will print methods that are available to us,

  Tab