Archive for the ‘Groovy’ Category

New DelegatingScript Base Class – Groovy 2.2 feature

leave a comment »

Script base class of Compiler Configuration can be customized.
Delegating Script Base Class helps to delegate the calls in a script to a class that has DSL methods/functions & variables.

import org.codehaus.groovy.control.CompilerConfiguration

def scriptInfo='''
        model="Nexus 5"

class MobileDealer{
    String model
    void getModel(){
        println "Mobile : $model"

def compilerConfig=new CompilerConfiguration()
def shell=new GroovyShell(compilerConfig)
def script=shell.parse(scriptInfo)
MobileDealer m=new MobileDealer()
  • Line 1 – import package of Compiler Configuration class
  • Line 3-6 has the script where the delegate is set and is run finally.
  • Line 8-13 has the class declaration of the delegate class MobileDealer. The methods and variables in this class can be reused commonly in scripts.
  • Line 15new instance of compiler configuration is created
  • Line 16DelegatingScript is set as the base class for that particular compilerConfiguration instance
  • Line 17-new groovyShell instance is created with the present compiler Configuration
  • Line 18-The above “scriptInfo” is parsed to DelegatingScript type
  • Line 20-MobileDealer class is set as delegate in the script.
  • Line 21-the script is run.


Written by thangaveluaishwarya

February 14, 2014 at 12:32 PM

Groovy-2.X tidbits

leave a comment »

Did you know …?

1.We can know the last element of an array by using -1 as the index
def a=[1,2,3,4,5,6,7]
assert a[-1]==7

2.Groovy is much like an English speaking language
Eg :   for loop
Earlier in Java,

for(int i=1;i<=10;i++){

*NOTE: Now that Java 8 has introduced Instream for loop with range.

In Groovy,

 println 'Groovy'

3.Default access specifiers

  • for Class -> public
  • for Method -> public
  • for variables -> private

4.Groovy generates 2 constructors implicitly
(1) a public constructor
(2) a public constructor where its class variables can be passed as parameters.

5.Values in the constructor can be assgined via Implicit coersion and Explicit coersion too

class Season{
def type
def month

//Normal way
def s1=new Season(type:"winter",month:"December")

//Implicit coersion - pre-defining the type of variable.
Season s3=[type:"autumn",month:"September"]

//Explicit coersion using 'as'
def s2=[type:"summer",month:"May"] as Season

6.Underscores can be used in number literals for better understanding

long creditCardNumber=1234_2345_3456_4567L

Advancements in languages is happening day by day.
Groovy beta version has come up with advanced features like Delegating scripts, TypeChecking Extensions in Script, project coin(present in Java7) and etc.,However Java 8 is also coming up with much advanced features.

We should bear in mind that language should be only the means to make things simpler.
It’s wise to choose the right one based on our needs.

Written by thangaveluaishwarya

February 9, 2014 at 2:46 PM

How to convert your Grails App into a Mobile-friendly App

with 9 comments

Assuming that you have already created a Grails application and you have it running in your machine ,  but you are struggling to fit your application onto different screens like PC, IPad, Tablet, Mobile etc., where your page css is crashing , then it is hightime to check out on RESPONSIVE WEB DESIGN .

RESPONSIVE DESIGN LAYOUT is the layout that makes our application  respond to any device screensize that we are using, be it an Ipad /MAC/ Tablet/ Phablet/Mobile screen. Any webpage designed with this layout, will appear attractive, and flexible too.

Here I have tried out Twitter  Bootstrap template.

Now to integrate Bootstrap into Grails , it’s enough if we run this command grails install-plugin kickstart-with-bootstrap  in our existing Grails app  and then change the content type as “kickstart” in the header of every gsp page of every domain class.

Now when we run our application the template would be as below ,


Ajax-Autocomplete in Grails-Bootstrap :Screenshot_2013-11-15-15-52-52 (2)

For ajax-autocomplete to work in Grails Bootstrap, all that we need to do  is,

  • install ajax dependancy plugin by executing grails install-plugin ajaxdependancyselection command.
  • add  <r:require module=”jquery-ui”/>   <r:require module=”jquery”/> tags in the header of kickstart.gsp . These tags when executed, will install jquery and jquery-ui plugin by itself.
  • Finally, add the necessary autocomplete tag in the respective gsp page .

The output of Ajax autocomplete working in Bootstrap template integrated with Grails screenshot taken in mobile is shown in the rightside.

However well-designed and worthy be our application , it is of no use until we make it user-friendly and attractive to common people. A product with good appearance and easy-to-use,  is known to market on its own. Bootstrap is one of the templates that helps to achieve looks.

The above images that I have shown has the standard Twitter Bootstrap template. However, we can change the  design and also add extra features like Carousel, Accordian, Button types, nav-bar, modals etc., in it to give better looks.

Have a great day 🙂

Written by thangaveluaishwarya

December 3, 2013 at 11:30 PM

@Canonical = @ToString + @TupleConstructor + @EqualsAndHashCode

with 3 comments

ToString in Groovy:

In Java , we override toString() to print results.

In Groovy, this can be achieved simply, by using the @ToString annotation which is one of the A.S.T Transformation traits.(Example given below)

Tuple Constructor:

import groovy.transform.ToString

class Car{
  Long carID
  String carBrand
  String carModelNo

Car car=new Car(carID:10,carBrand:"Audi",carModelNo:"Q5")
println car                                      // O/P: Car(10, Audi, Q5)
println car                                      // O/P: Car(1, Audi, Q5)
println car                                      // O/P: Car(4, Audi, Q5)

In a POGO class, the values to the atributes can be set in the above following ways,

  • Using a default constructor, where the attribute and its value is set as Key-Value pairs.
  • By creating a reference for the class and just denoting ref.attributeName=value
  • Setting values using Setter method.

However, values can also be set using Tuple Constructor like the example below,

import groovy.transform.ToString
import groovy.transform.TupleConstructor

class Car{
  Long carID
  String carBrand
  String carModelNo

Car car=new Car(15,"BENZ","E-63")
println car                       //O/P:Car(15, BENZ, E-63)

Here , the attribute key is not required. Only values are set directly.

NOTE: Values have to be set only in the order of the attributes listed in the POGO because this Tuple Constructor is a specific positional type Constructor.

The above 2 functionalities i.e., pretty print using toString() and assigning values using Tuple Constructor, along with Equals and HashCode check can be achieved by using a single annotation @Canonical which is imported from groovy.transform.Canonical


       @Canonical =  @ToString + @TupleCOnstructor + @EqualandHashCode

Have a great day 🙂

Written by thangaveluaishwarya

October 19, 2013 at 12:22 PM

memoize() in Groovy

with 5 comments

Memoization generally means remembering the output for the already passed input.

In Groovy, memoization is performed using memoize().

An example of memoize() called on closures is given below,


def toSquare={a->

//Case 1:
println toSquare(5)           // O/P:25 --> Got after 2000ms
//Case 2:
println toSquare(5)           // O/P:25 --> Got IMMEDIATELY
//Case 3:
println toSquare(6)           // O/P:36 --> Got after 2000ms

In the above code,There is a closure toSquare.

Here any  parameter that is passed into the closure is squared only after 2000ms and above all, the closure is Memoized.

  • Case 1 : When the closure is called for the first time and parameter 5 is passed, the computation is done completely . In accordance with the computational flow, the result is printed only after 2000ms .
  • Case 2: When the closure is called for the second time and the same parameter 5 is passed, computation is not done and the result is displayed immediately. This is becuase of the memoize(). i.e., By Memoization principle , it stores the calculated value of the input that has been passed already.
  • Case 3: Here , a new input is being passed. Computation is done.Result is displayed after 2000ms. However now that , this result for this particular input will be cached.

memoize()                                     –> stores all the new inputs and the corresponding outputs.

memoizeAtLeast(minimum)  –> stores atleast a minimum number of results.

memoizeAtMost(maximum) –> stores the maximum number of results specified .


Have a memoizable day 🙂

Written by thangaveluaishwarya

September 21, 2013 at 11:25 PM

Operator ad-hoc Polymorphism in Groovy

with 2 comments

Operator ad-hoc polymorphism most commonly known as Operator Overloading, expresses about the polymorphic(more than one)  behaviour exhibited by the operator at different contexts.

In Groovy, this behaviour depends on the operands on both sides.

Let’s look at it.

def a="ten"; b=2.5; c=3; d=[]; e=[:]

//Case 1
assert result=='ten2.5'
println result.getClass()                    //O/P: class java.lang.String

//Case 2
assert result==5.5
println result.getClass()                    //O/P: class java.math.BigDecimal

//Case 3
println c.getClass()                        //O/P: class java.lang.Integer
assert c==50000000000003
println c.getClass()                        //O/P: class java.lang.Long
println c.getClass()                        //O/P: class java.math.BigInteger

//Case 4
assert d==[100]

assert e==['A':1,'B':2,'C':3]

//Case 5
def f='!'
println f*10                               //O/P: !!!!!!!!!!
assert f*10==f.multiply(10)

In the above code, each variable is of different type and the operator behaves accordingly.

  • Case 1: + Operator appends the BigDecimal value to a String and the result is of String type. 
    In Groovy, a decimal number, by default is of BigDecimal type. Instead of + operator,  . plus() method can also be used.

Like .plus(),  there are various methods corresponding to a particular operator function. You can check it out over here.

  • Case 2: + Operator performs the operation of summing a BigDecimal value and and an Integer. Here the result type is BigDecimal.
  • Case 3: Before going into the third case, let’s get to know of something…

When I assign a number value to a def variable, groovy takes into account, the smallest variable type that accomodates that particular value.

Here in this case of c , the type is Integer. As the size of the variable increases , it would make it the instance of Long or BigInteger which are of greater sizes. Therefore the order is Integer–> Long–> BigInteger.

  • Case 4:+ Operator performs the action of adding elements to the list d and map e.
  • Case 5: If we want to print a String n number of times, it can be done by multiplying the String by an integer as shown in above code case 5.

In all the above cases,we can see that, an operator decides its nature of operation  based upon the behaviour and type of the operands.

== and .equals():

In groovy, == and .equals carry the same meaning.  It checks for value equality.

def a='abcd'
println a=='abcd'                  //O/P: true
println a.equals('abcd')           //O/P: true

But == and .equals are not the same in GString Implementation.

def a='abcd'
println "$a"=='abcd'               //O/P: true
println "$a".equals('abcd')        //O/P: false

GStrings are again behaving in a strange way.

The reason is that, GString’s .equals() method takes in argument that is an instance of GString and not of any other type, be it even a String.


Groovy has provided us an extra flexibility with handling the ever torturing NullPointerException.

Let’s see how…

a=null         // Null Pointer Exception thrown
result=a?.plus(8)        // O/P: null

In the above case , we can see that ,

SAFE NAVIGATIONAL OPERATOR ‘?’ checks null and prevents NullPointer Exception to be thrown.

Safe Navigational Operator shouldn’t be followed by another operator. If done so , it wont work.


Here a sequence of elements are got  when the Lowest value and the Highest Value is specified.. The sequence can be a sequence of number/ character .

Ranges extend java.util.List class.

Range Object is a List Object. i.e., the output is obtained in List form.

Range is defined as below,

def a=10..7
assert a==[10,9,8,7]

It can also be defined by using a spread operator(*).

def b=[*'a'..'h']
assert b==['a','b','c','d','e','f','g','h']

Here spread operator  extracts and spreads individual values in the form of a List object.


class GreWordDetails{
    String greWord
    String wordMeaning
    def explanation(){
     "$greWord means $wordMeaning"
def wordList=[
      new GreWordDetails(greWord:'abash',wordMeaning:'ashamed'),
      new GreWordDetails(greWord:'enigma',wordMeaning:'mystery')
println wordList*.explanation()

O/P:[abash means ashamed, enigma means mystery]

It is said , The spread-dot operator (*.) is used to invoke a method on all members of a Collection object.

In the above code,  this operator invokes the explanation() method on the members of wordList object and spreads the result.

ELVIS Operator(?:):

This operator is a CUT SHORT form of TERNARY OPERATOR

b=(a!=null)?a:false can also be written as b=a?:false

Groovy Operators are not just this.. There are lots of other things like Spacechip Operator, EXOR, AND, OR,Power Operator and etc.,

Have a nice day 🙂

Quick Note 1: String and GString

with 3 comments

There are two different string classes used in Groovy and are java.lang.String and groovy.lang.GString.
Here String can be expressed using a single quote (‘abcd’) or a double quote (“abcd”).

Below is an example,

 def a='High-five'
assert a in java.lang.String

def b="High-five"
assert b in java.lang.String

def c=5; def d="High-$c"
assert d in groovy.lang.GString

From the above example, we can notice that variable a has its value declared in single quote and that of b in double quote. However both of them belong to the same class java.lang.String.

Just a variable’s value with double quote doesn’t make it a GString but, if a variable with double quote has another variable called inside it, by using $ symbol , then it is considered to be of GString type (groovy.lang.GString) .


def a=1
def dummyMap=['item-1':'Cookies']

println dummMap.getClass()             //O/P: class java.util.LinkedHashMap
println dummyMap."item-$a"            // O/P: Cookies
println dummyMap.("item-$a")          // O/P: Cookies
println dummyMap["item-$a"]           // O/P: Cookies
println dummyMap.get("item-$a")       // O/P: null

println dummyMap.get("item-1")        //O/P: Cookies

There are different ways of retrieving values from a Map in Groovy. Few are listed above.

Though in the first place it appears that GString can be used to retrieve values by using $ symbol before the variable name , it also misbehaves at times.

An example is shown above .Misbehaviour in dummyMap.get(“item-$a”) . It provides a null value.

It’s now important for us to understand that ,GStrings are not like Java String.
Java Strings are immutable but GStrings can be mutated.

Check it out below.

Mutation in GString:

def number=5
def dummyString="High-$number"
println dummyString                                        //O/P: High-5
println dummyString                                        // O/P: High-6

Since GString is mutable , if used in key , then key is also prone to mutation.Therefore, it’s not a good practice to use a GString in key.

However, we can rectify this by converting GString to String. This is done by using toString() method.Once GString is converted to String, there wouldn’t be any problem because String is immutable.

Therefore, dummyMap.get(“item-$a”.toString()) will give us the proper output.

Otherwise,  dummyMap.getAt(“item-$a”) can be used. It is a Groovy method , so groovy implicitly takes care of the String conversion.

Whereas, dummyMap.get(“item-$a”) is a Java Method.Here we’ll have to explicitly specify toString() for conversion.

Apart from the above, multiple lines assigning can be done by using,

 Triple Single Quote ”’ and Triple Double quotes “””. 

It considers new lines (\n), white spaces, tabs (\t ) and etc.,

Triple Single Quote – reads Multiple Lines but is not supported by GString

Triple Double Quote – reads Multiple lines and is supported by GString.

a='''Horror Movies :
    Evil Dead'''
println a
assert a in java.lang.String

def movieList=['Conjuring','Evil Dead','Grudge']
b="""Horror Movies :
println b
assert b in groovy.lang.GString

Have a great day 🙂

Written by thangaveluaishwarya

August 25, 2013 at 9:57 PM