- •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
2
Using Groovy
Ecosystem
In this chapter, we will cover:
ff
ff
ff
ff
ff
ff
ff
ff
ff
Using Java classes from Groovy Embedding Groovy into Java Compiling Groovy code
Simplifying dependency management with Grape Integrating Groovy into the build process using Ant Integrating Groovy into the build process using Maven Integrating Groovy into the build process using Gradle Generating documentation for Groovy code
Checking Groovy code's quality with CodeNarc
Introduction
In this chapter, we will introduce the Groovy ecosystem: compilation, embedding, building, documentation, and analysis options that various, tools surrounding, Groovy offer to make your life smoother.
In the first three recipes, we will demonstrate how simple Java and Groovy interoperability is and what makes Groovy the perfect tool in a Java developer's hands. The following recipes will describe external dependency management possibilities and the most popular build tools (for example, Ant, Maven, and Gradle) integration options. Then there will be a recipe devoted to Groovydoc, which can be used to generate documentation for your sources. Finally, the last recipe will introduce a way to verify your Groovy code quality.
www.it-ebooks.info
Using Groovy Ecosystem
Using Java classes from Groovy
The Groovy language is designed in a way that it fully supports the Java syntax (there are only few minor exceptions; for example, do..while is not supported in Groovy). Most of the code that you can write in Java can automatically be considered Groovy code as well.
In this recipe, we will learn how simple it is to use existing Java classes and libraries from your Groovy code and we will explore some basic language features that makes Groovy—groovy!
How to do it...
This recipe has a rather simple setup. You can either start up the groovyConsole, as described in the Starting groovyConsole to execute Groovy snippets recipe in Chapter 1,
Getting Started with Groovy, or you can create a new file with the *.groovy extension.
1.In the groovyConsole type the following code:
import java.io.File;
File currentDir = new File("."); System.out.println("Current directory: " +
currentDir.getAbsolutePath()); File[] files = currentDir.listFiles();
for (File file: files) { System.out.println(file.getName());
}
2.Run the script to see the list of files found in the folder from where the groovyConsole was launched.
How it works...
The Groovy script from the previous section first prints the absolute path of the current directory and then the names of all the files contained in it by using the java.io.File API.
Since Groovy supports the Java syntax, you can import any class from the Java JDK in the same way you would do it in Java code.
As you can see, the code after the import statement can perfectly serve as a body of some Java method, but it is still Groovy code. On the other hand, we are still using the Java API directly.
There are several ways in which we can improve the previous script by using idiomatic Groovy syntax and without removing the java.io.File dependency.
48
www.it-ebooks.info
Chapter 2
First of all, Groovy automatically imports many classes from the Java JDK and the Groovy GDK into the scope of the script or class. The following packages do not need to be explicitly imported in Groovy, and you simply can refer to their classes:
ff java.io.* ff java.lang.*
ff java.math.BigDecimal ff java.math.BigInteger ff java.net.*
ff java.util.* ff groovy.lang.* ff groovy.util.*
For this reason, we can omit the import statements from the example script. We still need to import a class which is not located in one of the packages previously listed.
As we discussed in Chapter 1, Getting Started with Groovy, the Script class, an instance of which is created for each Groovy script, exposes the println method; this is why all calls to
System.out.println can be shortened to just println.
Another Groovy feature that can be applied to any imported class is the short notation for calling setters and getters. It allows you to write file.name instead of file.getName and
file.name = "poem.txt" instead of file.setName('poem.txt'). This feature greatly simplifies working with Java Beans and makes code much more readable (see also the Writing less verbose Java Beans with Groovy Beans recipe in Chapter 3, Using Groovy Language Features).
Famously, Groovy doesn't require a semicolon (;) at the end of a statement, if the statement is the only one in the line. We can happily omit semicolons from our script.
One more facet we can resort to in order to groovify our script is interpolation. Groovy simplifies string concatenation with the help of the ${ } operator, that is replaced with the value of the expression that appears inside it. If the expression is a simple reference to a variable or a dot expression (like in our case), then we can omit the curly brackets ({ }) and just write $currentDir.absolutePath. Or, for example, we can do the following:
def name = 'John'
println "My name is $name"
The previous code obviously yields the following:
My name is John
49
www.it-ebooks.info
Using Groovy Ecosystem
It is worth knowing that strings containing expression are actually GString in Groovy and not normal java.lang.String. String interpolation is only done for strings enclosed in double quotes ("). If you want to avoid string interpolation, then you can use single quotes (') or escape the dollar sign; that is, \$:
def price = 8
println "Item price: \$${price}"
The previous code snippet will print:
Item price: $8
Thanks to the dynamic nature of the language, we can also omit specifying the variable type in the variable declaration. We can just use the def keyword instead.
Taking all the previous notes into account, the code can be shortened to:
def currentDir = new File('.')
println "Current directory ${currentDir.absolutePath}" def files = currentDir.listFiles()
for (def file: files) { println file.name
}
There are a few other features of Groovy that can help to make this script even more concise such as closures and metaclass facilities, but those will be discussed in more detail in
Chapter 3, Using Groovy Language Features.
Under the hood (either for dynamic scripts or Groovy classes compiled through groovyc), Groovy code is always compiled into Java bytecode. Every direct call to an imported Java class would act in the exact same way as it would if it were a Java code.
There's more...
For many standard JDK classes, Groovy provides API extensions. For example, instances of the java.io.File class have methods such as append or getText:
def textFile = new File('poem.txt') textFile.append('What\'s in a name? ') textFile.append('That which we call a rose\n') textFile.append('By any other name would smell as sweet.\n') println textFile.text
50
www.it-ebooks.info