- •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
Using Groovy Language Features
If the Sample class is annotated with @TypeChecked, the compiler will return:
[Static type checking] -
Cannot find matching method java.lang.Object#toUpperCase(). Please check if the declared type is right
and if the method exists. @ line 77, column 44.
wo','three'].collect { println it.toUpper
^
What is happening here? Simply, the compiler has no idea of the type of the implicit variable it, which is often used inside closures to make the code even more terse. This compilation error can be solved by explicitly declaring the closure variable as follows:
['one','two','three'].collect {
myString -> println myString.toUpperCase()
}
Adding automatic logging to Groovy classes
In the Writing less verbose Java Beans with Groovy Beans, Adding the cloning functionality to Groovy Beans, and Inheriting constructors in Groovy classes recipes, we met some of the
annotation-based AST transformations available in Groovy. An AST transformation is a process in which a programmer is able to hook into the bytecode generation process and influence the final shape of the resulting bytecode. Groovy ships with many useful transformations and in this recipe, we are going to look at the family of logging annotations.
How to do it...
The transformation we are going to demonstrate is the @groovy.util.logging.Log annotation that injects java.util.logging.Logger into a Groovy class:
1.Let's apply the annotation to a Groovy class:
@groovy.util.logging.Log class UserService {
def createUser(String username, String password) { log.info("creating user with name ${username}")
}
}
2.And call the method of the new class:
def userService = new UserService() userService.createUser('john', 'secret')
132
www.it-ebooks.info
Chapter 3
3.The output will be:
INFO: creating user with name john
How it works...
The annotation takes a number of steps. First, it creates a logger with the variable name log and injects it in the class as a static final variable. Then it surrounds every call to the logger with a conditional check to verify whether the log level is enabled. No need to pollute your code with hard-to-read if statements just to check whether the log statement should
be evaluated.
The variable that holds the logger can be modified by using an attribute on the annotation:
@groovy.util.logging.Log('someLogger') class UserService { ... }
There's more...
The logging transformation is not limited to use only one logging framework but it also allows to use the following logging facilities by changing the annotation class:
ff @groovy.util.logging.Commons: It injects an Apache Commons logger and initializes it using LogFactory.getLog(class).
ff @groovy.util.logging.Log4j: It injects Log4J org.apache.log4j.Logger into the class and initializes it using Logger.getLogger(class).
ff @groovy.util.logging.Slf4j: It injects a Slf4J logger into the annotated class and initializes it using org.slf4j.LoggerFactory.getLogger(class). Slf4J is the underlying logger used by the newer framework Logback. If you wish to use that framework you should use the @Slf4j annotation.
See also
ff http://groovy.codehaus.org/api/groovy/util/logging/Log.html
ff http://docs.oracle.com/javase/7/docs/api/java/util/logging/ Logger.html
ff http://commons.apache.org/proper/commons-logging/ ff http://logging.apache.org/log4j
ff http://www.slf4j.org/
133
www.it-ebooks.info
www.it-ebooks.info
4
Working with Files in Groovy
In this chapter, we will cover:
ff ff ff ff ff ff ff ff ff ff ff ff ff
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 Filtering a text file's content
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
www.it-ebooks.info