Groovy « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Groovy ’ Category

Using Category in groovy

Posted by on November 30th, 2012

In one of my projects, I needed to save file from a particular url. I found a groovier way of doing this using category.

class FileBinaryCategory {
    def static leftShift(File file, URL url) {
        url.withInputStream {is ->
            file.withOutputStream {os ->
                def bs = new BufferedOutputStream(os)
                bs << is
            }
        }
    }
}

Here, I created a category class and created a static method named leftShift inside it. Here is how I used the category to download the file.

File download(String address) {
        def file = File.createTempFile(address.encodeAsMD5(), ".zip")
        use(FileBinaryCategory) {
            file << address.toURL()
        }
        return file
}

A category class consists of static methods. The first argument of the method defines the type to which that method is applied. In my case, the first argument is of type File.
The advantage of using category is that it can be applied to a specific part of the code by using the use keyword.

In line 4, the static method leftShift is called and a temporary file is passed as first argument and address.toURL() is passed as the second argument. The leftShift method simply copies the content from given address to the file.

Grails provides @Category annotation to achieve the same. You can find more about it here.

Raj Gupta
raj.gupta@intelligrape.com
@rajdgreat007

Posted in Grails, Groovy

Regular Expression – Slides Uploaded on SlideShare

Posted by on October 31st, 2012

Hi Guys,

 

I took a session on Regular Expressions in the company, i have shared my slide on slideshare. You can see it here :
http://www.slideshare.net/rajdgreat007/regular-expressions-14971247

 

I have discussed following topics in that slide :

  1. What are regular expressions
  2. Need for regular expressions
  3. Basic rules
  4. Regular expression groups
  5. search()
  6. match()
  7. replace()

 

I have thrown light on some practical examples in which we can use regular expressions. Hope you will like it.

 

Regards
Raj Gupta

Posted in Groovy

@Canonical annotation

Posted by on September 27th, 2012

@Canonical: It’s very useful annotation. It provides the combination of features of @ToString (default implementation of toString() method based upon the fields in the class), @EqualsAndHashCode(default implementation of equals() and hashCode() method of the class based upon the fields in the class) and @TupleConstructor (provides the classical constructor with default properties).

import groovy.transform.Canonical

@Canonical
class Person {
String name
String address
String city

}

Person person = new Person(name:"Mohit Garg",address:"Address",city: "city")
Person person1 = new Person("Mohit Garg","Address","city")

println("Check two objects are equal:::"+(person.equals(person1)))  // Both objects will be equal because of same hashCode. (Output:true)

println("person object:::"+person) //Output:Person(Mohit Garg, Address, city)

Hope this will help you :)

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Groovy

Groovy: Overriding “Plus” operator in a class with interesting example

Posted by on September 26th, 2012

Have you ever wondered how to overload “plus” operator in Groovy ? It is as easy as adding toppings to your favourite pizza. Let me explain. Let us taka a class for Pizza:

 

@ToString
class Pizza {
    String name
    List<Topping> toppings
    double price

}

And another for the Topping:

@ToString
class Topping {
    String name
    double price
}

Now to add toppings to the favourite pizza, let us overload the plus operator in Pizza class like this:

//Method with name "plus" will override the "+" operator. It will return a new pizza with the Toppings added.
    Pizza plus(Topping topping) {
        new Pizza(name: name, toppings: toppings + [topping], price: price + topping.price)
    }

Let us order a pizza:

Pizza pizza = new Pizza(name: "Veg Extravaganza Pizza", price: 323.32, toppings: [])

And our favourite toppings as well:

Topping cheeseBurst = new Topping(name: "cheese Burst", price: 80)
Topping extraCheese = new Topping(name: "Extra Cheese", price: 40.43)
Topping jalepenos = new Topping(name: "Jallepenos", price: 50.33)
Topping capsicum = new Topping(name: "capsicum", price: 20.32)

Can’t wait to add them all:

Pizza specialPizza = pizza + cheeseBurst + extraCheese + jalepenos + capsicum

Let us unbox our pizza:

println (specialPizza)
//OUTPUT
/*

Pizza(Veg Extravaganza Pizza, [Topping(cheese Burst, 80.0), Topping(Extra Cheese, 40.43), Topping(Jallepenos, 50.33), Topping(capsicum, 20.32)], 514.4)
*/

Isn’t it mouth watering.

Hope this helps.

 

Imran Mir
imran[at]intelligrape.com

Posted in Grails, Groovy

Getting property class from property name

Posted by on September 26th, 2012

Recently in one of my project i had a requirement of identifying the class of a property of an object with object class and property name and then determining whether it’s an Enum class or not. I found an easy solution for this using Reflection API. Using Java Reflection you can inspect the fields (member variables) of classes. This is done via the Java class java.lang.reflect.Field and calling geType() on this Field object gives the class of  that property.


class Utils {

public static def getClass(Class objectClass, String propertyName) {

def propertyClass = null

try {

propertyClass = objectClass.getDeclaredField(propertyName)?.type

}

catch (NoSuchFieldException ex){

log.error("No such property exist in this object class&"+objectClass)

}

return propertyClass

}

}

//Checking enum class or not

Utils.getClass(object.class,"someFieldName")?.isEnum()

There is one more benefit. One can also check whether particular property exists in a class or not as getDeclaredField throws NoSuchFieldException if there is no such property with given name in the object class.

(more…)

Posted in Grails, Groovy

Reading comments of LinkedIn wall post

Posted by on September 26th, 2012

Hi,


In one of my grails project, i needed to show the comments on any wall post of linkedin through API. I used the Java wrapper to connect any linkedIn account with the grails application which can be seen here. But somehow this library was not working when we need to fetch comments from any wall post and display them in our UI.


I searched a lot about it but couldn’t find anything appropriate, then i decided to use the linkedIn API directly for retrieving the data. To make GET calls , i used the Scribe java library which can be downloaded from here.


To make API calls on linkedIn, we need to have an authenticated account’s access_token and access_secret, which can be obtained by connecting a linkedIn account with the application as mentioned in this post.


Code to fetch comments on LinkedIn Wall post :-

String consumerKey = CONSUMER_KEY // key obtained by linkedIn app
String consumerSecret = CONSUMER_SECRET // secret obtained from linkedIn app
String accessToken = 'assess_token'
String accessSecret = 'access_secret'
String postId = POST_ID // id of the wall post

 OAuthService service = new ServiceBuilder()
                .provider(LinkedInApi.class)
                .apiKey(consumerKey)
                .apiSecret(consumerSecret)
                .debug()
                .build();
 String url = "http://api.linkedin.com/v1/people/~/network/updates/key=${postId}/update-comments?format=json";
 
       OAuthRequest request = new OAuthRequest(Verb.GET, url);
        org.scribe.model.Token accessToken = new org.scribe.model.Token(accessToken,accessSecret)
        service.signRequest(accessToken, request);
        Response response = request.send();
        String jsonResponse = response.getBody()
         def updates = JSON.parse(jsonResponse) // contains comments data in JSON format

          updates.values.each {def commentData ->
                  println "Comment : ${commentData.comment}"
                  println "Creator: ${commentData.person.firstName}"        
            }

This code will fetch the comments from any linkedin wall post. It worked in my case.


Hope it helps.


Cheers..!!!
Vishal Sahu
vishal@intelligrape.com
www.linkedin.com/in/vishalsahu

Posted in Grails, Groovy

Using Inject method in Groovy 2.0

Posted by on September 26th, 2012

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:

class Employee{
     String name
     Float salary
}

Employee emp1 = new Employee(name:"Divya",salary:50000)
Employee emp2 = new Employee(name:"Priya",salary:30000)
Employee emp3 = new Employee(name:"Ginny",salary:60000)
Employee emp4 = new Employee(name:"Shreya",salary:80000)
Employee emp5 = new Employee(name:"Heena",salary:10000)

List<Employee> employees = [emp1,emp2,emp3,emp4,emp5]

And if we have to find out sum of salaries of those employees whose salary is greater than 40000, then most cleaner way of doing the same is using the inject method which also prevent us to define a new variable for doing the same.

Float totalSalaryOfUsers = employees*.salary.inject{accumulator,currentValue-> accumulator  + (currentValue > 40000 ? currentValue : 0) }

println totalSalaryOfUsers

// Output : 190000.0

In previous version of Groovy(<2.0), there was need to initialize the inject method with a value, but in Groovy 2.0, inject method initializes itself with the first element of collection.

Consider one more example of inject method for clear understanding, i.e. ,converting list to String is:

List<String> thought = ["Don't","put","off","till","tomorrow","what","you","can","do","today"]

String strThought = thought.inject{accumulator,currentValue-> accumulator + " " + currentValue }

println strThought

// Output: Don't put off till tomorrow what you can do today

Posted in Groovy

@Log annotation

Posted by on September 26th, 2012

@Log : This annotation provides the log object in groovy class. By using it you don’t need to create the Logger object, it automatically provides log object.

Example:

import groovy.util.logging.Log

@Log
class Person {
    String name
    String address
    String city

    public void logDetails(){
        log.info("Name:::${name}--->Address ::: ${address}---> city :::${city}")
    }
}

new Person(name:"Mohit Garg",address:"Address",city: "city").logDetails()

It logs the details of the person object.

Hope this will help you :)

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Groovy

TupleConstructor annotation in Groovy

Posted by on September 25th, 2012

@TupleConstructor annotation provides the classical constructor with default properties. It will create the constructor with first parameter as address, second parameter as name etc. Constructor implementation depends upon the order of the variable declaration. One thing you need to ensure that you need to pass the value in same order as used in variable declaration.

Here is the example:

import groovy.transform.TupleConstructor
@TupleConstructor
class Person {
    String address
    String name
    String city
    int age
}

Person person1 = new Person('ADDD','MOHIT','CITY',1)

println("name:::"+person1.name)
println("adreess:::"+person1.address)
println("city:::"+person1.city)
println("age:::"+person1.age)

Hope this code will help you :)

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Tags:
Posted in Groovy

Executing Groovy scripts at runtime

Posted by on September 25th, 2012

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.


// Area.groovy

Float r = "${radius}".toFloat()  //radius will be passed as an argument to this script.

return "Area of the circle : " + Math.PI*r*r;


Now if we want to execute the Area.groovy script at runtime, then the solution is to use GroovyScriptEngine class. For using GroovyScriptEngine class, there is need to pass the directory path to tell where the groovy script is saved. e.g.

GroovyScriptEngine gse = new GroovyScriptEngine(<Directory_Path>);

If there is need to pass any argument in the script, then we can use Binding class to bind the argument with the script.

e.g.

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;

GroovyScriptEngine gse = new GroovyScriptEngine("/home/divya/Desktop");

Binding binding = new Binding();

binding.setVariable("radius", 5); // Argument to be passed is "radius" with value 5

String areaOfCircle = gse.run("Area.groovy", binding);

println areaOfCircle

// Output:  Area of the circle : 78.53981633974483

The run method is used to execute the script.

Hope it would help!!

Divya Setia
divya@intelligrape.com
https://twitter.com/divs157

Posted in Groovy