39,59 €
Get up to speed with Groovy, a language for the Java Virtual Machine (JVM) that integrates features of both object-oriented and functional programming. This book will show you the powerful features of Groovy 2 applied to real-world scenarios and how the dynamic nature of the language makes it very simple to tackle problems that would otherwise require hours or days of research and implementation.
Groovy 2 Cookbook contains a vast number of recipes covering many facets of today's programming landscape. From language-specific topics such as closures and metaprogramming, to more advanced applications of Groovy flexibility such as DSL and testing techniques, this book gives you quick solutions to everyday problems.
The recipes in this book start from the basics of installing Groovy and running your first scripts and continue with progressively more advanced examples that will help you to take advantage of the language's amazing features.
Packed with hundreds of tried-and-true Groovy recipes, Groovy 2 Cookbook includes code segments covering many specialized APIs to work with files and collections, manipulate XML, work with REST services and JSON, create asynchronous tasks, and more. But Groovy does more than just ease traditional Java development: it brings modern programming features to the Java platform like closures, duck-typing, and metaprogramming.
In this new book, you'll find code examples that you can use in your projects right away along with a discussion about how and why the solution works. Focusing on what's useful and tricky, Groovy 2 Cookbook offers a wealth of useful code for all Java and Groovy programmers, not just advanced practitioners.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 419
Veröffentlichungsjahr: 2013
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 (<[email protected]>)
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
Andrey Adamovich is a software craftsman with many years of experience in different lifecycle phases of software creation. He is passionate about defining good development practices, documenting and presenting architecture, the reuse of code and design patterns, the profiling 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.
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 certifications. 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 Specific 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.
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-Specific Languages, and various Groovy related topics at conferences worldwide.
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files 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 <[email protected]> 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.
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.
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.
Groovy 2 Cookbook consists of problem-solving recipes for Groovy, one of the most flexible programming languages we have ever used. Th book contains solutions to more than 100 common problems, shown with more than 500 Groovy code snippets.
There are a few unique things about this book:
Th book covers Groovy 2.0 and 2.1.
Groovy arises from the self-imposed limitations of the Java language. Java is an "old" language, originally conceived in 1990 and released at the beginning of 1996 (Java 1.0). We are looking at a 20 year life span that, in our field, is equivalent to an ice age. Java was portable (remember the motto "write once, run anywhere"?), sported a truly object-oriented core, and provided an automatic management of memory. The Java platform evolved in two directions: Java Virtual Machine, an outstanding piece of software engineering, which has become increasingly powerful and more performant over the years, and the actual Java language. The latter unquestionably matured and changed since its origin, but it did so in a unnerving slow-motion pace. The reason for this pondered evolution lies in the strong ties that the Java language historically had with the enterprise world. This bond acted as a double-edged weapon. It gave the language the massive adoption and popularity that it enjoys today, but it tampered the ability to quickly adapt to an ever-changing IT landscape.
In order to counteract the lethargic adoption of new features in Java, new languages based on the JVM started to see the light. Groovy is one of these languages, along with Scala, Clojure, JRuby, Jython and many others. So what is Groovy? Groovy is an optionally typed, dynamic language for the JVM with many features influenced by languages Python, Ruby, and Smalltalk, making them available to Java developers using a Java- syntax. Groovy is designed to work seamlessly with Java at every level, from syntax alignment to bytecode generation (although it creates different bytecode). The language evolved from being a limited scripting language to a fully-fledged programming language that can be used in very different contexts, such as web applications and services, backend servers, background jobs, desktop applications.
The dynamic nature of the language allows a degree of flexibility hardly achievable with Java. Thanks to the language's metaprogramming features, it is possible to modify or augment the code and behavior at runtime or even at compile time (using AST) and create Domain-Specific Languages (DSL) in a breeze. Furthermore Groovy adds a huge number of convenience methods and approaches that simplify your code and make it more powerful.
We, the authors, have been programming in Groovy for many years now. We hope that through this book, we will be able to convey the great fun and productivity boost that we enjoyed by using this language.
Chapter 1, Getting Started with Groovy, covers the installation process on different operating systems and the basic tools that come with the language distribution.
Chapter 2, Using Groovy Ecosystem, introduces the Groovy ecosystem—a set of tools for compiling, embedding, building, documenting and running code analysis with Groovy.
Chapter 3, Using Groovy Language Features, shows the different facets of the Groovy language that allows you to write a terser, readable and less ceremonious code in comparison to Java.
Chapter 4, Working with Files in Groovy, covers I/O with Groovy, from simple cases such as reading a file to more complex endeavors mining data from a PDF file or an Excel spreadsheet.
Chapter 5, Working with XML in Groovy, introduces you to recipes that discuss how to consume and produce XML, as well as more advanced topics such serialization.
Chapter 6, Working with JSON in Groovy, covers Groovy's native support for reading and producing JSON documents.
Chapter 7, Working with Databases in Groovy, presents recipes related to data persistence, either through a relational SQL database or a NoSQL data store.
Chapter 8, Working with Web Services in Groovy, explains how to use Groovy to interact with SOAP and REST-based web services.
Chapter 9, Metaprogramming and DSLs in Groovy, covers advanced metaprogramming concepts such as dynamically extending classes with new methods, creating DSLs, and using AST transformation to modify the code at compilation time.
Chapter 10, Concurrent Programming in Groovy, introduces you to the GPars framework and several approaches to execute tasks concurrently.
Chapter 11, Testing with Groovy, covers how to use Groovy for testing not only code using unit tests, but also databases, web services and the performance of your application. This chapter is available online at: http://www.packtpub.com/sites/default/files/downloads/Testingwithgroovy.pdf.
In order to be able to run the examples in the book, you will need the Java Development Kit 1.6 or newer, and 2.0 (or higher) of Groovy.
This book is for Java and Groovy developers who have an interest in discovering new ways to quickly get the job done using the Groovy language, which shares many similarities with Java. The book's recipes start simple, therefore no extensive Groovy experience is required to understand and use the code and the explanations accompanying the examples. Some advanced recipes assume that the reader already has the necessary background to understand the topic at hand (for example, general knowledge of computer science, data structures, complexity, concurrent programming). Moreover, the recipes are often just skeletons that aim to provide essential information for getting started, but which require the reader to do more research to fill in the details. As such, it is assumed that the reader knows how to use search engines and how to access Groovy's online documentation.
Feedback from our readers is always welcome. Let us know what you think about this book—what you d or may have dis. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
In this chapter, we will cover:
The first chapter focuses on the basics of getting started with Groovy. We begin by showing how to install Groovy on the most popular operating systems and we move to some command-line tools available with the language distribution. The remaining recipes offer an overview of how the language easily integrates with the most popular Java IDEs.
In this recipe, we will provide instructions on installing the Groovy distribution on the Windows operating system.
The requirement for installing Groovy 2.0 is JDK 1.5 and higher. We assume that you have JDK installed and know how to use Java. In case you use JDK 7 or later, then you can take advantage of the dynamic language optimization present in that version. For instance, the invokedynamic bytecode instruction (see the Running Groovy with invokedynamic support recipe).
To install Groovy on Windows, you need to download the ZIP distribution from http://groovy.codehaus.org/Download.
The latest major version at the time of writing is 2.1.6. The latest minor version is 2.0.8. Since v2.0, Groovy has changed the release version numbering, so the next major version of Groovy will be 3.0 and the next minor versions will have the second digit increased (2.1, 2.2, 2.3, and so on).
Alternatively, you can build Groovy from the source distribution which is described in the Building Groovy from source recipe.
After downloading the zipped distribution, you need to unzip the archive to a directory of your choice and carry out the following steps to install Groovy on Windows:
If you get the output displayed as in the previous screenshot, your Groovy installation is complete.
As an alternative to the zipped archive, Windows users can also download a one-click installer (you can find the link on the same download page under the Download Windows-Installer link). Execute the installer and follow the instructions to get a fully functional Groovy installation.
This recipe gives you instructions for installing Groovy on any Linux distribution and Mac OS X.
As a starter, 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:
The output should display the installed Groovy version and the JDK in use.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Using the symbolic link called current, which we created in step 2, makes it very easy to upgrade to a newer version of Groovy by changing the folder to which the symbolic link points to.
Most *nix-based operating systems (such as Linux or Mac OS X) have package manager systems that allow you to install Groovy by simply typing a command in the terminal.
In Ubuntu, Groovy can be installed by simply typing:
The version installed by the Ubuntu package manager is quite old (1.7.10), so you may want to install Groovy manually as described in this recipe.
In OS X, you can use Homebrew as follows:
If you are happy with running a stable version of Groovy, but possibly not the most recent one, a package manager is the recommended way to get Groovy quickly and easily. If you want to install a beta version of Groovy or a version that is not yet available on the package manager system used by your OS, install the binaries from the website.
Groovy, by definition, is a language with scripting features. Many developers approach Groovy by writing short scripts to automate repetitive tasks. The language provides a set of command-line tools that help you create scripts that are usable within your favorite shell.
In this recipe, we will cover the execution of a simple script with the help of the groovy command, which is made available to you after a successful Groovy installation (see the Installing Groovy on Windows recipe and Installing Groovy on Linux and OS X recipe).
Let's start with the most abused example in programming books, printing Hello, World!:
In step 1, the actual Groovy code resides in the double quotes (") and uses the predefined println method to print a Hello, World! string. But to explain where the println method actually comes from, we need to give a bit more details on Groovy internals.
Every script in Groovy (a command-line parameter or a standalone script file) is compiled on the fly into a class that extends the groovy.lang.Script class (Javadoc for this class can be found at http://groovy.codehaus.org/api/groovy/lang/Script.html).
Naturally, a Script class is eventually inherited from java.lang.Object, which is the base class for all classes in both Java and Groovy. But since Groovy adds its own extension methods to many standard JDK classes (see the Adding a functionality to the existing Java/Groovy classes recipe in Chapter 3, Using Groovy Language Features for Information on Custom Extension Modules), java.lang.Object is enriched with many useful methods including println (the relevant Java documentation can be found at http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html#println(java.lang.Object)).
In fact, the groovy command has several other useful command-line options. If you type groovy --help, you can get a full list of them as shown in the following screenshot:
Let's go through some of those options to get a better overview of the possibilities.
First of all, -classpath, --classpath, and -cp options work in a very similar way to the java command. You just specify a list of the *.jar files or list of directories with the *.class files. The only peculiarity is that -classpath must come as the first parameter in the command line; otherwise Groovy will not recognize it.
Another parameter that is common with the java command is -D, which allows to pass the system properties to your script in the following way:
One of the strengths of Groovy (as opposed to Java) is its conciseness. This rule is also applied to what Groovy prints out if an exception occurs in your script:
To print the conventional full Java stack trace, you can use the -d or -debug options (some stack trace lines are omitted for brevity):
For additional command-line features, please refer to the following recipes:
For more information on the Groovy script structure and Groovy additions, go to:
The groovy command, which we introduced in the Executing Groovy code from the command line recipe, can also be used as a stream editor or text file filter. In this recipe, we will cover the -i, -n, and -p parameters that can be used to leverage file editing and processing functionality.
Assume that you have a file, data.txt, which contains five lines with numbers from 1 to 5:
Due to the fact that we are using the -n option, the code in double quotes is applied to each line read from the datafile specified as the last parameter in the command line. The line variable is predefined by Groovy, and you can use it to access, filter, or modify the line's content.
If you add the -i option to the previous command, then it will actually modify the input file, with output values as follows:
Adding a suffix .bak to the -i option will save the original input file data.txt under data.txt.bak:
You can use the -n and -p options to filter the input stream of other operating system commands. For example, if you want to filter the output of a directory listing command (dir) to show only the *.jar files, on Windows you can use the following command:
Or on *nix-based operating systems, you can use the following command:
Of course, the result of the previous commands can be easily achieved by more efficient operating system instructions. However, these examples are given to demonstrate that you can actually leverage the full power of the Groovy and Java programming languages to implement more complex processing rules.
In this recipe, we continue to explore the groovy command's features at one's disposal. This time, we show how to create a process capable of serving client requests through TCP/IP directly from the command line and with one line of code.
The command-line option that we are going to use for this purpose is -l:
In this way, you can quite easily organize communication channels for ad hoc notifications on different hosts.
One of the biggest improvements introduced in Groovy 2.0 is the support for the invokedynamic instruction. The invokedynamic is a new JVM instruction available in Java 7, which allows easier implementation and promises increased speed and efficiency of dynamic languages (for example, Groovy).
Dynamic languages generate a bytecode that often necessitates a number of JVM method invocations to perform a single operation. Furthermore, reflection and dynamic proxies are used extensively, which comes with a costly performance toll. Also, the JIT (Just-In-Time) compiler that helps to improve the runtime performance of a JVM, cannot work its magic by applying optimization to the bytecode because it lacks information and patterns, which are normally possible to optimize. The new bytecode instruction, invokedynamic, is able to mitigate partially these issues, including support for better JIT optimization.
In this recipe, we will show how to run Groovy with the invokedynamic (also known as indy) support and Java 7.
The invokedynamic support is a compile-time and runtime feature only. In other words, a developer cannot use it from within the source code. What invokedynamic brings to Groovy 2.0 (and even more to 2.1) is basically improved runtime performance.
As explained in the introduction, Java 7 is the required version of the JVM to compile Groovy code that leverages the invokedynamic instruction:
It is important to note that if the --indy flag is omitted, the code will be compiled without the invokedynamic support, even if Java 7 is used and the Groovy JAR files have been replaced.
The performance gain introduced by the new JVM instruction greatly varies depending on a numbers of factors, including the actual JVM version and the type of code that is optimized. JVM support for the invokedynamic instruction improves at each version. The upcoming Java 8 will use invokedynamic to support lambda functions, so it is very likely that newer JVMs will offer even greater optimization. Given the current state of things, some benchmarks that we have run have shown an improvement of around 20 percent when given the same code compiled with the invokedynamic instruction enabled.
In this recipe, we introduce a procedure for building Groovy from the source code. The only requirement needed to build Groovy from source is Java JDK 1.7 or higher.
Java 7 is required to leverage the new invokedynamic instruction used by Groovy 2. You can read more about the benefits of invokedynamic in the Running Groovy with invokedynamic support recipe.
Like many of today's open source projects, Groovy source is maintained on GitHub. GitHub is a website that provides a Git hosting service. You have probably heard of Git, the version control system started by the Linux creator, Linus Torvalds.
In order to build Groovy, you need a local copy of the source code that must be fetched from GitHub via Git. If you are running a Linux or OS X operating system, chances are that you already have Git installed on your box.
For Windows, there are several ways to install Git. You may want to use Cygwin (http://www.cygwin.com/) or the officially released version available on the Git website (http://git-scm.com/download/win).
For this recipe, we assume that a recent version of Git is available in your shell. To test that Git is indeed available, open a shell and type the following command:
Assuming that git is installed and operational, we can proceed with the following steps to build Groovy from source:
On Linux or Mac OS X, open a shell, move to the groovy-core folder, and type:
The git clone command in the first step fetches the Groovy repository, around 125 MB, so be patient if you are on a slow connection. Groovy has switched to the Gradle build tool from Ant. The gradlew command is a convenient wrapper for Gradle that takes care of downloading all the required dependencies and triggering the build. Chapter 2, Using Groovy Ecosystem, has a whole recipe dedicated to Gradle, so you may want to take a look at the Integrating Groovy into the build process using Gradle recipe to know more about this awesome tool. Furthermore, several recipes in this book will make use of Gradle to build the code examples.
The build process will download the required dependencies and compile the code. Upon successful compilation, the build will generate a ZIP file named groovy-binary-2.x.x-SNAPSHOT.zip that contains the binaries, under /target/distributions. Install the binaries in the same way as explained in the Installing Groovy on Windows and Installing Groovy on Linux and OS X recipes.
Note how two types of Groovy binaries are generated: a normal version and an indy version. The indy version will leverage the invokedynamic feature (see also the Running Groovy with invokedynamic support recipe).
If a developer needs to work with different Groovy distributions on the same machine, chances are that he or she would be involved in a lot of environment variable fiddling, such as PATH, JAVA_HOME, and GROOVY_HOME.
Luckily, there is a tool that helps to manage those variables as well as to download the required setup files on demand.
The name of this goody is GVM (Groovy enVironment Manager). GVM was inspired by similar tools from the Ruby ecosystem, RVM, and rbenv.
In this recipe, we will demonstrate how to use the GVM tool and show the benefits it delivers.
Use the package manager available on your Linux distribution to install curl, unzip, and java on your machine. For example, on Ubuntu it can be achieved with the following command sequence:
The GVM installation script will not work without those packages. You can skip the OpenJDK package in case you have Java 5 or later distribution already installed.
Then you need to fetch the installation script from GVM's website (http://get.gvmtool.net) and pass it to bash using the following command:
It will start the set up process as shown in the following screenshot:
To finalize the installation, open a new terminal and run the following command:
As soon as GVM is installed and running, you can start putting it to use:
The reason the directorySize() method (steps 9 and 10) didn't work for v1.8.6 of Groovy is simply because this method was only introduced in v2.
