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{ ...
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...
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...
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...
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...
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...
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() ...