Archive for the ‘Groovy’ Category

Here is a small sample code I wrote that shows object serialization in groovy. when I ran this directly in groovy shell it did not work off the bat. I had to move the class Name to separate file Name.groovy and make sure it is in the class-path to work. Here is the link to original discussion on groovy forum.

// put this in a file named Name.groovy and compile using groovyc 
class Name implements Serializable  {
   def fname, lname
}
// Now run the code below to see the Object serialization and de-serialization.
def test1= new Name(fname: "fn1", lname : "ln1")
def test2 = new Name(fname: "fn2", lname: "ln2")
//serialization
new File("C:/config.txt").withObjectOutputStream { out ->
    out << test1
    out << test2
}
//de-serialization
new File("C:/config.txt").withObjectInputStream { instream ->
    instream.eachObject { 
        println it
    }
}

All controller actions in grails magically have access to request, params, session and bunch of other utility methods such as redirect, render etc. I digged through the grails source to find how it is done. The functionality is added to controller meta-classes utilizing groovy’s meta-programming capabilities. It is written as a plugin where in all the controller meta-classes are attached the functionality we all see. Here is the portion of code that adds some functionality. Imagine writing an action/controller in conventional j2ee style, this small portion of elegant code gets rid of all the boiler plate repetitive code. This simple example shows the power of meta programming. Kudos to all the contributors for this excellent project.

/*
The method below is called for controller meta classes. and RCH is the RequestContenxtHolder from spring MVC
import org.springframework.web.context.request.RequestContextHolder as RCH
*/
def registerCommonWebProperties(MetaClass mc, GrailsApplication application) {
        def paramsObject = {->
            RCH.currentRequestAttributes().params
        }
        def flashObject = {->
            RCH.currentRequestAttributes().flashScope
        }
        def sessionObject = {->
            RCH.currentRequestAttributes().session
        }
        def requestObject = {->
            RCH.currentRequestAttributes().currentRequest
        }
        def responseObject = {->
            RCH.currentRequestAttributes().currentResponse
        }
        def servletContextObject = {->
            RCH.currentRequestAttributes().servletContext
        }
        def grailsAttrsObject = {->
            RCH.currentRequestAttributes().attributes
        }
        // the params object
        mc.getParams = paramsObject
        // the flash object
        mc.getFlash = flashObject
        // the session object
        mc.getSession = sessionObject
        // the request object
        mc.getRequest = requestObject
        // the servlet context
        mc.getServletContext = servletContextObject
        // the response object
        mc.getResponse = responseObject
        // The GrailsApplicationAttributes object
        mc.getGrailsAttributes = grailsAttrsObject
        // The GrailsApplication object
        mc.getGrailsApplication = {-> RCH.currentRequestAttributes().attributes.grailsApplication }
        mc.getActionName = {->
            RCH.currentRequestAttributes().actionName
        }
        mc.getControllerName = {->
            RCH.currentRequestAttributes().controllerName
        }
    }
}

It is evident from recent developments in the software industry that there is and will be a huge push towards dynamic languages in coming years. Emerging and successful frameworks like Ruby on Rails, Django, Grails etc. have shown the power of dynamic languages. Not only these frameworks offer large productivity gain, underlying they are all pushing towards a new era of programming languages and features. Even .Net guys have realized this and started incorporating dynamic language features into C#. C#4.o will have features like dynamic type, optional parameters and default parameter values. So what is a dynamic language. Wikipedia does a good job of explaining what features are considered for a language to be dynamic. The following definition is directly picked from wikipedia.

“Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution. These behaviors can be emulated in nearly any language of sufficient complexity, but dynamic languages provide direct tools to make use of them.”

Ruby is my favorite among these especially because of its syntax and its ability to easily write DSLs. In my previous post I have  shown how we can write DSLs in Ruby and Groovy. Other features that make these languages more likable are Duck Typing, Closures, Meta-programming etc. There is a notion among lot of developers that these are scripting languages and not full blown programming languages. Any one who spends good amount of time learning Rails and Grails frameworks will take a step back and think. Although both ruby and groovy being ten times slower than java the productivity they offer outweighs the slowness, and with ever increasing power of CPUs we can afford that.

Check this out. A new magazine has started for groovy and grails developers. Kudos to all the people for their effort to put this magazine together.

http://www.groovymag.com/

Groovy’s spread and elvis operators are very elegant and from my experience I see that they are under used. Lets checkout the following code to see what spread and elvis operators can do for us.

1) Spread Operator used when we want to do an operation on a collection of objects

class Author {
    String name
    Book[] books
}
 
class Book {
    String name
}
 
def authors = []
def authorA = new Author(name:"GroovyGuy" ,books: [new Book(name:"groovy"), new Book(name:"grails")])
def authorB = new Author(name:"RubyGuy" ,books: [new Book(name:"ruby"), new Book(name:"rails")])
 
authors << authorA << authorB
 
//I want book names by authorA
println authorA*.books*.name
--> ["groovy", "grails"]
 
//I want all books names by all authors
println authors*.books*.name.flatten()
--> ["groovy", "grails", "ruby", "rails"]
 
println authors*.name
--> ["GroovyGuy", "RubyGuy"]
 
//we can also get list of books by doing this. but if we have a null object in either authors or books
//we get an null pointer exception. so spread takes cares
//of safe navigation on collection
println authors.books.name.flatten()
--> ["groovy", "grails", "ruby", "rails"]

2) Elvis oprator can be used to assign a default value to an object if it happens to be null or empty

def rockstar
def defaultrockstar = rockstar?:"Elvis Presley"
println defaultrockstar
-->"Elvis Presley"

     Recently I have been working more in Grails. After working a while in Ruby on Rails and checking out Grails, I have to say I am quiet impressed with Grails. Things that baffled me in Rails coming from conventional j2EE based frameworks are conventions, plugins, ActiveRecord dynamic finders and all other goodies by extending Ruby. Most of these are made possible by dynamic nature and meta-programming hooks of ruby. Grails also has gone in the RoR route by adopting convention over configuration, plugins, GORM etc. Although I prefer Rails personally but I have to admit Grails is not for throwaways. All those J2EE aficionado’s should at least start investing more in frameworks like Rails and Grails. Since Groovy syntax is more like java the learning curve should be fairly flat.

Both ruby and groovy enable us to easily write DSLs. In this blog I want to show how this made possible in Ruby and Groovy. “2.days.from.now” which is one my favorite constructs from Rails. Lets see how this is done in Ruby and Groovy.

In Ruby:

module IntegerExtensions
    def days
        self
    end
    def from
        self
    end
    def now
        Date.today - self
    end
end
class Fixnum
    include IntegerExtensions
end
print 2.days.from.now

In Groovy:

class IntegerExtentions {
    static getDays(self) {
        self
    }
    static getFrom(self) {
        self
    }
    static getNow(self) {
        new Date()-self
    }
}
use(IntegerExtentions) {
    print 2.days.from.now
}

I like the ruby way of using Modules to Mixin behavior at runtime. While in groovy Categories are a way to Mixin behavior
at runtime. ‘Use’ creates a separate scope so that all methods are available as class methods. Once you are out of ‘use’
block the methods are no longer available. There are other ways to achieve the same functionality in both groovy and ruby!
This is just one of them.