www.it-ebooks.info www.it-ebooks.info 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. www.it-ebooks.info 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 www.it-ebooks.info Programming Groovy 2 Dynamic Productivity for the Java Developer Venkat Subramaniam The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina www.it-ebooks.info 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 titles, please visit us at http://pragprog.com . 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) Copyright © 2013 The Pragmatic Programmers, LLC . All rights reserved. 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, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-937785-30-7 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—July 2013 www.it-ebooks.info To Mythili and Balu—for being much more than an aunt and an uncle—for being there when I needed them most. www.it-ebooks.info Contents Foreword to the Second Edition . . . . . . . . xiii Introduction . . . . . . . . . . . . . xv Part I — Beginning Groovy 1. Getting Started . . . . . . . . . . . . 3 Installing Groovy 31.1 1.2 Installing and Managing Groovy Versions 5 1.3 Test-Drive Using groovysh 5 1.4 Using groovyConsole 6 1.5 Running Groovy on the Command Line 7 1.6 Using an IDE 8 2. Groovy for Java Eyes . . . . . . . . . . 11 From Java to Groovy 112.1 2.2 JavaBeans 19 2.3 Flexible Initialization and Named Arguments 22 2.4 Optional Parameters 24 2.5 Using Multiple Assignments 25 2.6 Implementing Interfaces 26 2.7 Groovy Boolean Evaluation 30 2.8 Operator Overloading 31 2.9 Support of Java 5 Language Features 33 2.10 Using Groovy Code-Generation Transformations 40 2.11 Gotchas 46 3. Dynamic Typing . . . . . . . . . . . . 53 Typing in Java 533.1 3.2 Dynamic Typing 54 3.3 Dynamic Typing != Weak Typing 55 www.it-ebooks.info 3.4 Design by Capability 56 3.5 Optional Typing 61 3.6 Multimethods 62 3.7 Dynamic: To Be or Not to Be? 65 3.8 Switching Off Dynamic Typing 65 4. Using Closures . . . . . . . . . . . . 71 The Convenience of Closures 724.1 4.2 Programming with Closures 75 4.3 Ways to Use Closures 75 4.4 Passing Parameters to Closures 77 4.5 Using Closures for Resource Cleanup 78 4.6 Closures and Coroutines 80 4.7 Curried Closure 82 4.8 Dynamic Closures 84 4.9 Closure Delegation 86 4.10 Programming with Tail Recursion 89 4.11 Improving Performance Using Memoization 92 5. Working with Strings . . . . . . . . . . 97 Literals and Expressions 975.1 5.2 GString Lazy-Evaluation Problem 100 5.3 Multiline Strings 103 5.4 String Convenience Methods 105 5.5 Regular Expressions 106 6. Working with Collections . . . . . . . . . 109 Using List 1096.1 6.2 Iterating Over an ArrayList 111 6.3 Using Finder Methods 113 6.4 Other Convenience Methods on Lists 115 6.5 Using the Map Class 118 6.6 Iterating Over Map 120 6.7 Other Convenience Methods on Maps 122 Part II — Using Groovy 7. Exploring the GDK . . . . . . . . . . . 127 7.1 Using Object Extensions 128 7.2 Other Extensions 133 7.3 Custom Methods Using the Extension Modules 139 Contents • viii www.it-ebooks.info 8. Working with XML . . . . . . . . . . . 143 8.1 Parsing XML 143 8.2 Creating XML 148 9. Working with Databases . . . . . . . . . 151 Setting Up the Database 1519.1 9.2 Connecting to a Database 152 9.3 Database Select 153 9.4 Transforming Data to XML 154 9.5 Using DataSet 155 9.6 Inserting and Updating 156 9.7 Accessing Microsoft Excel 156 10. Working with Scripts and Classes . . . . . . . 159 The Melting Pot of Java and Groovy 15910.1 10.2 Running Groovy 160 10.3 Using Groovy Classes from Groovy 161 10.4 Intermixing Groovy and Java with Joint Compilation 162 10.5 Creating and Passing Groovy Closures from Java 163 10.6 Calling Groovy Dynamic Methods from Java 165 10.7 Using Java Classes from Groovy 166 10.8 Using Groovy Scripts from Groovy 167 10.9 Using Groovy Scripts from Java 169 Part III — MOPping Groovy 11. Exploring Metaobject Protocol (MOP) . . . . . . 175 11.1 Groovy Object 176 11.2 Querying Methods and Properties 180 11.3 Dynamically Accessing Objects 182 12. Intercepting Methods Using MOP . . . . . . . 185 12.1 Intercepting Methods Using GroovyInterceptable 185 12.2 Intercepting Methods Using MetaClass 188 13. MOP Method Injection . . . . . . . . . . 193 Injecting Methods Using Categories 19313.1 13.2 Injecting Methods Using ExpandoMetaClass 198 13.3 Injecting Methods into Specific Instances 203 13.4 Injecting Methods Using Mixins 206 13.5 Decorating Classes with Multiple Mixins 208 Contents • ix www.it-ebooks.info [...]... 18 .2 Unit Testing Java and Groovy Code 18.3 Testing for Exceptions 18.4 Mocking 18.5 Mocking by Overriding 18.6 Mocking Using Categories 18.7 Mocking Using ExpandoMetaClass 18.8 Mocking Using Expando 18.9 Mocking Using Map 18.10 Mocking Using the Groovy Mock Library 27 1 27 1 27 2 27 7 27 7 28 0 28 3 28 4 28 5 28 8 28 9 19 Creating DSLs in Groovy 19.1 Context 19 .2 Fluency 19.3 Types of DSLs 29 5 29 5 29 7 29 8... at Compile Time 16 .2 Intercepting Method Calls Using AST Transformations 16.3 Injecting Methods Using AST Transformations 23 5 23 6 24 1 24 6 Part IV — Using Metaprogramming 17 Groovy Builders 17.1 Building XML 17 .2 Building JSON 17.3 Building Swing 17.4 Custom Builder Using Metaprogramming 17.5 Using BuilderSupport 17.6 Using FactoryBuilderSupport 25 3 25 3 25 6 25 8 26 0 26 2 26 6 18 Unit Testing...Contents 14 MOP 14.1 14 .2 14.3 •x Method Synthesis Method Synthesis Using methodMissing Method Synthesis Using ExpandoMetaClass Synthesizing Methods for Specific Instances 21 5 21 6 22 0 22 2 15 MOPping Up 15.1 Creating Dynamic Classes with Expando 15 .2 Method Delegation: Putting It All Together 15.3 Review of MOP Techniques 22 5 22 5 22 7 23 1 16 Applying Compile-Time Metaprogramming 16.1... 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: 0 02> } ===> groovysh_evaluate$_run_closure1@64b99636 groovy: 000> 'mom'.isPalindrome() ===> true groovy: 000> 'mom'.l lastIndexOf( leftShift( groovy: 000> 'mom'.l 2 length() http://gvmtool.net www.it-ebooks.info... Using groovysh We’ve installed Groovy and checked the version—it’s time to take it for a testdrive Using the command-line tool groovysh is one of the quickest ways to play 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>... list groovy If you want to use a particular version of Groovy, say 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... install Groovy and take it for a test-drive using groovysh and groovyConsole We’ll also see how to run Groovy without these tools—from the command line and within an integrated development environment In 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... 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... System.out.print("ho "); } System.out.println("Merry Groovy! "); } } www.it-ebooks.info report erratum • discuss Chapter 2 Groovy for Java Eyes • 12 Let’s execute this code using the command groovy Greetings .groovy and take a look at the output: ho ho ho Merry Groovy! That’s a lot of code for such a simple task Still, Groovy obediently accepted and executed it Groovy has a higher signal-to-noise ratio than... 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 . Running Groovy on the Command Line 7 1.6 Using an IDE 8 2. Groovy for Java Eyes . . . . . . . . . . 11 From Java to Groovy 1 12. 1 2. 2 JavaBeans 19 2. 3 Flexible Initialization and Named Arguments 22 2. 4. Parameters 24 2. 5 Using Multiple Assignments 25 2. 6 Implementing Interfaces 26 2. 7 Groovy Boolean Evaluation 30 2. 8 Operator Overloading 31 2. 9 Support of Java 5 Language Features 33 2. 10 Using Groovy. Expando 22 5 15 .2 Method Delegation: Putting It All Together 22 7 15.3 Review of MOP Techniques 23 1 16. Applying Compile-Time Metaprogramming . . . . . 23 5 16.1 Analyzing Code at Compile Time 23 6 16.2