- •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
Chapter 4
Also pay your attention to the following Groovydoc references:
ff http://groovy.codehaus.org/groovy-jdk/java/io/File.html
ff http://groovy.codehaus.org/api/groovy/io/FileType.html
ff http://groovy.codehaus.org/api/groovy/io/FileVisitResult.html
Changing file attributes on Windows
Groovy is widely used as a scripting language for automating repetitive tasks. While working with files, it occurs sometime that one has to change the attributes of a file in Windows. For example, you may need to set the file as read-only, archived, and so on.
In this recipe, we will learn how to change file attributes in Windows using Groovy.
Getting ready
Let's start by creating a file and adding some content to it. Open your shell, start groovysh and type the following code:
f = new File('test.txt')
f << 'hello, this is a test file'
You should now see a file named test.txt in the same directory where you started groovysh.
On a DOS console, type:
attrib test.txt
The output should be as follows:
A |
I |
C:\hello.txt |
The initial on the left stands for the first letter of the enabled attribute: A for "archive", S for "system", H for "hidden" and R for "read-only".
How to do it...
With the exclusion of the read-only attribute; in Java, there is no way to set the Windows file attributes through the File API. To make a file read-only:
f.setReadOnly()
157
www.it-ebooks.info
Working with Files in Groovy
This will change the R attribute:
attrib test.txt
AR I C:\hello.txt
1.In order to change other file attributes, we have to resort to executing an external process with Groovy, using the execute method of String. The external process is the attrib DOS command that can be used to set and read file attributes.
2.To make a file "Hidden":
'attrib +H C:/hello.txt'.execute()
3.And to remove the "Hidden" attribute:
'attrib -H C:/hello.txt'.execute()
4.You can use the same approach for the other file attributes, S and A.
How it works...
Groovy provides a simple way to execute command line processes. Simply write the command line as a string and call the execute method. The execute method returns a java.lang. Process instance, which will subsequently allow the in/err/outstreams to be processed and the exit value from the process to be inspected.
This snippet executed from groovish will output the directory listing on a UNIX machine:
println 'ls -al'.execute().text
Alternatively, we can access the stream resulting from the process and print the result line-by-line:
p = 'ls -al'.execute().text p.in.eachLine { line -> print line }
There's more...
If you run Groovy using JDK 7, you can leverage the new NIO API to set the Windows file attributes. The following example shows you how to do it:
import java.nio.file.*
import java.nio.file.attribute.* def f = new File('hello.txt')
f << 'hello, hello'
def path = Paths.get('C:\\groovybook\\hello.txt') def dosView = Files.getFileAttributeView(
path, DosFileAttributeView
)
158
www.it-ebooks.info
Chapter 4
dosView.hidden = true dosView.archive = true dosView.system = true
This code will fail if it is executed in an environment other than Windows.
Reading data from a ZIP file
Reading from a ZIP file with Groovy is a simple affair. This recipe shows you how to read the contents of a ZIP file without having to extract the content first.
Getting ready
Groovy doesn't have any GDK class to deal with ZIP files so we have to approach the problem by using one of the JDK alternatives. Nevertheless, we can "groovify" the code quite a lot in order to achieve simplicity and elegance.
How to do it...
Let's assume we have a ZIP file named archive.zip containing a bunch of text files.
1.The following code iterates through the ZIP entries and prints the name of the file as well as the content:
def dumpZipContent(File zipFIle) {
def zf = new java.util.zip.ZipFile(zipFIle) zf.entries().findAll { !it.directory }.each {
println it.name
println zf.getInputStream(it).text
}
}
dumpZipContent(new File('archive.zip'))
2.The output may look as follows:
a/b.txt
This is text file! c/d.txt
This is another text file!
159
www.it-ebooks.info
Working with Files in Groovy
How it works...
The dumpZipContent function takes a File as an argument and creates a JDK ZipFIle out of it. Finally, the code iterates on all the entries of the ZIP file, filtering out the folders. The iteration is done through a couple of nested closures, the second of which prints the content of the ZIP file using the handy text property added to the Java's InputStream class by Groovy JDK.
There's more...
We have already encountered the AntBuilder class in the Deleting a file or directory recipe. This class is a gateway to the enormous amount of tasks exposed by the Ant build system.
Among them, we can find the unzip task that allows us to decompress a ZIP, JAR, WAR, and EAR file:
def ant = new AntBuilder()
ant.unzip (src: 'zipped.zip', dest: '.')
The previous snippet unzips a file named zipped.zip into the same folder where the code is executed. For a complete list of properties of the unzip task, refer to Ant documentation
(https://ant.apache.org/manual/Tasks/unzip.html).
See also
ff http://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipFile. html
ff https://ant.apache.org/manual/Tasks/unzip.html
Reading an Excel file
In this recipe, you will learn how to read and extract data from an Excel file. If you are a
Windows or Mac user, changes are that you have worked in some capacity with Microsoft Excel, the de facto standard for spreadsheets. Excel files are often the default data interchange format of the enterprise. Entire departments are run using incredibly complex
Excel files with thousands of rows and absurdly convoluted formulas. As a programmer, it is often the case that you are asked to interact with such files.
160
www.it-ebooks.info
Chapter 4
Getting ready
Groovy (and Java) does not offer any out-of-the-box ingredient to manipulate Excel files.
Fortunately, there is no shortage of third-party libraries that are able to deal with Microsoft documents. The undisputed king of this realm is Apache POI, the Java API for Microsoft documents. With Apache POI, it is possible to parse as well as write Excel 2007 OOXML documents (.xlsx) and older formats (.xls).
How to do it...
Let's start with a simple Excel file with only a few columns:
1.The script that follows, extracts the content of the Excel file depicted in the previous screenshot and prints it on the console:
@Grab('org.apache.poi:poi:3.8') @Grab('org.apache.poi:poi-ooxml:3.8') @GrabExclude('xml-apis:xml-apis')
import org.apache.poi.xssf.usermodel.XSSFWorkbook import org.apache.poi.xssf.usermodel.XSSFSheet def excelFile = new File('Workbook1.xlsx') excelFile.withInputStream { is ->
workbook = new XSSFWorkbook(is) (0..<workbook.numberOfSheets).each { sheetNumber ->
XSSFSheet sheet = workbook.getSheetAt( sheetNumber ) sheet.rowIterator().each { row ->
row.cellIterator().each { cell -> println cell.toString()
}
}
}
}
161
www.it-ebooks.info