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

Working with Web Services in Groovy
The code yields the following output:
> http://docs.codehaus.org/pages/editpage.action?spaceKey=GROOVY&title=Pr oject+Information
The code snippet that transforms a Map into a query uses the collect method of the Map. It iterates through the Map entries and executes a simple transformation closure returning a List. The closure simply encodes each parameter value using the java.net.URLEncoder class and adds the = sign between a parameter name and its content. Finally, the join method is applied to the resulting collection to concatenate all entries into a single string using & symbol.
See also
ff Downloading content from the Internet
ff Constructing and modifying complex URLs ff Executing an HTTP POST request
ff http://docs.oracle.com/javase/6/docs/api/java/net/ URLConnection.html
ff http://docs.oracle.com/javase/6/docs/api/java/net/URLEncoder. html
Executing an HTTP POST request
In this recipe, we demonstrate how to POST data to a remote HTTP server using Groovy. The
POST request method is often used to upload a file or submit a web form to a server. This method sits at the opposite end of the spectrum of the HTTP GET method, used to retrieve information from the server.
How to do it...
The code required to execute a POST request with Groovy is fairly similar to the one discussed in the previous recipe, Executing an HTTP GET request, except that it's more convoluted:
1.The sending of a POST request is expressed in the following way:
def baseUrl = new URL('http://api.duckduckgo.com') def queryString = 'q=groovy&format=json&pretty=1' def connection = baseUrl.openConnection() connection.with {
doOutput = true requestMethod = 'POST'
268
www.it-ebooks.info

Chapter 8
outputStream.withWriter { writer -> writer << queryString
}
println content.text
}
2.The printed results will look similar to the following code snippet:
{
"Definition" :
"groovy definition: marvelous, wonderful, excellent.", "DefinitionSource" : "Merriam-Webster",
"Heading" : "Groovy", "AbstractSource" : "Wikipedia", "Image" : "",
"RelatedTopics" : [
...
]
...
}
How it works...
The first few lines of the script open a connection to an API provided by the DuckDuckGo search engine, which is an alternative privacy-oriented search service.
To reduce code verbosity we use Groovy's with method, which basically allows us to suppress references to the connection variable and call its methods and properties directly within a closure passed to the Groovy's with method.
Before making a request, we set several connection properties such as requestMethod to indicate that we actually want to fire a POST request. Finally, the code creates a writer object to append to the stream containing the data that will be posted to the remote connection.
The response is read by using the text property of the InputStream method returned by the content property (see the Executing an HTTP GET request recipe).
There's more...
Another way to POST data to a web server is to use the HTTPBuilder third-party library
(http://groovy.codehaus.org/modules/http-builder/doc/index.html). The project is discussed in more details in the Issuing a REST request and parsing a response recipe.
269
www.it-ebooks.info

Working with Web Services in Groovy
As we are working with an external dependency, we use Grape to fetch the
HTTPBuilder library:
@Grab( group='org.codehaus.groovy.modules.http-builder', module='http-builder',
version='0.6'
)
import groovyx.net.http.*
def baseUrl = 'http://api.duckduckgo.com'
def queryString = 'q=groovy&format=json&pretty=1' def http = new HTTPBuilder(baseUrl) http.request(Method.POST) {
send ContentType.URLENC, queryString response.success = { response, reader ->
println response.statusLine println reader.text
}
response.failure = { response -> println response.statusLine
}
}
The result of the posted data is handled in the response.success closure. We also handle failures (for example, 404 or 500 status codes) in the failure closure. The response variable holds the response metadata such as the status code and the headers. The reader
object is used to get access to the remote data stream. Since the reader implements a java.io.Reader interface, we can use the text property provided by Groovy to fully-fetch response content and print it to the standard output.
See also
ff http://groovy.codehaus.org/modules/http-builder
ff The Simplifying dependency management with Grape recipe in Chapter 2, Using Groovy Ecosystem
ff ff
Constructing and modifying complex URLs Executing an HTTP GET request
270
www.it-ebooks.info

Chapter 8
Constructing and modifying complex URLs
At the heart of any HTTP request, there is a Universal Resource Locator (URL) or a more generic Universal Resource Identifier (URI) which identifies the target of the operation we need to perform.
We have seen in the previous recipes (for example, the Downloading content from the Internet recipe) that it's very hard to avoid dealing with URLs when interacting with the HTTP protocol. In this recipe, we are going to present a more structured approach to constructing and modifying complex URLs with the help of an additional Groovy library.
How to do it...
If you have worked with Java's URL class before, you know that the only way to construct instances of that class is to provide a full URL to the constructor, which will return an immutable (non-changeable) object.
Groovy's core does not add any special support for URL manipulation apart from what Java already offers, but there is an officially supported HttpBuilder module that is hosted on Groovy's website (http://groovy.codehaus.org/modules/http-builder) and that can be used to make more accessible URL creation and modification:
1.First of all, we need to @Grab that module and import the URIBuilder class, which will help us with our task:
@Grab( group='org.codehaus.groovy.modules.http-builder', module='http-builder',
version='0.6'
)
import groovyx.net.http.URIBuilder
2.At this point, we can create a URIBuilder instance and pass baseUri to that:
def baseUri = 'http://groovy.services.com/service1/operation2'
def uri = new URIBuilder(baseUri)
3.Now, we can modify any URI's component with simple property assignments, as follows:
uri.with {
scheme = 'https' host = 'localhost' port = 8080
271
www.it-ebooks.info