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

Problems faced with Ubuntu 12.04 LTS in Lenovo Z580: Black/Purple Screen + OverHeat + Hanging of system and returning to Login Screen.

with 5 comments


  • Lenovo Z580
  • Ubuntu 12.04 LTS

PROBLEM 1: Black Screen recurrence and OverHeat generation in machine
Many a time, my machine got hanged and produced black/purple screen.After that I had to forcefully shutdown and restart the machine.

For this, I made changes in the grub file as below,

To go to the grub file —> gksudo gedit /etc/default/grub

grub file:

# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
# info -f grub -n 'Simple configuration'

GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX="noapic, nolapic"

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)

# Uncomment to disable graphical terminal (grub-pc only)

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux

# Uncomment to disable generation of recovery mode menu entries

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

Then in the terminal run,

sudo update-grub

PROBLEM 2: System getting stuck and returning to login screen:

After resolving the black screen problem, system still faced the problem of getting stuck while working on something and when I pressed Ctrl+Alt+Del, after sometime it took me to a command screen which said ,

could not write bytes: broken pipe.
checking battery state.

and then to the login screen.Now when I logged in, the programs, that I was working on, where closed without saving.

If this is what, even you are facing, then below is the solution for it.

It might be due to,

1. Mimatch of the nvidia version when we installed Ubuntu with that of the version getting updated.This mismatch in version doesn’t compatibilize with eachother and causes screen hanging.
For this, use the below commands

sudo apt-get purge nvidia-*

Here we purge nvidia instead of removing it.

  • PURGE: ‘purge’ removes nvidia completely from your machine including the configuration files.
  • REMOVE: ‘remove‘ removes the software but not the configuration files.
sudo apt-get install nvidia-current-updates

Above command does a fresh new installation of the latest nvidia onto your system.

2. Also check that Ubuntu 12.04 uses ldm and not gdm because it is said Ubuntu 12.04 uses lightdm(ldm) as its display manager.
For changing, exhibit the following commands,

sudo apt-get install lightdm
sudo dpkg-reconfigure lightdm
sudo stop gdm
sudo start ldm

Now Restart your system and it should work fine without getting stuck.

Any Driver Problems:
When you install Ubuntu from your USB card/CD, it doesn’t give you third party software in readymade Eg: Wifi-Drivers , Bluetooth Drivers etc.,

For this ,you should either carry out your installation with Internet on, so that latest packages will also be updated
When u install Ubuntu in your machine without Internet, you have to manually install the driver packages.

Have a great day 🙂

EJB class able to render REST WebService via Annotation

with 3 comments

Advancements in Java, especially the advent of JEE6 and JEE7  has eased the way we code.
Deployment descriptors for Servlet classes, Entity classes, Web Services are being replaced by annotations, thus advancing towards the concept of Convention over Configuration.

Below is a simple example on how to make a Session Bean class provide a RESTful WebService using annotations.

Here I have used JEE 7 and GlassFish 4 Application Server.
Note: As of now, JEE7 is  compatible only with GlassFish 4.

Here I have considered WebsterPublications example which has,

  •  DictionaryEntity – Entity class
  •  DictionaryResource – EJB+REST Service Provider Class

STEP 1: Create

@Table(name = "WP_DICTIONARY")
public class DictionaryEntity {

    private Long id;

    @NotNull(message = "Enter a word")
    private String word;

    @NotNull(message = "Enter the word's meaning")
    private String meaning;

    //Getters , Setters

Attributes can be annotated with constraints like @NotNull, @Pattern and can be made to through message during runtime, when violations occur.

STEP 2: Create

@Path(value = "dictionary")
public class DictionaryResource {

    @PersistenceContext(unitName = "webster")
    private EntityManager em;

    @Path(value = "wordlist")
    public List<DictionaryEntity> getWordList(){
        Query query=em.createQuery("select d from DictionaryEntity d");
        List<DictionaryEntity> wordList=query.getResultList();
        return wordList;

Here we can notice that this class apart from acting as a Stateless Bean also provides a RESTful WebService.
i.e., stateless session bean class providing the output object via REST WebService (Here JSON object got as Output).

Mapping the persistence unit and connection pooling in glassfish server is done (default Derby DB used).

STEP 3: Create

Since DictionaryResource acts like a Servlet by providing WebService, it’s essential to provide its entry in web.xml.
But this can also be done through annotation even.

WebsterRESTConfig class is created that extends Application and adds DictionaryResource as its resource class.Like DictionaryResource various other resource class can also be added."webresources")
public class WebsterRESTConfig extends Application {

    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        return resources;

   private void addRestResourceClasses(Set<Class<?>> resources) {

Here @ApplicationPath is equivalent to the servlet-mapping URL-Pattern that we would specify in web.xml.

Also note, while instantiating Set<Class<?>> resources = new java.util.HashSet<>(); I haven’t used generics in HashSet<> but have just used a plane Diamond notation. This is one of the light-weight changes in Java SE 7.

Now when we give the path as:


The result is obtained as below.


In my this post I wanted to highlight on the concept of Convention Over Configuration which is taking a great leap as the advancements in JEE versions are happening.Without even taking the pain to write the conventional web.xml deployment descriptor, we are now that able to  configure those settings by using simple annotations at the right place.

You can find the above source code in my GitHub repository. 

I wish you all a BLASTFUL 2014 🙂

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

Groovy is NOT Java !

with one comment

Groovy is a Dynamic Scripting Language.

It follows the principle of Duck Typing, 

“If anything quacks,walks and swims like a duck then the object is considered to be a duck.”

So, if something possesses,
BEHAVIOURS  —>quacking, walking and swimming like a duck then
TYPE of that object –> Duck
Therefore based on the behaviour , the type is assigned to a variable.

In Groovy , we use the keyword def to assign any type to a variable.

Here’s an example to illustrate the above.

def a=10
assert a in java.lang.Integer

assert a in java.math.BigDecimal

assert a in java.lang.String

In the above we can notice few things,

1. Variable a has been assigned to multiple types . This is possible in groovy ,because ‘a’ has been defined as def, which means polymorphic substitution of values is possible.However,whatever value has been assigned finally, that will considered as the final type of a.

2. In the assert statements, java library has been used. Actually Groovy is the extension of Java. GDK(Groovy Development Kit) extends JDK, Java Libraries. Groovy code when compiled , gets converted to Java Bytecode and runs on the JVM.

Groovy follows Java Syntax. That’s why , it’s generally said that, Groovy would be easy for Java Developers.
However, I would like  to mark on the above statement that, though Groovy would be easy for a Java developer to understand, the style of Groovy coding is different from Java.
GROOVY IS NOT JAVA and has to be coded in the Groovy way.

If Groovy is the same as Java, then why should the Groovy Language ever be introduced ?

3. I haven’t included any class or method(especially main method) to execute my code because Groovy is a SCRIPTING Language.However, when we write an application, classes and methods are included for clarity.

4. Semi-colons are not used in any of the statements.

Yes, it is not a compulsary in Groovy , to use semi-colons to end the statement. Even, if you use it, it’s not a mistake.
If multiple assignments are being made in a single statement, then semi-colons can be used.

def a=10;  b= "I feel up";  c= a+b

In the above case, without semi-colon , you’ll not be able to distinguish and will get Runtime-Exception.

5. In a=’Aish’ The String has been quoted in Single quote.

Double quotes can also be used. Their difference, I will quote it in my next blog.

Groovy has got many advanced features like String Gstring usage, Operators functioning based on t type ,Easy Looping using Closures, minimising  Exceptional handling and etc.,

Groovier Updates coming up…

Written by thangaveluaishwarya

August 24, 2013 at 3:37 PM