The Apache Groovy programming language

What is Groovy Scripting?




Groovy scripting

  • Compiling to Java bytecode, leveraging the JVM, and being interoperable with Java, Groovy adds the agileness and dynamic of scripting languages like Ruby or Python to Java.
  • Features include closures, native syntax for collections, regular expressions, variable interpolation into strings (GString), an XPath-like object / property / child object navigation (GPath), and operator overloading.
  • Groovy’s meta programming capabilities allow for extending objects at compile- or runtime, like adding or intercepting methods, altering behaviour, etc.
  • As almost any Java constructs are valid in Groovy, the learning curve is quite low. Moreover, most Groovy code is quite intuitively understandable.
  • Groovy is an object-oriented programming language for the Java platform

 


Groovy Basics

Groovy Console :

  • The Groovy Console is a Java Swing based graphical user interface that is packaged with the Groovy distribution. It provides a simple but elegant way of executing interactive groovy scripts, with Groovy script entered in the top window, and the output of the script appearing in the lower window.

Groovy Console
Groovy scripting Console

 

Groovy Compiler

  • Groovy compiler is much similar to the java compiler.
  • It compiles the code in the .grrovy file amd generates a class file.
  • Syntax to compile code in groovy is

groovyc file_name.groovy

  • The class file generated after compiling is similar to the class file compiled java compiler.This class file can be used in java programs if required.

Running Groovy Scripts

Groovy scripts are a number of statements and class declarations in a text file. Groovy scripts can be used similarly to other scripting languages. There are various ways of running Groovy scripts
Following are diff ways of executing groovy scripts :
a) Using the interactive console
b) Running Groovy scripts from your IDE
syntax : java groovy.lang.GroovyShell foo/MyScript.groovy [arguments]
c) Running Groovy scripts from the command line
groovy foo/MyScript.groovy [arguments]

Hashes, Arrays

Hashes :

  • Groovy uses Java implementations for storing hashes
  • A simple example of hashing is given as shown below:

 age = [ Nat:24, Jules:25, Josh:17 ]

 assert age[‘Nat’] == 24

 age.”Jules” == 25 

 foodColor = [ Apple: ‘red’, Banana: ‘yellow’, Lemon: ‘yellow’, Carrot: ‘orange’ ] 

 assert foodColor.size() == 4

 
Arrays :
An array is a container object that holds a fixed number of values of a single type
A simple implementation of array is shown below :
def MAX_SIZE = 4
def myArray = new Object[MAX_SIZE]
myArray[0] = “This”
myArray[1] = “is” myArray[2] =
“my” myArray[3] = “array”
myArray.each { log.info(it) }
 

General guidelines

  • Groovy is a optional typing language unlike java which is statically typed language or python which is dynamically typed.
  • This means declaring the data type is not mandatory.
  • We can declare based on the requirement.
  • Example :

def msg = ‘Hello’

def num = 8

  • This allows the variables msg and num to take values of different data types at diff times.
  • In groovy it is not mandatory to have semicolon to end the statement



Groovy Constructs

If, If-else, If-else if

  • If:  if construct is used to execute a set of commands based on some condition . In groovy the if construct is implemented as shown below

 
Example:
           
            def x = 10
      def y = 20
            If ( x =! y)
            {
                 x = true
            }
            assert x == y
 
If-else : This construct is used when we want execute a set of instruction if a particular condition is satisfied or diff set of instruction if it does not . Following is a simple implementation of if-else in groovy scripting
                    def x = false
                   def y = false
                   If ( !x )
                  {     x = true }
                  assert x == true
                 If ( x ) {     x = false }
                 else {     y = true }
                assert x == y
 
If-else-if : Groovy also supports the normal Java “nested” if then else if .
Below is the example illustrating if-else-if :
 def x = false
def y = false
if ( !x )
{
x = true
}
assert x == true
elseif ( x )
{
x = false
}
else
{
y = true
}
assert x == y
 

Loops – while, for, for-each

Loops : This construct is used to execute a set of instruction for a particular condtion is met.Groovy scripting also gives us the feature of using these constructs. Below are the examples how they are implemented in groovy

  • While Loop :

def x = 0
  def y = 5
   while ( y– > 0 )
           {
            x++
           }
            assert x == 5
 

  • for : The for loop in Groovy is much simpler and works with any kind of array, collection, Map etc.

 
     def x = 0
     for ( i in 0..9 )
     { 
        x += i
     }
    assert x == 45

  • for-each : Like in other laguages groovy also supports the for each looping constuct . Below is a simple example to illustrate it

def stringList = [ “java”, “perl”, “python”, “ruby”, “c#”,  “cobol”, “groovy”, “jython”, “smalltalk” ];
def stringMap = [ “Su” : “Sunday”, “Mo” : “Monday”, “Tu” : “Tuesday”, “We” : “Wednesday”, “Th” : “Thursday”, “Fr” : “Friday”, ];
stringList.each() { print ” ${it}” }; println “”;
stringMap.each() { key, value -> println “${key} ==  ${value}” };
 

  • Switch

The switch statement in Groovy is backwards compatible with Java code.One difference though is that the Groovy switch statement can handle any kind of switch value and different kinds of matching can be performed.
Example :

  •  def x = 1.23def result = “”
    switch ( x )
    {
    case “foo”:         result = “found foo”
    case “bar”:         result += “bar”
    case [4, 5, 6, ‘inList’]:         result = “list”
    case Number:         result = “number”
    default:         result = “default
    }
    assert result == “number”



Groovy Concepts

Exception Handling :
Handling exceptions in Groovy is the same as in Java. A try-catch block is used to catch an exception and handle it. In Groovy every exception is optional. This goes for checked exceptions as well.
Example :
try {
def url = new URL(‘malformedUrl’)
assert false, ‘We should never get here because of              the exception.’
} catch (MalformedURLException e) {
assert true
assert e in MalformedURLException
}
 
Regular Expression Match
Groovy supports regular expressions natively using the ~ “pattern”expression, which creates a compiled Java Pattern object from the given pattern string. Groovy also supports the =~ (create Matcher) and ==~ (returns boolean, whether String matches the pattern) operators.
Example :
  def checkSpelling(spellingAttempt, spellingRegularExpression)
 {
   if (spellingAttempt ==~ spellingRegularExpression)
     {
     println(“Congratulations, you spelled it correctly.”)
     } else
     {
       println(“Sorry, try again.”) }
    }
Examples :
1) slashy regex
pattern = ~/(?i)(\d+)\s+\d+%\s+(\/nfs\/data.*)/
2) Converting string into a regex
regex = “(?i)(\\d+)\\s+\\d+%\\s+(/nfs/data.*)”
pattern = ~regex
3) Converting a document string into regex
regex = ”'(?ix)(\\d+)\\s+\\d+%\\s+(/nfs/data.*)”’
pattern = ~regex
4) assert “It Is A Very Beautiful Day!” == (“it is a VERY beautiful day!”.replaceAll(/\w+/, { it[0].toUpperCase() + ((it.size() > 1) ? it[1..-1].toLowerCase() : ”) }))
 


Groovy Functions

Functions:
 Groovy’s functions (like Java’s) can be used to define functions which contain no imperative steps . We need not specify a return statement here . The value at the last step execution will be returned.
Defining functions :  Below is the example how we define a function
    def sayHello(name)
{
                return ‘Hello, ‘ + name
}
println sayHello(‘Groovy’)
 
Calling a function :

  • Calling a function in groovy is similar to java
  • Below is a example to show how a function is invoked

class Greeting
{
def sayHello(name) { return ‘Hello, ‘ + name }
}
def greet = new Greeting()
println greet.sayHello(‘Groovy’)

Console Programs

Similar to java programs , groovy scripts can also be executed using the command line .
Following are the steps to be followed :

  • Write the script in a notepad and save it with the extension .groovy.
  • Then the groovy script can be executed with the below c command :

groovy foo/MyScript.groovy [arguments]
      Example :
          $ cat test.groovy
println ‘Hello Bonson’
$ groovy test.groovy
Hello Bonson

  • We can also edit and run the script immediately . Below is a example to illustrate it :

$ cat test.groovy
println ‘Hello ‘ + args[0]
$ groovy test.groovy Jeeves
Hello Jeeves

  • We can also run such a simple groovy program by providing the script in the command line arguments.

$ groovy -e “println ‘Hello Bob'”
Hello Bob
 


Some Commonly used Groovy Functions

a ) size() : This function is used find the size of  the array
b ) min() : Returns the min value of the object array.It is also used to select the minimum value found from the Object array using the given comparator.
C ) Sum() : Sums the items in an array. This is equivalent to invoking the “plus” method on all items in the array.
d ) last() : Returns the last item from the array.
e ) Collect : It is used to collect the return value of calling a closure on each item in a collection.
Ex :
def value = [1, 2, 3].collect { it * 2 }
assert value == [2, 4, 6]
f ) inject : This function allows to pass a value into the first iteration and then pass the result of that iteration into the next iteration and so on. This is ideal for counting and other forms of processing
Ex :
def value = [1, 2, 3].inject(‘counting: ‘) { str, item -> str + item }  assert value == “counting: 123”   value = [1, 2, 3].inject(0) { count, item -> count + item } assert value == 6
g ) Assert : This function is used to add a check point or asserting a value.
Example :
def list = [1, 2, ‘hello’, new java.util.Date()]
assert list.size() == 4 assert list.get(2) == ‘hello’
assert list[2] == ‘hello’
h ) replace all: It replaces all occurrences of a captured group by the result of a closure call on that text.
Example :
assert “hellO wOrld” == “hello world”.replaceAll(~”(o)”) { it[0].toUpperCase() }
 

Math Functions :

Following are the mathematical functions available in groovy scripting :
  Number classes

  • abs
  • round

  Collections

  • sum
  • max
  • min

Ex:
Below shows a simple example using above mentioned functions
def list = [8, 6, 7, 5]
assert list.get(2) == 7
Assert list[2] == 7
println root.size()
println root.sum()
println root.min()
println root.last()
println root.max()
Output :
  4
  26
  5
  5
  8