Groovy in Action.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Groovy in Action Groovy in Action DIERK KÖNIG WITH ANDREW GLOVER, PAUL KING GUILLAUME LAFORGE, AND JON SKEET MANNING Greenwich (74° w. long.) For online information and ordering of this and other Manning books, please go to www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. Cherokee Station PO Box 20386 Fax: (609) 877-8256 New York, NY 10021 email: [email protected] ©2007 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books they publish printed on acid-free paper, and we exert our best efforts to that end. Manning Publications Co. Cherokee Station Copyeditor: Benjamin Berg PO Box 20386 Typesetter: Denis Dalinnik New York, NY 10021 Cover designer: Leslie Haimes ISBN 1-932394-84-2 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 10 09 08 07 06 To the love of my life —D.K. brief contents 1 ■ Your way to Groovy 1 PART 1 THE GROOVY LANGUAGE ...................................... 27 2 ■ Overture: The Groovy basics 29 3 ■ The simple Groovy datatypes 55 4 ■ The collective Groovy datatypes 93 5 ■ Working with closures 122 6 ■ Groovy control structures 153 7 ■ Dynamic object orientation, Groovy style 174 PART 2 AROUND THE GROOVY LIBRARY ........................ 227 8 ■ Working with builders 229 9 ■ Working with the GDK 277 10 ■ Database programming with Groovy 323 11 ■ Integrating Groovy 360 12 ■ Working with XML 401 vii viii BRIEF CONTENTS PART 3 EVERYDAY GROOVY ............................................ 451 13 ■ Tips and tricks 453 14 ■ Unit testing with Groovy 503 15 ■ Groovy on Windows 546 16 ■ Seeing the Grails light 572 appendix A ■ Installation and documentation 606 appendix B ■ Groovy language info 610 appendix C ■ GDK API quick reference 613 appendix D ■ Cheat sheets 631 contents foreword xix preface xx acknowledgments xxiii about this book xxv about the authors xxix about the title xxxii about the cover illustration xxxiii Your way to Groovy 1 1 1.1 The Groovy story 3 What is Groovy? 4 ■ Playing nicely with Java: seamless integration 4 ■ Power in your code: a feature-rich language 6 Community-driven but corporate-backed 9 1.2 What Groovy can do for you 10 Groovy for Java professionals 10 ■ Groovy for script programmers 11 ■ Groovy for pragmatic programmers, extremos, and agilists 12 1.3 Running Groovy 13 Using groovysh for “Hello World” 14 ■ Using groovyConsole 17 ■ Using groovy 18 ix x CONTENTS 1.4 Compiling and running Groovy 19 Compiling Groovy with groovyc 19 ■ Running a compiled Groovy script with Java 20 ■ Compiling and running with Ant 21 1.5 Groovy IDE and editor support 22 IntelliJ IDEA plug-in 23 ■ Eclipse plug-in 24 Groovy support in other editors 24 1.6 Summary 25 PART 1 THE GROOVY LANGUAGE ..................................... 27 Overture: The Groovy basics 29 2 2.1 General code appearance 30 Commenting Groovy code 30 ■ Comparing Groovy and Java syntax 31 ■ Beauty through brevity 32 2.2 Probing the language with assertions 33 2.3 Groovy at a glance 36 Declaring classes 36 ■ Using scripts 37 ■ GroovyBeans 38 Handling text 39 ■ Numbers are objects 40 ■ Using lists, maps, and ranges 41 ■ Code as objects: closures 43 Groovy control structures 46 2.4 Groovy’s place in the Java environment 47 My class is your class 47 ■ GDK: the Groovy library 49 The Groovy lifecycle 50 2.5 Summary 53 The simple Groovy datatypes 55 3 3.1 Objects, objects everywhere 56 Java’s type system—primitives and references 56 Groovy’s answer—everything’s an object 57 Interoperating with Java—automatic boxing and unboxing 59 No intermediate unboxing 60 3.2 The concept of optional typing 61 Assigning types 61 ■ Static versus dynamic typing 62 3.3 Overriding operators 63 Overview of overridable operators 63 ■ Overridden operators in action 65 ■ Making coercion work for you 67 CONTENTS xi 3.4 Working with strings 69 Varieties of string literals 69 ■ Working with GStrings 72 From Java to Groovy 74 3.5 Working with regular expressions 76 Specifying patterns in string literals 78 ■ Applying patterns 81 Patterns in action 82 ■ Patterns and performance 85 Patterns for classification 86 3.6 Working with numbers 87 Coercion with numeric operators 87 GDK methods for numbers 90 3.7 Summary 91 The collective Groovy datatypes 93 4 4.1 Working with ranges 94 Specifying ranges 95 ■ Ranges are objects 97 Ranges in action 98 4.2 Working with lists 100 Specifying lists 100 ■ Using list operators 101 Using list methods 104 ■ Lists in action 109 4.3 Working with maps 111 Specifying maps 111 ■ Using map operators 113 Maps in action 117 4.4 Notes on Groovy collections 119 Understanding concurrent modification 119 Distinguishing between copy and modify semantics 120 4.5 Summary 121 Working with closures 122 5 5.1 A gentle introduction to closures 123 5.2 The case for closures 125 Using iterators 125 ■ Handling resources 127 5.3 Declaring closures 130 The simple declaration 130 ■ Using assignments for declaration 131 ■ Referring to methods as closures 131 Comparing the available options 133 xii CONTENTS 5.4 Using closures 135 Calling a closure 135 ■ More closure methods 137 5.5 Understanding scoping 141 The simple variable scope 142 ■ The general closure scope 143 Scoping at work: the classic accumulator test 146 5.6 Returning from closures 148 5.7 Support for design patterns 149 Relationship to the Visitor pattern 149 ■ Relationship to the Builder pattern 150 ■ Relationship to other patterns 151 5.8 Summary 151 Groovy control structures 153 6 6.1 The Groovy truth 154 Evaluating Boolean tests 154 ■ Assignments within Boolean tests 156 6.2 Conditional execution structures 158 The humble if statement 158 ■ The conditional ?: operator 159 ■ The switch statement 160 Sanity checking with assertions 163 6.3 Looping 167 Looping with while 167 ■ Looping with for 168 6.4 Exiting blocks and methods 170 Normal termination: return/break/continue 170 Exceptions: throw/try-catch-finally 171 6.5 Summary 172 Dynamic object orientation, Groovy style 174 7 7.1 Defining classes and scripts 175 Defining fields and local variables 176 ■ Methods and parameters 180 ■ Safe dereferencing with the ?. operator 184 Constructors 185 7.2 Organizing classes and scripts 188 File to class relationship 188 ■ Organizing classes in packages 190 ■ Further classpath considerations 194 7.3 Advanced OO features 195 Using inheritance 195 ■ Using interfaces 196 Multimethods 197 CONTENTS xiii 7.4 Working with GroovyBeans 199 Declaring beans 200 ■ Working with beans 201 Using bean methods for any object 205 Fields, accessors, maps, and Expando 206 7.5 Using power features 207 Querying objects with GPaths 208 ■ Injecting the spread operator 212 ■ Mix-in categories with the use keyword 213 7.6 Meta programming in Groovy 216 Understanding the MetaClass concept 216 ■ Method invocation and interception 218 ■ Method interception in action 220 7.7 Summary 224 PART 2 AROUND THE GROOVY LIBRARY........................... 227 Working with builders 229 8 8.1 Learning by example—using a builder 231 8.2 Building object trees with NodeBuilder 234 NodeBuilder in action—a closer look at builder code 235 Understanding the builder concept 237 ■ Smart building with logic 237 8.3 Working with MarkupBuilder 239 Building XML 240 ■ Building HTML 241 8.4 Task automation with AntBuilder 243 From Ant scripts to Groovy scripts 243 ■ How AntBuilder works 245 ■ Smart automation scripts with logic 246 8.5 Easy GUIs with SwingBuilder 247 Reading a password with SwingBuilder 248 ■ Creating Swing widgets 250 ■ Arranging your widgets 254 ■ Referring to widgets 257 ■ Using Swing actions 260 ■ Using models 262 ■ Putting it all together 264 8.6 Creating your own builder 271 Subclassing BuilderSupport 272 The DebugBuilder example 274 8.7 Summary 276 xiv CONTENTS Working with the GDK 277 9 9.1 Working with Objects 278 Interactive objects 279 ■ Convenient Object methods 285 Iterative Object methods 288 9.2 Working with files and I/O 291 Traversing the filesystem 294 ■ Reading from input sources 295 ■ Writing to output destinations 297 Filters and conversions 298 ■ Streaming serialized objects 300 9.3 Working with threads and processes 301 Groovy multithreading 302 Integrating external processes 304 9.4 Working with templates 309 Understanding the template format 309 ■ Templates in action 310 ■ Advanced template issues 312 9.5 Working with Groovlets 314 Starting with “hello world” 314 ■ The Groovlet binding 316 Templating Groovlets 319 9.6 Summary 321 Database programming with Groovy 323 10 10.1 Basic database operations 325 Setting up for database access 325 ■ Executing SQL 329 Fetching data 334 ■ Putting it all together 338 10.2 DataSets for SQL without SQL 340 Using DataSet operations 341 ■ DataSets on database views 344 10.3 Organizing database work 347 Architectural overview 347 ■ Specifying the application behavior 349 ■ Implementing the infrastructure 350 Using a transparent domain model 355 ■ Implementing