- •Credits
- •About the Authors
- •About the Reviewers
- •www.PacktPub.com
- •Table of Contents
- •Preface
- •Introduction
- •Installing Groovy on Windows
- •Installing Groovy on Linux and OS X
- •Executing Groovy code from the command line
- •Using Groovy as a command-line text file editor
- •Running Groovy with invokedynamic support
- •Building Groovy from source
- •Managing multiple Groovy installations on Linux
- •Using groovysh to try out Groovy commands
- •Starting groovyConsole to execute Groovy snippets
- •Configuring Groovy in Eclipse
- •Configuring Groovy in IntelliJ IDEA
- •Introduction
- •Using Java classes from Groovy
- •Embedding Groovy into Java
- •Compiling Groovy code
- •Generating documentation for Groovy code
- •Introduction
- •Searching strings with regular expressions
- •Writing less verbose Java Beans with Groovy Beans
- •Inheriting constructors in Groovy classes
- •Defining code as data in Groovy
- •Defining data structures as code in Groovy
- •Implementing multiple inheritance in Groovy
- •Defining type-checking rules for dynamic code
- •Adding automatic logging to Groovy classes
- •Introduction
- •Reading from a file
- •Reading a text file line by line
- •Processing every word in a text file
- •Writing to a file
- •Replacing tabs with spaces in a text file
- •Deleting a file or directory
- •Walking through a directory recursively
- •Searching for files
- •Changing file attributes on Windows
- •Reading data from a ZIP file
- •Reading an Excel file
- •Extracting data from a PDF
- •Introduction
- •Reading XML using XmlSlurper
- •Reading XML using XmlParser
- •Reading XML content with namespaces
- •Searching in XML with GPath
- •Searching in XML with XPath
- •Constructing XML content
- •Modifying XML content
- •Sorting XML nodes
- •Serializing Groovy Beans to XML
- •Introduction
- •Parsing JSON messages with JsonSlurper
- •Constructing JSON messages with JsonBuilder
- •Modifying JSON messages
- •Validating JSON messages
- •Converting JSON message to XML
- •Converting JSON message to Groovy Bean
- •Using JSON to configure your scripts
- •Introduction
- •Creating a database table
- •Connecting to an SQL database
- •Modifying data in an SQL database
- •Calling a stored procedure
- •Reading BLOB/CLOB from a database
- •Building a simple ORM framework
- •Using Groovy to access Redis
- •Using Groovy to access MongoDB
- •Using Groovy to access Apache Cassandra
- •Introduction
- •Downloading content from the Internet
- •Executing an HTTP GET request
- •Executing an HTTP POST request
- •Constructing and modifying complex URLs
- •Issuing a REST request and parsing a response
- •Issuing a SOAP request and parsing a response
- •Consuming RSS and Atom feeds
- •Using basic authentication for web service security
- •Using OAuth for web service security
- •Introduction
- •Querying methods and properties
- •Dynamically extending classes with new methods
- •Overriding methods dynamically
- •Adding performance logging to methods
- •Adding transparent imports to a script
- •DSL for executing commands over SSH
- •DSL for generating reports from logfiles
- •Introduction
- •Processing collections concurrently
- •Downloading files concurrently
- •Splitting a large task into smaller parallel jobs
- •Running tasks in parallel and asynchronously
- •Using actors to build message-based concurrency
- •Using STM to atomically update fields
- •Using dataflow variables for lazy evaluation
- •Index
Preface
Groovy 2 Cookbook consists of problem-solving recipes for Groovy, one of the most flexible programming languages we have ever used. This 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:
ff
ff
ff
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 in 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.
This 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 (JVM), 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 an 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.
www.it-ebooks.info
Preface
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 such as Python, Ruby, and
Smalltalk, making them available to Java developers using a Java-such as 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, and 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 such as mining data from a PDF file or an
Excel spreadsheet.
Chapter 5, Working with XML in Groovy, introduces you to the 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.
2
www.it-ebooks.info
Preface
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 v2.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, and 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."
3
www.it-ebooks.info
Preface
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 like this: "Click on the Advanced system settings to open the System Properties window".
Warnings or important notes appear in a box like this.
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 liked or may have disliked. 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 feedback@packtpub.com, 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.
4
www.it-ebooks.info
Preface
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 copyright@packtpub.com 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 questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it.
5
www.it-ebooks.info
www.it-ebooks.info