This article is not up to date and it has been substitute with new up to date content.

Please look the new up to date content.

Getting started with Groovy

4,729 views Published on Oct 24, 2011
Applies to: All versions
Table of contents

Getting Started

The aim of this article is to get you started with Groovy, a simple yet powerful Java-based language, used in WebRatio in the Layout Templates and in the Script Unit. Being Java-based, Groovy integrates with all existing Java objects and libraries. This means that in your Script units or layout you can use every Java libraries (http://groovy.codehaus.org/).

Hello World!

Groovy provides a simple way to print messages in Java console, our Hello World application is composed of just a command


 println "Hello World!"

the effect is the same as:


 System.out.println("Hello World!") 

in a Java program.

Variables

Groovy supports dynamic typing, the following is a correct Groovy program:


 def x //defines a variable x

 x = 1 

 println x //prints 1

   

 x = new java.util.Date()

 println x //prints the current date

  

 x = -3.1499392

 println x //prints -3.1499392

  

 x = false

 println x //prints false 

  

 x = "Hi"

 println x //prints Hi

Lists and Maps

The Groovy language has built-in support for two important data types, lists and maps (Lists can be operated as arrays in Java language). Lists are used to store ordered collections of data.


 myList = [1776, -1, 33, 99, 0, 928734928763] // a list of integers

 

 scores = [ "Brett":100, "Pete":"Did not finish", "Andrew":86.87 ] //a map of names and scores

  

 println scores.size() //prints 3

 println scores["Pete"] //access to the value assigned to the key "Pete". Prints Did not finish

 println scores.Pete //access to the value assigned to the key "Pete". Prints Did not finish

 

 scores["Pete"] = 3 //assign the value 3 to the map's key "Pete"

  

 emptyMap = [:] //declares an empy map

 emptyList = [] //declares an empty list

  

 println emptyMap.size() //prints 0

 println emptyList.size() //prints 0

Note that each of the values stored in the map is of a different type: Brett's is an integer, Pete's is a string, and Andrew's is a floating point number. We can access the values in a map in either the two ways shown above. To add data to a map, the syntax is similar to adding values to a list.

Conditional Execution

One of the most important features of any programming language is the ability to execute different code under different conditions. The simplest way to do this is to use the "if" construct.


 amPM = Calendar.getInstance().get(Calendar.AM_PM) //determines if it's before or after noon

 if (amPM == Calendar.AM) //checks if is before noon

 {

   println("Good morning") //prints Good morning

 } else { //if is not before noon

   println("Good evening") //prints Good evening

 }

This example determines whether it's morning or afternoon (using the java.util.Calendar library) and prints the appropriate sentence (using the "if" construct). As shown, the "if" construct works as follows: first it evaluates the expression in the parentheses, then depending on whether the result is true or false it executes the first or the second code block. Note that the "else" block is not required, but the "then" block is

Boolean Expressions

There is a special data type in most programming languages that is used to represent truth values, "true" and "false". Boolean values can be stored in variables, just like any other data type and are used to evaluate conditions, with boolean operators.


 def booleanValue = true

 12346 == 219 // evaluates to false

 12346 > 219 // evaulates to true

 "James Cameron" != "Peter Jackson" // evaluates to true

 "James Cameron" > "Peter Jackson" // evaluates to false, because "J" is before "P"

 3 + 5 <= 2 * 5 // evaulates to true

Closures

One of the things that makes Groovy different than most compiled languages is that you can create functions that are first class objects. That is you can define a chunk of code and then pass it around as if it were a string or an integer.


 square = { it * it }

 def newValue = square(9) // use the variable "square" as a function. Here we get 81 in newValue variable

The curly braces around the expression "it * it" tells the Groovy compiler to treat this expression as code. In the software world, this is called a "closure". In this case, the designator "it" refers to whatever value is given to the function. Then this compiled function is assigned to the variable "square" much like those above. The true power of closures is that it's possible to pass them as values. There are some built in functions that take a function like this as an argument. One example is the "collect" method on arrays:


 [ 1, 2, 3, 4 ].collect(square) //returns [ 1, 4, 9, 16 ]

This expression creates an array with the values 1,2,3 and 4 and calls the "collect" method, passing in the closure we defined above. The collect method runs through each item in the array, calls the closure on the item, then puts the result in a new array. By default closures take 1 parameter called "it", you can also create closures with named parameters. For example the method Map.each() can take a closure with two variables, to which it binds the key and associated value:


 printMapClosure = { key, value -> println key + "=" + value } 

 //defines a closure with two variables

 [ "yue" : "wu", "lane" : "burks", "sudha" : "sasee" ].each(printMapClosure) 

 //applies the closure to each element of the list

Moreover, closures can interact with variables outside itself and closures can be "anonymous", meaning that it is not given a name, and is defined in the place where the each method is called, as shown in the following example:


 fullString = "" //defines an empty String

 orderParts = ["BUY", 200, "Hot Dogs", "1"] //defines a String list

 orderParts.each {

   fullString += it + " " //concatenates fullString and the current String

 }

Dealing with Strings

Strings in Groovy have all the same functionality of Java strings. That is, a Groovy string is just a Java string with a few extra things added to it.


 stringDate = "2005-07-04"

 dateArray = stringDate.split("-")	

 //split() uses regEx's, so you need to escape chars such as a "." -> "."

 year = dateArray[0].toInteger()

 year = year + 1

 newDate = year + "-" + dateArray[1] + "-" + dateArray[2] 

 //defines a String containing the new data

This example uses the java.lang.String "split(String regex)" method to split the string around matches of the given regular expression and uses the toInteger() method to convert the string into an Integer. Note that the toInteger method is one of the Groovy methods added to the String class (Groovy JDK API specification).

 
 

This article is not up to date and it has been substitute with new up to date content.

Please look the new up to date content.