Book Image

Groovy 2 Cookbook

Book Image

Groovy 2 Cookbook

Overview of this book

Get up to speed with Groovy, a language for the Java Virtual Machine (JVM) that integrates features of both object-oriented and functional programming. This book will show you the powerful features of Groovy 2 applied to real-world scenarios and how the dynamic nature of the language makes it very simple to tackle problems that would otherwise require hours or days of research and implementation. Groovy 2 Cookbook contains a vast number of recipes covering many facets of today's programming landscape. From language-specific topics such as closures and metaprogramming, to more advanced applications of Groovy flexibility such as DSL and testing techniques, this book gives you quick solutions to everyday problems. The recipes in this book start from the basics of installing Groovy and running your first scripts and continue with progressively more advanced examples that will help you to take advantage of the language's amazing features. Packed with hundreds of tried-and-true Groovy recipes, Groovy 2 Cookbook includes code segments covering many specialized APIs to work with files and collections, manipulate XML, work with REST services and JSON, create asynchronous tasks, and more. But Groovy does more than just ease traditional Java development: it brings modern programming features to the Java platform like closures, duck-typing, and metaprogramming. In this new book, you'll find code examples that you can use in your projects right away along with a discussion about how and why the solution works. Focusing on what's useful and tricky, Groovy 2 Cookbook offers a wealth of useful code for all Java and Groovy programmers, not just advanced practitioners.
Table of Contents (17 chapters)
Groovy 2 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Using groovysh to try out Groovy commands


Similar to many other languages (for example, Ruby or Perl), Groovy sports a so called Read - Evaluate - Print loop (REPL). REPL is a simple, interactive programming environment mostly used to quickly try out language features. Groovy's REPL is named groovysh, and in this recipe we are going to explore some of its features.

How to do it...

The groovysh command is a command-line tool available with the standard Groovy distribution. Install Groovy as described in one of the installation recipes (see the Installing Groovy on Windows recipe and Installing Groovy on Linux and OS X recipe) and you'll get the groovysh command available in your shell:

  1. Open a shell on your operating system and type groovysh, as shown in the following screenshot:

  2. The Groovy shell allows you to evaluate simple expressions, such as:

    groovy:000> println "Hello World!"
    Hello World
    ===> null
    
  3. It is also possible to evaluate more complex expressions such as functions or closures, (closures are discussed in great length in the Defining code as data in Groovy recipe in Chapter 3, Using Groovy Language Features):

    groovy:000> helloClosure = { println ""Hello $it"" }
    ===> groovysh_evaluate$_run_closure1@7301061
    groovy:000> counter = 1..5
    ===> 1..5
    groovy:000> counter.each helloClosure
    Hello 1
    Hello 2
    Hello 3
    Hello 4
    Hello 5
    ===> 1..5
    
  4. The Groovy shell also supports creating classes:

    groovy:000> class Vehicle {
    groovy:001> String brand
    groovy:002> String type
    groovy:003> String engineType
    groovy:004> }
    ===> true
    groovy:000> v = new Vehicle()
    ===> Vehicle@7639fabd
    groovy:000> v.brand = 'Ferrari'
    ===> Ferrari
    groovy:000> v.type = 'Car'
    ===> Car
    ===> null
    groovy:000> println v.brand
    Ferrari
    ===> null
    
  5. The dynamic nature of Groovy allows us to quickly list all the methods on a class:

    groovy:000> GString.methods.each { println it}
    public java.util.regex.Pattern groovy.lang.GString.negate()
    public boolean groovy.lang.GString.equals(java.lang.Object)
    public boolean groovy.lang.GString.equals(groovy.lang.GString)
    public java.lang.String groovy.lang.GString.toString()
    public int groovy.lang.GString.hashCode()
    

How it works...

The groovysh command compiles and executes completed statements as soon as we press the Enter key. It then prints the result of that statement execution along with any output from the execution.

Autocompletion is supported through the JLine library that can be found at http://jline.sourceforge.net/. Pressing the Tab key automatically completes keywords and methods as we type:

groovy:000> string = "I'm a String!"
===> I'm a String!
groovy:000> string.
Display all 159 possibilities? (y or n)
groovy:000> string.toU

toURI()         toURL()         toUpperCase(    toUpperCase()

In step 2, the evaluated statement returned null. This is normal as groovysh is informing us that the last statement didn't return any value—hence null.

In step 4, we can see how groovysh supports code that spawns multiple lines. Note how the counter on the left of each statement increases at each line. The up and down arrows key will display the history of the typed commands. The history is preserved even across sessions so you can safely exit groovysh and you will still be able to access the history.

You may have noticed that in the previous examples, we didn't use any typed variables.A variable declared with def or a data type is not stored in the session and will be lost as soon as the command is issued:

groovy:000> def name = "Oscar"
===> Oscar
groovy:000> println name
ERROR groovy.lang.MissingPropertyException:
No such property: name for class: groovysh_evaluate
      at groovysh_evaluate.run (groovysh_evaluate:2)

This is a small gotcha you should remember when using groovysh.

There's more...

groovysh has a number of commands, which can be listed by typing help as shown in the following screenshot:

The import behaves like the standard import keyword in Groovy and Java. It allows to import packages from the JDK or the GDK:

groovy:000> import groovy.swing.SwingBuilder
===> [import groovy.swing.SwingBuilder]
groovy:000> swing = new SwingBuilder()
===> groovy.swing.SwingBuilder@6df59ac1
groovy:000> frame = swing.frame(title:'Frame') {
groovy:000>   textlabel = label(text:'hello world!')
groovy:000> }
===> javax.swing.JFrame[...]
groovy:000> frame.show()
===> null

The display command shows the current buffer and save allows to save it to a file:

groovy:000> display
Buffer is empty
groovy:000> class Person {
groovy:001> display

With clear, the buffer can be reset, in case you mistyped something.

The record command acts as a flying recorder. It saves the typed commands to a file as we type. Use record start and record stop to control the recording. It is preferable to specify a file to which you want the recorded commands to be stored:

groovy:000> record start Session1.txt
Recording session to: Session1.txt
===> Session1.txt
groovy:000> println 'hello world!'
hello world!
===> null
groovy:000> class Person {
groovy:001> String name
groovy:002> }
===> true
groovy:000> record stop
Recording stopped; session saved as: Session1.txt (202 bytes)
===> Session1.txt

A very useful feature of the Groovy shell is the inspect command that displays the content of the last evaluated expression inside a GUI application, named Groovy Object Browser.

The Groovy Object Browser shows a good deal of information about the latest stored object, such as the class name, the implemented interfaces, and all the methods exposed by the object. The following screenshot shows some of the methods visible in the java.lang.String class:

groovy:000> name = "Oscar"
===> Oscar
inspect