Divya Setia

Technology

Using Inject method in Groovy 2.0

A very useful enhanced method in Groovy 2.0 is inject method whose key purpose is to pass the outcome of first iteration to next iteration and keep on passing till all the elements of collections are processed. Lets start with an example, consider a class Employee with name and salary as attributes: [java] class Employee{ ...

26-Sep-2012

Grails

Executing Groovy scripts at runtime

A very useful Groovy class GroovyScriptEngine can be used to execute Groovy scripts at runtime. For understanding purpose, lets start with an example. We have a script named as Area.groovy that calculates the area of circle. [java] // Area.groovy Float r = "${radius}".toFloat() //radius will be passed as an...

25-Sep-2012

Technology

Changing the order of the elements of List in random manner

I found a very interesting method in java to change the order of elements in a list randomly, also called shuffling of elements in list. Actually I got the requirement to show a random product details out of 5 products, each time user refreshes the page. I came out with the solution using Collections.shuffle(<list>) For...

25-Sep-2012

Grails

Understanding Groovy 2.0 withLazyDefault and withEagerDefault methods

Sometimes there is need to get some default value in place of null values from a list, that was the reason I came across: withLazyDefault and withEagerDefault methods. My use case consisted of a list of user names with possibility of null elements, hence wherever the element was null, I wanted to return “unknown”. Although there...

17-Sep-2012

Grails

Two Interesting methods in Groovy 2.0 : takeWhile and dropWhile

Today I found two very interesting methods: takeWhile and dropWhile. The names itself reveals their work i.e. takeWhile (consider while some condition is true) and dropWhile (ignore while some condition is true). Although, these methods have been added to Groovy 1.8.7, but for character sequence, these methods are supported in Groovy...

12-Sep-2012

Grails

Groovy HTTP builder for sending multipart file.

I had two applications that communicate with each other through web-services. There I had a requirement to send multi-part file from one application to another. After searching I came out with the following solution and thought to share: [java] import org.apache.http.entity.mime.MultipartEntity import...

31-Aug-2012

Grails

Executing linux shell command using ProcessBuilder

We often need to execute linux shell command from our groovy code. What I had to do in my project was to resize the image saved on file system. I was doing something like : [java]String command = "convert -adaptive-resize ${width}x${height}! ${sourceFilePath} ${destinationFilePath}" Process process=command.execute() ...

29-Dec-2011