Book Image

Groovy 2 Cookbook

Book Image

Groovy 2 Cookbook

Overview of this book

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.
Table of Contents (17 chapters)
Groovy 2 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

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:

  • As a cookbook, it's intended to save your time by providing solutions to the most common problems you'll encounter.

  • Most of the examples can be run as Groovy scripts or directly in the GroovyConsole. As a result, whether you're sitting by a computer or n a plane, you get the benefit of seeing their exact output.

  • 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.

Th book covers Groovy 2.0 and 2.1.

The Groovy language

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.

What this book covers

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.

What you need for this book

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.

Who this book is for

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.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "It also ensures that the reader object gets closed after the method returns."

A block of code is set as follows:

class Person {
  String name
  String lastName
}

p = new Person()

Any command-line input or output is written as follows:

groovy -e "throw new Exception()"
Caught: java.lang.Exception
java.lang.Exception
        at script_from_command_line.run(script_from_command_line:1)

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text this: "Click on the Advanced system settings to open the System Properties window".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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 , 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.

Customer support

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.

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.

Errata

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 errata submission form 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

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 with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.