www.it-ebooks.info Groovy 2 Cookbook Over 90 recipes that provide solutions to everyday programming challenges using the powerful features of Groovy 2 Andrey Adamovich Luciano Fiandesio BIRMINGHAM - MUMBAI www.it-ebooks.info Groovy 2 Cookbook Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: October 2013 Production Reference: 1151013 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84951-936-6 www.packtpub.com Cover Image by Jarek Blaminsky (milak6@wp.pl) www.it-ebooks.info Credits Authors Andrey Adamovich Luciano Fiandesio Reviewers Kunal Dabir Ayan Dave Fergal Dearle Eric Kelm Guillaume Laforge Acquisition Editors Kartikey Pandey Rebecca Youe Lead Technical Editor Ankita Shashi Technical Editors Pragnesh Bilimoria Jinesh Kampani Sandeep Madnaik Chandni Maishery Ankita Thakur Project Coordinator Apeksha Chitnis Proofreaders Ameesha Green Katherine Tarr Indexer Hemangini Bari Graphics Ronak Dhruv Yuvraj Mannari Production Coordinator Shantanu Zagade Cover Work Shantanu Zagade www.it-ebooks.info About the Authors Andrey Adamovich is a software craftsman with many years of experience in different lifecycle phases of software creation. He is passionate about dening good development practices, documenting and presenting architecture, the reuse of code and design patterns, the proling 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. I would like to thank my wife Lena for her patience and understanding that gave me enough time and energy to focus on the book. Many thanks to my friends, Sergey and Dmitry, who attentively reviewed book chapters and shared their insightful comments. And, of course, I'm very grateful to Luciano for the exciting experience we had together while working on this book. 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. I'd like to thank Andrey, my business partner, friend, and co-author on this book; Laura, my life partner for her patience; Matteo, my brother, for his help; and Pierluigi for reviewing the book. www.it-ebooks.info About the Reviewers Ayan Dave is a software engineer that takes pride in building and delivering high quality applications using languages and components in the JVM ecosystem. He is passionate about software development and enjoys exploring open source projects. He is enthusiastic about Agile and Extreme Programming, and frequently advocates for them. Over the years, he has provided a consulting service to several organizations and has played many different roles. Most recently, he is the "Architectus Oryzus" for a project team with big ideas, and he subscribes to the idea that running code is the system of truth. He has a Master's degree in Computer Engineering from the University of Houston-Clear Lake and holds PMP, PSM-1, and OCMJEA certications. He is also a speaker on various technical topics at local user groups and community events. He currently lives in Columbus, Ohio, where he works with Quick Solutions Inc. In the digital world, he can be found at http://daveayan.com. Fergal Dearle has been writing code since he started writing BASIC as a bellbottom-wearing teenager in the 70s. The jeans aren't bellbottoms anymore and the code is in Groovy, not BASIC but he's still wearing jeans and he's still coding. Recently, he can be found mostly working on web-based projects in Groovy on Grails as his framework of choice. He is the author of Groovy for Domain Specic Languages and is a passionate advocate of Agile methods. Eric Kelm is senior software developer with over nine years of experience as a developer, senior developer, and technical lead, delivering top-notch solutions to customers. His current focus is developing Java web applications, particularly with the Groovy-based Grails framework. He holds a Bachelor's degree in Computer Science from the Sam Houston State University. Along with his day-to-day work, he also shares his insights into some of his technical solutions with a broader audience through his blog http://asoftwareguy.com. www.it-ebooks.info Guillaume Laforge is the project lead of the Groovy language. He works for Pivotal, formerly the SpringSource division of VMware. Guillaume co-authored the Groovy in Action best-seller, and speaks regularly about Groovy, Domain-Specic Languages, and various Groovy related topics at conferences worldwide. www.it-ebooks.info www.PacktPub.com Support les, eBooks, discount offers and more You might want to visit www.PacktPub.com for support les and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub les available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? f Fully searchable across every book published by Packt f Copy and paste, print and bookmark content f On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. www.it-ebooks.info www.it-ebooks.info Table of Contents Preface 1 Chapter 1: Getting Started with Groovy 7 Introduction 7 Installing Groovy on Windows 8 Installing Groovy on Linux and OS X 10 Executing Groovy code from the command line 11 Using Groovy as a command-line text le editor 14 Using Groovy to start a server on the command line 16 Running Groovy with invokedynamic support 17 Building Groovy from source 18 Managing multiple Groovy installations on Linux 20 Using groovysh to try out Groovy commands 23 Starting groovyConsole to execute Groovy snippets 29 Conguring Groovy in Eclipse 35 Conguring Groovy in IntelliJ IDEA 42 Chapter 2: Using Groovy Ecosystem 47 Introduction 47 Using Java classes from Groovy 48 Embedding Groovy into Java 51 Compiling Groovy code 57 Simplifying dependency management with Grape 60 Integrating Groovy into the build process using Ant 63 Integrating Groovy into the build process using Maven 71 Integrating Groovy into the build process using Gradle 75 Generating documentation for Groovy code 78 Checking Groovy code's quality with CodeNarc 82 www.it-ebooks.info [...]... scripts 21 8 Introduction 22 3 Creating a database table 22 4 Connecting to an SQL database 22 8 Querying an SQL database 23 1 Modifying data in an SQL database 23 5 Calling a stored procedure 23 9 Reading BLOB/CLOB from a database 24 2 Building a simple ORM framework 24 4 Using Groovy to access Redis 24 6 Using Groovy to access MongoDB 25 2 Using Groovy to access Apache Cassandra 25 6 Introduction 26 3 Downloading content... Databases in Groovy 22 3 Chapter 8: Working with Web Services in Groovy 26 3 Chapter 9: Metaprogramming and DSLs in Groovy 28 9 Introduction 197 Parsing JSON messages with JsonSlurper 198 Constructing JSON messages with JsonBuilder 20 1 Modifying JSON messages 20 4 Validating JSON messages 20 5 Converting JSON message to XML 21 1 Converting JSON message to Groovy Bean 21 4 Using JSON to configure your scripts 21 8 Introduction 22 3... groovy 2. 1.6 Default groovy version set to 2. 1.6 6 You can also verify that Groovy is running and is the requested version by typing: > groovy version Groovy Version: 2. 1.6 JVM: 7 To switch temporarily to a different Groovy distribution, just type: > gvm use groovy 1.8.6 Using groovy version 1.8.6 in this shell 8 Another way to check which version of Groovy is currently active is: > gvm current groovy. .. download the Groovy 2. 0 binaries as described in the Installing Groovy on Windows recipe and perform the following steps to install Groovy on Linux and OS X: 1 Create a new folder for the Groovy distribution: sudo mkdir /usr/share /groovy 2 Move the unzipped Groovy folder into /usr/share /groovy and create a symlink to the folder, without using the version number: sudo mv groovy- 2. 1.6 /usr/share /groovy/ sudo... Internet 26 4 Executing an HTTP GET request 26 5 Executing an HTTP POST request 26 8 Constructing and modifying complex URLs 27 1 Issuing a REST request and parsing a response 27 2 Issuing a SOAP request and parsing a response 27 6 Consuming RSS and Atom feeds 27 9 Using basic authentication for web service security 28 3 Using OAuth for web service security 28 4 Introduction 28 9 Querying methods and properties 29 0... with Groovy In this chapter, we will cover: ff Installing Groovy on Windows ff Installing Groovy on Linux and OS X ff Executing Groovy code from the command line ff Using Groovy as a command-line text file editor ff Using Groovy to start a server on the command line ff Running Groovy with invokedynamic support ff Building Groovy from source ff Managing multiple Groovy installations on Linux ff Using groovysh... command: > gvm install groovy 1.8.6 Downloading: groovy 1.8.6 Installing: groovy 1.8.6 Done installing! 21 www.it-ebooks.info Getting Started with Groovy 4 Again it will ask about setting 1.8.6 as default Groovy distribution Answer n (no) in this case since we would like to keep v2 as the primary one: Do you want groovy 1.8.6 to be set as default? (Y/n): n 5 To set (or to ensure) Groovy version used... run as Groovy scripts or directly in the GroovyConsole As a result, whether you're sitting by a computer or in a plane, you get the benefit of seeing their exact output ff The book covers not only the Groovy language, but also has several recipes on Groovy libraries and tools, including Gradle, concurrent programming, and functional testing This book covers Groovy 2. 0 and 2. 1 The Groovy language Groovy. .. functionality to the existing Java /Groovy classes 123 Defining type-checking rules for dynamic code 126 Adding automatic logging to Groovy classes 1 32 Chapter 4: Working with Files in Groovy 135 Chapter 5: Working with XML in Groovy 167 Introduction 136 Reading from a file 136 Reading a text file line by line 138 Processing every word in a text file 140 Writing to a file 1 42 Replacing tabs with spaces in... from 1 to 5: 1 To multiply each number by 2, you can use the following command: groovy -n -e "println line.toLong() * 2" data.txt 2 We can even omit the println method call if we pass additional the -p parameter to the command: groovy -n -p -e "line.toLong() * 2" data.txt 14 www.it-ebooks.info Chapter 1 3 In both cases, Groovy will print the following output: 2 4 6 8 10 How it works Due to the fact . in Groovy 22 3 Introduction 22 3 Creating a database table 22 4 Connecting to an SQL database 22 8 Querying an SQL database 23 1 Modifying data in an SQL database 23 5 Calling a stored procedure 23 9 Reading. groovysh to try out Groovy commands 23 Starting groovyConsole to execute Groovy snippets 29 Conguring Groovy in Eclipse 35 Conguring Groovy in IntelliJ IDEA 42 Chapter 2: Using Groovy Ecosystem. BLOB/CLOB from a database 24 2 Building a simple ORM framework 24 4 Using Groovy to access Redis 24 6 Using Groovy to access MongoDB 25 2 Using Groovy to access Apache Cassandra 25 6 Chapter 8: Working