JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

JSF + Groovy Integration

April 10, 2014 by Amr Mohammed Leave a Comment

Groovy is another popular programming language for the Java Virtual Machine. Groovy is dynamically typed, and groovy code can be more concise than the equivalent Java because you can omit types of variables and parameters.

Almost any Java code is legal groovy, that’s make it simple and easier for getting started using it. Ultimately, using the Groovy within JSF applications isn’t more complex for one reason the using of groovy compiler to compile your groovy code does generate a .class file. In JSF, it doesn’t know, or care that you’re using groovy to generate them.

The JSF reference implementation  supports hot deployment of your Groovy code. When you change the groovy source files, the JSF implementation automatically recompile it and deploys the class files to the web application.

This tutorial you are going to integrate the Groovy with the JavaServer Faces using support of Eclipse IDE. This tutorial you will use the already created jsf maven project.

Tools Required For JSF + Groovy Integration

  • Eclipse IDE 4.3 (Kepler)
  • Tomcat Servlet Runner (7.0.35)
  • Groovy 2.0.x
  • JSF 2.0

1. Install Groovy Plugin for Eclipse

By using the Groovy download link you can choose the proper plugin for your Eclipse, but in our case you a have consider the link that provided for Kepler version. The steps required for installing the Groovy is as following:

  • Open Eclipse IDE
  • From Help menu choose Install New Software.
  • Inside Work with type the Groovy download link mentioned above.
  • From the fetched list, select Groovy-Eclipse.

Groovy Eclipse IDE - Download Groovy Plugin

2. Add Groovy Nature

If you’ve tried to create any type of Groovy files (groovy class, project, etc ..) you’re surely about getting complexity, cause your imported maven project doesn’t support Groovy naturally.

For adding Groovy you have to follow the below steps:

  • Right click on the created JSF project that imported into your eclipse IDE.
  • From Configure choose the option Convert To Groovy Project.
  • From Project menu select clean.
  • There is no specific perspective for Groovy, cause it’s considered as Java Project.

JSF 2 Groovy Add Nature

3. Groovy Library

Make sure that once you’ve added a groovy nature to your project,  the groovy library in it’s turn being added for it. Just look at your project structure and beside libraries such Maven Dependencies and JRE System Library you should see Groovy Libraries & Groovy DSL Support.

If you’ve not seen it, add it by the following steps:

  • Right click on your project.
  • From Grrovy Menu, select Add Groovy Library To Build Path.

But for those developers that focusing on using of maven you can consider the following dependency as mandatory.

Groovy Maven Dependency

[code lang=”xml”]
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.2.2</version>
</dependency>
[/code]

Either you are using the library added by the eclipse or use the library added by the maven, you are getting the right way and your application should running smoothly.

JSF 2 Groovy Add Library

JSF 2 Groovy Added Libraries

4. Groovy Class (Managed Bean)

To create a Groovy class that would be considering later as a managed bean, you have to follow the below steps:

  • Right click on the already created package and select New.
  • From the sub menu of new select Groovy Class.
  • Name your newly created Groovy class as IndexBean.
  • Staring to write a groovy class.

Your class should look like the below one:

IndexBean.groovy

[code lang=”java”]
package net.javabeat.jsf

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
class IndexBean implements GroovyObject{
private message = "Hello Mr. "; // Within groovy, you can omit the types
private userInput; // Within groovy, you can omit the types

public void setMessage(String message){
this.message = message;
}

public String getMessage(){
return this.message;
}

public void setUserInput(String userInput){
this.userInput = userInput;
}

public String getUserInput(){
return this.userInput;
}

public String navigate(){
return "anonymousView";
}
}
[/code]

  • Note using of properties without typos.
  • Note using of jsf2 @ManagedBean annotation
  • Note using of jsf2 @SessionScoped annotation
  • IndexBean groovy class defines two properties and one method named navigate that doesn’t consider any parameters and it will return a string.

JSF Groovy Adding Groovy Class

5. The View

index.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<f:view>
<h:form prependId="false">
<h1>JavaBeat JSF 2.2 Examples</h1>
<h2>JSF2 & Groovy</h2>
<br/>
<h:outputText value="#{indexBean.message}"></h:outputText>
<h:inputText value="#{indexBean.userInput}"></h:inputText>
<br/>
<h:commandButton value="Navigate Using Groovy Action" action="#{indexBean.navigate}"/>
</h:form>
</f:view>
</html>
[/code]

anonymousView.xhtml

[code lang=”xml”]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:form prependId="false">
<h1>JavaBeat JSF 2.2 Examples</h1>
<h2>JSF2 & Groovy</h2>
<h3>Anonymous View</h3>
<h:outputText value="#{indexBean.message}"></h:outputText>
#{‘ ‘}
<h:outputText value="#{indexBean.userInput}"></h:outputText>
</h:form>
</html>
[/code]

6. Faces Configuration File

faces-config.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<resource-bundle>
<base-name>net.javabeat.jsf.application</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>
[/code]

7. The Deployment Descriptor

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5" metadata-complete="true">
<context-param>
<description>State saving method: ‘client’ or ‘server’
(=default). See JSF Specification 2.5.2
</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
[/code]

8. JSF & Groovy Integration Demo

The below snapshots show you a running demonstration for a jsf application does use a Groovy programming language.

JSF 2 Groovy Example 1

JSF 2 Groovy Example 2

9. java.lang.NoClassDefFoundError: groovy/lang/GroovyObject

If you’ve followed the previous steps carefully, and your application doesn’t functional properly. Make sure that your Tomcat 7 has loaded the Groovy library in it’s classpath even your application has been compiled successfully. Also, you might be familiar with an error message that shown on the Eclipse console says

[code lang=”xml”]
SEVERE: Unable to load annotated class: net.javabeat.jsf.IndexBean, reason: java.lang.NoClassDefFoundError: groovy/lang/GroovyObject
[/code]

Even that your application has been running, but your groovy managed bean doesn’t initialized and try to navigate for seeing a big exception telling you that your managed bean is resolved to null.

Don’t worry, all things that you have to do is to assemble the groovy library into your server by following the below steps:

  • Right click on the project.
  • Choose properties, and point on Deployment Assembly.
  • Click Add button within the Web Deployment Assembly dialog.
  • Choose the Java Build Path Entries and click next.
  • Choose those libraries that mentioned for Groovy. and click finish.
  • Enjoy running your application.

JSF 2 Groovy Example 4

JSF 2 Groovy Example 5

JSF 2 Groovy Example 6

JSF 2 Groovy Example 7

[wpdm_file id=55]

Filed Under: JSF Tagged With: Eclipse, Groovy, JSF 2, JSF Integration

Setup Groovy enVironment Manager (GVM)

October 8, 2013 by Krishna Srinivasan Leave a Comment

Groovy enVironment Manager (GVM) is a tool used for managing the multiple version of the software development kits in the Unix based systems. In the current version, it supports the groovy related development kits. Groovy software kits can be installed and configured using this tool. There is no setup available for the windows based systems. In simple terms, GVM is very much handy for installing the various version of Groovy, Grails, etc. and setting the default version used or switching to different versions by using the command. At present it supports the following:

  • Groovy
  • Grails
  • Griffon
  • Gradle
  • Groovyserv
  • Lazybones
  • vert.x

This tool can be installed on the following platforms.

  • Linux
  • Mac OSX
  • Cygwin
  • Solaris
  • FreeBSD (with bash installed)

When you install GVM, your system should have installed the http://curl.haxx.se/ already. Otherwise you can install it by typing the following command. In the below example, second statement is for installing the GVM in your system.

[java]
sudo apt-get install curl
curl -s get.gvmtool.net | bash
[/java]

Install Software Using GVM

It is very simple to install using the above commands. Once installed, you can use the GVM commands and install the softwares supported by them (I have listed above in this article). You can specify any particular version details to install. If you are not passing the version details, it would install the latest version in the repository. Look at the below screenshot, when I type the command gvm install groovy, it has started installing the latest version of groovy 2.1.7 in my local. In the same way you can install the required software.

GVM  Groovy

Also you can add the already installed software to it. The following are commands important to remember.

[java]
$ gvm use grails 2.1.1 //Telling gvm to use specific version
$ gvm default grails 1.3.9 //Setting the default version to be used
$ gvm current grails // Lists current version details
$ gvm selfupdate //This enables the auto update of GVM when new version is released
$ gvm version //Prints current version of GVM
[/java]

The above commands are simple to understand and easy to to test it in your local environment. If you are working the Unix based systems, let’s try this tool if you are developing the groovy applications.

  • What is Groovy?
  • Spring and Groovy Integration

Filed Under: Groovy Tagged With: Groovy, GVM

CRUD Operations in Gaelyk- Part 2- Read Operation

June 24, 2012 by Mohamed Sanaulla Leave a Comment

In our previous post we saw about implementing Create operation for creating a new entity and persisting to the database. In this article lets see how we can retrieve all the entities stored in the datastore. This would be the Read operation from the CRUD operations in Gaelyk

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

Read- CRUD Operations in Gaelyk

We would continue with the project created in the previous post, so for those who haven’t please read the previous post and then continue with this post.

The DatastoreService provides synchronous access to the datastore to perform create, read, delete, update operations on the Entity. It also provides transaction support. Gaelyk provides shortcuts for the operations supported by Google App Engine and on similar lines DatastoreService can be accessed by using datastore shorthand.One can read here about the shorthands provided by Gaelyk for DatastoreService.

And as mentioned in previous post PROJECT_HOME is the location where the Gaelyk Template Project was extracted. Lets create listBooks.groovy groovlet in PROJECT_HOME/src/main/webapp/WEB-INF/groovy folder:

[code lang=”java”]
def books = datastore.execute{
select all from book
}
request.books = books
forward ‘/WEB-INF/pages/listBook.gtpl’
[/code]

All the groovy scripts in PROJECT_HOME/src/main/webapp/WEB-INF/groovy folder are the groovlets, just like the servlets we have in Java world. One can read about the datastore.execute syntax here. We fetch all the entities named “book” and store it in books reference and set this data to the request attribute. The books reference is actually some iterator which can be traversed using the each function. In Dynamically typed languages such as Groovy you really not care what the type is, we are concerned with what methods can be invoked on that object. Its something called “Duck Typing”. Lets have a look at listBook.gtpl which renders the data retrieved from above. Create listBook.gtpl in PROJECT_HOME/src/main/webapp/WEB-INF/pages:

[code lang=”xml”]
//listBook.gtpl
<% include ‘/WEB-INF/includes/header.gtpl’ %>
<div class=’row’>
<div class=’span1’><h4>ISBN</h4></div>
<div class=’span3’><h4>Title</h4></div>
<div class=’span3’><h4>Authors</h4></div>
<div class=’span2’><h4>Publisher</h4></div>
</div>
<%
request.books.each{
book ->
%>
<div class=’row’>
<div class=’span1’><%= book.isbn %></div>
<div class=’span3’><%= book.title %></div>
<div class=’span3’><%= book.authors %></div>
<div class=’span2’><%= book.publisher %></div>
</div>
<%
}
%>
<% include ‘/WEB-INF/includes/footer.gtpl’ %>
[/code]

As I said before we are more interested in the methods which can be invoked on the data set in the request. And I also said that the data set is some form of iterator and hence we iterate through it by providing a closure to the each method. In the closure provided we render the HTML content for each item in the iterator. This is quite familiar for people from the JSP/PHP world.

We havent yet setup the route to access the above page, lets go ahead and edit the routes.groovy file in PROJECT_HOME/src/main/webapp/WEB-INF/ and add the following line:

[code lang=”java”]
get ‘/book/all’, forward: ‘/listBooks.groovy’
[/code]

Run your application by executing gradlew gaeRun on the terminal and then access the page using: http://localhost:8080/book/all. If you dont see any data that means you havent added any. If you followed our previous post then you must be able to add new data by using the URL: http://localhost:8080/book/new.

Once the application is up and running, on visiting the browser, one would see some content similar to:

I have committed the source code into my github project here. Though the git hub project is not exclusively for this example, but it does contain the files/code necessary for these CRUD operation examples.

Filed Under: Groovy Tagged With: Gaelyk, Groovy

CRUD Operations in Gaelyk- Part 1- Create Operation

June 23, 2012 by Mohamed Sanaulla Leave a Comment

We have seen here and here on creating simple mashup using Gaelyk. In this series of articles lets see how we can implement CRUD operations in Gaelyk.

CRUD Operations in Gaelyk would involve:

  • Create an entity
  • Read an entity
  • Update an entity
  • Delete an entity

In this article we will look at creating an entity in the datastore.

Create of CRUD operations

Google App Engine supports both NoSQL and SQL based database. The NoSQL counterpart uses BigTable datastore. And we would be using the same for our CRUD operations.

The data in BigTable is held in Entity where each entity has some fields, associated types and values for each field. It also adds a Key to each data row in the entity.

We will look at the details of the datastore as we proceed further, but lets setup the Gaelyk project first. The easiest way is to download the template project from here and extract it to some directory. Lets call this directory as PROJECT_HOME. One can run the command gradlew gaeRun to deploy the template project into the embedded Jetty server and access it from http://localhost:8080/.

In this series of articles we would be focused on a Book entity which has the following fields: isbn, title, authors, publisher, number of pages. To create an entity and store in the database we need to create a form for data entry, let go ahead and create a newBook.gtpl in PROJECT_HOME/src/main/webapp/WEB-INF/pages folder:

[code lang=”html”]
//newBook.gtpl
<% include ‘/WEB-INF/includes/header.gtpl’ %>
<form action="/book" method="POST">
<div class="row">
<div class="span5">
<label for="isbn"/>ISBN</label>
<input id="isbn" type="text"
name="isbn"/>

<label for="title"/>Title</label>
<input id="title" type="text"
name="title"/>

<label for="authors"/>Author(s)</label>
<input id="authors" type="text"
name="authors"/>

<label for="publisher"/>Publisher</label>
<input id="publisher" type="text"
name="publisher"/>

<label for="numberOfPages"/>Number of Pages</label>
<input id="numberOfPages" type="text"
name="numberOfPages"/>
</div>
</div>
<div class="row">
<div class="span4">
<input type="submit" value="Save">
<input type="reset" value="Reset">
</div>
</div>
</form>

<% include ‘/WEB-INF/includes/footer.gtpl’ %>
[/code]

The template project uses bootstrap and therefor the styling aspects would be taken care! Now that we have a form to enter the data, we would need to setup up the route to access this page, that way we will have clean urls and not ending with .gtpl or .groovy and so on. The routes.groovy file handles all the routing information and is present in PROJECT_HOME/src/main/webapp/WEB-INF folder. Lets add the following entry to the routes.groovy file

[code lang=”html”]
//routes.groovy
get "/book/new", forward: "/WEB-INF/pages/newBook.gtpl"
[/code]

the above code says that when there is a GET request for ‘/book/new’, forward the request to the newBook.gtpl which renders the html markup for the page. On running the application locally using gradlew gaeRun and navigating to http://localhost:8080/book/new you should be able to see your page as something like:

Wait! we havent still configured the routes for Save operations, lets go ahead of do that. Lets create a groovy script addBook.groovy in the PROJECT_HOME/src/main/webapp/WEB-INF/groovy folder where all the groovy scripts(groovlets) are to be added.

[code lang=”java”]
//addBook.groovy
import com.google.appengine.api.datastore.Entity
def entity = new Entity("book")
entity << params
entity.save()
request.operation = "saved"
request.savedTitle = params.title

forward ‘/WEB-INF/pages/success.gtpl’
[/code]

params is a map which contains the data submitted by the form as key-value pairs. One can inspect the data by logging params.isbn or params.title or any of the params.fieldName data on to the console. Just in case someone wants to try use log.info params.title in the above groovy script.

[code lang=”java”]
entity << params
entity.save()
[/code]

the above code appends the key-value pairs in the params object to the entity object we have created and then save the contents on the entity object to the datastore. After saving the entity we forward to another page- success.gtpl which is created in PROJECT_HOME/src/main/webapp/WEB-INF/pages folder.

[code lang=”html”]
//success.gtpl
<% include ‘/WEB-INF/includes/header.gtpl’ %>
<div class="row">
<p>Successfully <%= request.operation %> the
book <%= request.savedTitle %></p>
<p><a href="/book/new">Add another book</a></p>
</div>

<% include ‘/WEB-INF/includes/footer.gtpl’ %>
[/code]

We are yet to setup the route information for the groovy script we created to add the books. So go back to routes.groovy and add the following to the routes.groovy

[code lang=”html”]
//routes.groovy
post "/book", forward: "/addBook.groovy"
[/code]

which says, that any POST requests for /book should be forwarded to addBook.groovy script/groovlet. So save all the files and reload the URL http://localhost:8080/book/new and add some entries to the form and click on “Save” button and you should be able to see the “success” page.

Google App Engine provides a way to access the entities/data stored in the datastores by navigating to: http://localhost:8080/_ah/admin/datastore.

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

In the next article lets see how we can list all the entities we have stored in the datastore.

Filed Under: Groovy Tagged With: Gaelyk, Groovy

Developing Groovy based web application and deploying to Google App Engine

June 5, 2012 by Mohamed Sanaulla Leave a Comment

We have seen how to develop a ZK based application and deploy it to OpenShift. Google has also a Paas offering called Google App Engine(GAE) which supports Java, Python and Dart applications. Gaelyk is a simple Groovy based toolkit to develop and deploy application to GAE. In this article lets build a simple Gaelyk based application and deploy it to GAE.

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

The sample application developed would show the details of location information from where this application was accessed, information lie Name of the city, country, region, latitude, longitude and timezone would be shown.

Setting up Gaelyk

But before that we need to download and setup Gaelyk. Faster way to start with Gaelyk is to download the Template project and extract its contents. Gaelyk template project uses Gradle build system to manage all the dependencies. To draw an analogy Gradle is similar to Maven. The template project has defined all the require dependencies and also provides a Gradle wrapper gradlew using which you can run gradle tasks without having to install Gradle. Also Gradle manages downloading and configuring the Google App Engine SDK, so you need not worry about that.
[code]
$ gradlew tasks
[/code]
shows the available tasks, it might download the dependencies it doesnt find in its local repository. To run the template project:
[code]
$ gradlew gaeRun
[/code]

The application will be deployed in the embedded jetty container and can be accessed at http://localhost:8080/. Gaelyk builds on top of Groovlets and Groovy templates. Groovy templates and Groovlets reside in the WEB-INF/pages and WEB-INF/groovy folders respectively. Also all the GAE services can be accessed from with in these Groovlets and Groovy Templates using the shortcodes provided by Gaelyk like memcache for accessing the caching service, datastore for accessing the GAE Datastore service and so on.

Location Information from IP Address

For this we make use of the API provided by the IPInfoDb. We are interested in City wise precision and the results in JSON, hence make use of the following API:
[code lang=”xml”]
http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=<ip_address>&format=json
[/code]

The above api returns result which is something like
[code]
{
"statusCode" : "OK",
"statusMessage" : "",
"ipAddress" : "74.125.45.100",
"countryCode" : "US",
"countryName" : "UNITED STATES",
"regionName" : "CALIFORNIA",
"cityName" : "MOUNTAIN VIEW",
"zipCode" : "94043",
"latitude" : "37.3956",
"longitude" : "-122.076",
"timeZone" : "-08:00"
}
[/code]
parsing the above JSON in Groovy we would have something like
[code lang=”java”]
//Setting up the JSON data.
def myIp = request.remoteAddr
def api_key="<enter the api key for IpInfoDb here>"
def ipUrl = "http://api.ipinfodb.com/v3/ip-city/?key=${api_key}&ip=${myIp}&format=json"
def jsonSlurper = new JsonSlurper()
def locationInformation = jsonSlurper.parseText(new URL(ipUrl).text)
[/code]

In the above code request represents the HttpServletRequest object and to access the IP address of the client we make use of the getRemoteAddr() method of HttpServletRequest. In groovy one can invoke getPropertyName as just propertyName, hence request.remoteAddr. If you are running this locally then you might want to replace the IP address 127.0.0.1 with your actual IP address. Something like:
[code lang=”java”]
def myIp = request.remoteAddr
if(myIp.equals("127.0.0.1")){
myIp = "YOUR IP ADDRESS"
}
[/code]
The subsequent code makes a GET request to the API URL and parses the obtained JSON response to get the location information.
[code lang=”java”]
//Parsing the JSON to get the required information
locationInformation = jsonSlurper.parseText(new URL(ipUrl).text)

//We set this as parameters to the request object
request.ipAddress = locationInformation.ipAddress
request.country = locationInformation.countryName
request.region = locationInformation.regionName
request.city = locationInformation.cityName
request.latitude = locationInformation.latitude
request.longitude = locationInformation.longitude
request.timezone = locationInformation.timeZone
[/code]

Gaelyk provides a flexible URL routing system where in we can map the URL to corresponding Groovlets. These routes are declared in the routes.groovy file which is present in the WEB-INF directory. Lets create a Groovlet for our Index page and call it: index.groovy and this groovlet would be responsible for intercepting the request and obtaining the required data and forwarding to the right groovy template. The template project which you would have downloaded would have a groovy template by name: index.gtpl, and the groovlet which we created would forward the request to index.gtpl. The template project has the “/” route pointing to a different handler, we would update that to point to our groovlet.
[code lang=”java”]
//Updating the routes.groovy
get "/", forward: "/index.groovy"
[/code]

As already mentioned the groovlet: index.groovy would be responsible for obtaining the location information from the IP address and setting those values in the request, which are then displayed by the groovy template- index.gtpl
[code lang=”java”]
//Contents of index.groovy
import groovy.json.JsonSlurper

def myIp = request.remoteAddr
if(myIp.equals("127.0.0.1")){
myIp = "YOUR IP ADDRESS"
}

def api_key="YOUR IPINFODB API KEY"

def ipUrl = "http://api.ipinfodb.com/v3/ip-city/?key=${api_key}&ip=${myIp}&format=json"
def jsonSlurper = new JsonSlurper()
def locationInformation = null
//Use memcache to cache the location information
if (memcache[myIp] != null){
locationInformation = memcache[myIp]
}
else{
locationInformation = jsonSlurper.parseText(new URL(ipUrl).text)
memcache[myIp] = locationInformation
}
request.ipAddress = locationInformation.ipAddress
request.country = locationInformation.countryName
request.region = locationInformation.regionName
request.city = locationInformation.cityName
request.latitude = locationInformation.latitude
request.longitude = locationInformation.longitude
request.timezone = locationInformation.timeZone

//Forward to the corresponding groovy template
forward ‘/WEB-INF/pages/index.gtpl’
[/code]
The interesting piece of information in the above code snippet is:memcache. This binding refers to the Memcache service provided by Google App Engine. We cache the location information against the IP address and any subsequent requests from the same IP would fetch from the cache instead.

The values set as part of the request parameters are then retrieved by the index.gtpl as:

[code lang=”html”]
<% include ‘/WEB-INF/includes/header.gtpl’ %>
<div class="row">
<div class="span12">
<h2>You are accessing from</h2>
<ul>
<li>Your IP Address: ${request.ipAddress}</li>
<li>Country: ${request.country}</li>
<li>Region: ${request.region}</li>
<li>City: ${request.city}</li>
<li>Latitude: ${request.latitude}</li>
<li>Longitude: ${request.longitude}</li>
<li>Timezone: ${request.timezone}</li>
</ul>
</div>
</div>
<% include ‘/WEB-INF/includes/footer.gtpl’ %>
[/code]

the include is used to include other groovy templates. Groovy templates lets you embed groovy code by just like we do in JSP and PHP.
[code]
#Run the application
$ ./gradlew gaeRun
[/code]
The application would be running http://localhost:8080/

One can even create a eclipse/intellij project for this by:
[code]
#For Eclipse
gradlew cleanEclipse eclipse

#For IntelliJ
gradlew cleanIdea idea
[/code]
and then load the project in your IDE.

Once we are done with the development, we can deploy to Google App Engine by using:
[code]
$ ./gradlew gaeUpload
[/code]
but before that you must create an application in your Google App Engine account and update the appengine-web.xml file in src/main/webapp/WEB-INF directory by adding the appid to the XML.

To try out this sample, you need to create a new index.groovy file in src/main/webapp/WEB-INF/groovy folder. Then create index.gtpl in src/main/webapp/WEB-INF/pages. Also dont forget to update the appengine-web.xml file.

Filed Under: Groovy Tagged With: Gaelyk, Google App Engine, Groovy

Exiting Blocks and Methods in Groovy

April 26, 2011 by Krishna Srinivasan Leave a Comment

This article is based on Groovy in Action, Second Edition, to be published on Summer 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ Use promotional code ‘java40beat’ and get 40% discount on eBooks and pBooks ]

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

Exiting Blocks and Methods

Introduction

Although it’s nice to have code that reads like a simple list of instructions with no jumping around, it’s often vital that control is passed from the current block or method to the enclosing block or the calling method—or sometimes even further up the call stack. Just like in Java, Groovy allows this to happen in an expected, orderly fashion with return, break, and continue statements and, in emergency situations, with exceptions. Let’s take a closer look.

Normal termination: return/break/continue

The general logic of return, break, and continue is similar to Java. One difference is that the return keyword is optional for the last expression in a method or closure. If it is omitted, the return value is that of the last expression. Methods with an explicit return type of void do not return a value, whereas closures always return a value.

Listing 1 shows how the current loop is shortcut with continue and prematurely ended with break. As in Java, there is an optional label.

Listing 1 Simple break and continue
[code lang=”java”]def a = 1
while (true) { //#1 Do forever
a++
break //#2 Forever is over now
}
assert a == 2
for (i in 0..10) {
if (i==0) continue //#3 Proceed with 1
a++
if (i > 0) break //#4 Premature loop end
}
assert a==3
Using break and continue is sometimes considered smelly. However, they can be useful for controlling the workflow in services that run in an endless loop or for breaking apart complex conditional logic, such as this:
for(i in whatever){
if (filterA) continue // skip if filter matches
if (conditionB) break // exit loop if condition matches
// normal case here
}[/code]
Similarly, returning from multiple points in the method is frowned upon in some circles but other people find it can greatly increase the readability of methods that might be able to return a result early. We encourage you to figure out what you find most readable and discuss it with whomever else is going to be reading your code—consistency is as important as anything else.

As a final note on return handling, remember that, when closures are used with iteration methods such as each, a return statement within the closure returns from the closure rather than the method.

Exceptions: throw/try-catch-finally

Exception handling is exactly the same as in Java and follows the same logic. Just as in Java, you can specify a complete try-catch-finally sequence of blocks, or just try-catch, or just try-finally. Note that, unlike various other control structures, braces are required around the block bodies whether or not they contain more than one statement. The only difference between Java and Groovy in terms of exceptions is that declarations of exceptions in the method signature are optional, even for checked exceptions. Listing 2 shows the usual behavior.

Listing 2 Throw, try, catch, and finally
[code lang=”java”]def myMethod() {
throw new IllegalArgumentException()
}
def log = []
try {
myMethod()
} catch (Exception e) {
log << e.toString()
} finally {
log << ‘finally’
}
assert log.size() == 2[/code]
In accordance with optional typing in the rest of Groovy, a type declaration is optional in the catch expression. And, like in Java, you can declare multiple catches.

There are no compile-time or runtime warnings from Groovy when checked exceptions are not declared. When a checked exception is not handled, it is propagated up the execution stack like a RuntimeException in Java.

It is worth noting an issue relating to exceptions. When using a Groovy class from Java, you need to be careful—the Groovy methods will not declare that they throw any checked exceptions unless you’ve explicitly added the declaration even though they might throw checked exceptions at runtime. Unfortunately, the Java compiler attempts to be clever and will complain if you try to catch a checked exception in Java when it believes there’s no way that the exception can be thrown. If you run into this and need to explicitly catch a checked exception generated in Groovy code, you may need to add a throws declaration to the Groovy code just to keep javac happy.

Summary

This article covered one of Groovy’s control structures: exiting blocks and methods early. We haven’t seen any big surprises: everything turned out to be like Java, enriched with a bit of Groovy flavor. The only structural difference is the for loop. Exception handling is very similar to Java, minus the requirement to declare checked exceptions.

Filed Under: Groovy Tagged With: Groovy

Objects in Groovy

April 26, 2011 by Krishna Srinivasan Leave a Comment

This article is based on Groovy in Action, Second Edition, to be published on Summer 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ Use promotional code ‘java40beat’ and get 40% discount on eBooks and pBooks ]

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

Introduction

In Groovy, everything is an object. It is, after all, an object-oriented language. Groovy doesn’t have the slight fudge factor of Java, which is object-oriented apart from some built-in types. In order to explain the choices made by Groovy’s designers, we’ll first go over some basics of Java’s type system. We will then explain how Groovy addresses the difficulties presented and, finally, examine how Groovy and Java can still interoperate with ease due to automatic boxing and unboxing where necessary.

Java’s type system—primitives and references

Java distinguishes between primitive types (such as boolean, short, int, float, double, char, and byte) and reference types (such as Object and String). There is a fixed set of primitive types and these are the only types that have value semantics, where the value of a variable of that type is the actual number (or character, or true/false value). You cannot create your own value types in Java.

Reference types (everything apart from primitives) have reference semantics; the value of a variable of that type is only a reference to an object. Readers with a C/C++ background may wish to think of a reference as a pointer—it’s a similar concept. If you change the value of a reference type variable that has no effect on the object it was previously referring to, you’re just making the variable refer to a different object or to no object at all. The reverse is true too: changing the contents of an object doesn’t affect the value of a variable referring to that object.

You cannot call methods on values of primitive types, and you cannot use them where Java expects objects of type java.lang.Object. For each primitive type, Java has a wrapper type–a reference type that stores a value of the primitive type in an object. For example, the wrapper for int is java.lang.Integer.

On the other hand, operators such as * in 3*2 or a*b are not supported for arbitrary1 reference types, but only for primitive types (with the notable exception of +, which is also supported for strings).

The Groovy code in listing 1 calls methods on seemingly primitive types (first, with a literal declaration and, then, on a variable), which is not allowed in Java, where you need to explicitly create the integer wrapper to convince the compiler. While calling + on strings is allowed in Java, calling the – (minus) operator is not. Groovy allows both.

Listing 1 Groovy allows methods to be called on types that are declared like primitive types in Java
[code lang=”java”](60 * 60 * 24 * 365).toString(); // invalid Java
int secondsPerYear = 60 * 60 * 24 * 365;
secondsPerYear.toString(); // invalid Java
new Integer(secondsPerYear).toString();
assert "abc" – "a" == "bc" // invalid Java[/code]
The Groovy way looks more consistent and involves some language sophistication that we are going to explore next.

Groovy’s answer—everything’s an object

In order to make Groovy fully object oriented and because, at the JVM level, Java does not support object-oriented operations such as method calls on primitive types, Groovy designers decided to do away with primitive types. When Groovy needs to store values that would have used Java’s primitive types, Groovy uses the wrapper classes already provided by the Java platform. Table 1 provides a complete list of these wrappers.

Any time you see what looks like a primitive literal value (for example, the number 5, or the Boolean value true) in Groovy source code, that’s a reference to an instance of the appropriate wrapper class. For the sake of brevity and familiarity, Groovy allows you to declare variables as if they were primitive type variables. Don’t be fooled—the type used is really the wrapper type. Strings and arrays are not listed in table 1 because they are already reference types and not primitive types—no wrapper is needed.

While we have the Java primitives under the microscope, so to speak, it’s worth examining the numeric literal formats that Java and Groovy each use. They are slightly different because Groovy allows instances of java.math.BigDecimal and java.math.BigInteger to be specified using literals in addition to the usual binary floating-point types. Table 2 gives examples of each of the literal formats available for numeric types in Groovy.

Notice how Groovy decides whether to use a BigInteger or a BigDecimal to hold a literal with a G suffix depending on the presence or absence of a decimal point. Furthermore, notice how BigDecimal is the default type of non-integer literals; BigDecimal will be used unless you specify a suffix to force the literal to be a Float or a Double.

Interoperating with Java—automatic boxing and unboxing

Converting a primitive value into an instance of a wrapper type is called boxing in Java and other languages that support the same notion. The reverse action—taking an instance of a wrapper and retrieving the primitive value—is called unboxing. Groovy performs these operations automatically for you where necessary. This is primarily the case when you call a Java method from Groovy. This automatic boxing and unboxing is known as autoboxing.

You’ve already seen that Groovy is designed to work well with Java; so, what happens when a Java method takes primitive parameters or returns a primitive return type? How can you call that method from Groovy? Consider the existing method in the java.lang.String class: int indexOf (int ch). You can call this method from Groovy like this:
[code lang=”java”]assert ’ABCDE’.indexOf(67) == 2[/code]
From Groovy’s point of view, we’re passing an Integer containing the value 67 (the Unicode value for the letter C), even though the method expects a parameter of primitive type int. Groovy takes care of the unboxing. The method returns a primitive type int that is boxed into an Integer as soon as it enters the world of Groovy. That way, we can compare it to the Integer with value 2 back in the Groovy script.

Figure 1 shows the process of going from the Groovy world to the Java world and back.

Figure 1 Autoboxing in action: An Integer parameter is unboxed to an int for the Java method call, and an int return value is boxed into an Integer for use in Groovy.All of this is transparent—you don’t need to do anything in the Groovy code to enable it. Now that you understand autoboxing, the question of how to apply operators to objects becomes interesting. We’ll explore this question next.

No intermediate unboxing

If in 1 + 1 both numbers are objects of type Integer, you may be wondering whether those Integers unboxed to execute the plus operation on primitive types.

The answer is no: Groovy is more object-oriented than Java. It executes this expression as 1.plus(1), calling the plus() method of the first Integer object, and passing3 the second Integer object as an argument. The method call returns an Integer object of value 2.

This is a powerful model. Calling methods on objects is what object-oriented languages should do. It opens the door for applying the full range of object-oriented capabilities to those operators.

Summary

Let’s summarize. No matter how literals (numbers, strings, and so forth) appear in Groovy code, they are always objects. Only at the border to Java are they boxed and unboxed. Operators are shorthand for method calls.

Filed Under: Groovy Tagged With: Groovy

Groovy Interview Questions and FAQs

August 5, 2010 by Krishna Srinivasan Leave a Comment

Groovy Interview Questions and FAQs – 1

What is Groovy?

Groovy is a powerful high level language for the Java platform which compiles down to Java bytecode.
Think of it as a Ruby or Python like language that is tightly integrated with the Java platform – allowing you the same powerful and concise coding syntax as Ruby or Pyton but allowing you to stay on the JVM and protect your investment in J2SE, J2EE and all the plethora of great useful Java code out there.

Why Groovy? Why don’t you just use Jython, JRuby, bsh, rhino, pnuts, …

Firstly ports of existing languages like Python, Ruby, Smalltalk and JavaScript to the JVM are a good thing and we welcome them. If you already use and/or are fond of these languages please be our guests to use the Java-port of them.One of the main design goals of Groovy is to be a scripting language for Java developers to use. So we wanted to reuse both Java’s semantics and the whole set of J2SE APIs rather than introduce a port of a different language with different semantics and APIs to learn and implement/maintain.

e.g. in Groovy, java.lang.Object is the root of the object hierarchy, Object.equals(), Object.hashCode() and Comparable are used for comparions and lookups of objects, that java.util.List and java.util.Map are used for collections, Java Beans are fully supported and that Java and Groovy classes are interchangable inside the VM. Groovy is built on top of the J2SE APIs, rather than having 2 parallel platforms etc.
In other words we wanted the Groovy language to be very easy to pick up if you’re already a Java developer and for there to be a very small number of new APIs to learn. By this statement we’re not implying that Python / Ruby / JavaScript are hard to learn per se – its just there’s more to know, things are more different and there’s more APIs to learn

Think of Groovy as a Ruby or Python like language that is tightly integrated with the Java platform (as opposed to the Unix/Posix command shell and C-libraries) – allowing you the same powerful and concise coding syntax as Ruby or Pyton but allowing you to stay on the JVM and protect your investment in J2SE, J2EE and all the plethora of great useful Java code out there without any adapter layers or parallel API sets etc. There is a more detailed set of comparisio ther languages here

What are the dependencies for Groovy?

As well as Java 1.4 and the Groovy jar we also depend at runtime on the ASM library.

What is the licence for Groovy?

Groovy is open source using a BSD / Apache style licence

I get errors when trying to run groovy, groovysh or groovyConsole. Whats wrong?

Groovy depends on JDK 1.4 or later. Common errors people have when trying to run Groovy is that there’s an old groovy jar on the CLASSPATH somewhere (have you checked in java/lib/ext?) or that JAVA_HOME points to an old JDK before JDK 1. For more help please see this description of running Groovy code.

How can I add stuff to the classpath when running things in groovysh or groovy?

You can add things to your $CLASSPATH environment variable. Another popular option is to create a .groovy/lib directory in your home directory and add whatever jars you want to be available by default. e.g. if you wish to connect to your favourite JDBC database and do some scripting with it then add your JDBC driver to ~/.groovy/lib.

Things work if I use Suns conventions and put { on the same line, but if I add a new line things break?

When using closures with method calls we have some syntax sugar in Groovy which is sensitive to white space (newlines to be precise). Please see this description in common gotchas for a full description.

Filed Under: Interview Questions Tagged With: Groovy

Templates in Groovy

April 6, 2008 by Krishna Srinivasan Leave a Comment

1) Introduction

In this article, we will expose the various APIs for processing Templates in Groovy. A template can be thought of some static content along with some well-defined place-holders. These templates can be re-used any number of times by simply copying it and substituting the place-holders with some appropriate values. The first section of the article concentrates on the various types of Template Engines available in Groovy. And the later section of the article guides you in using the Template API. This is not an introductory article about Groovy, so novice readers can read the introductory article Introductory Article on Groovy before continuing with this article.

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

2) Groovy Template API

2.1) Templates
As mentioned earlier, generally a template is a static content with well-defined placeholders. For example, consider the following,
‘[0] and [1] went up the hill’
The above content is an example of templated content which is having two place-holders pointed by [0] and [1]. Now this templated content can be re-used any number of times as following by substituting appropriate values,
‘Jack and Jill went up the hill’
‘Mary and Rosy went up the hill’

.
.
.

‘Somebody and Nobody went up the hill’

2.2) API Support

The necessary support for programming Groovy templates is available in the groovy.text package. This package can be logically broken into three pieces as follows,

  1. Representation of a template
  2. Template Engines

We will discuss in detail in the forth coming sections.

2.2.1) Representation of a template

Template in Groovy is represented by the interface groovy.text.Template. A template usually represents some text content and they are often associated with a set of bindings. The set of bindings contains the values for the template text containing place-holders.
Values can be passed to the template text by calling the Template.make(Map bindings) method.

2.2.2) Template Engines

Template Engines are Factory classes which are used to create Template objects from a variety of sources. The source can be as simple as an ordinary text, from a file or a reader or from an URL. For example, the following code snippet creates a Template object whose content will come from a file,

[code lang=”java”]File fileContainingTemplate = new File("template.txt");
TemplateEngine templateEngine = new SimpleTemplateEngine();
Template templateObject = templateEngine.createTemplate(fileContainingTemplate);[/code]

3) Code Samples

3.1) Simple Substitution

We will see how to make use of Groovy Template API for text manipulation. To start with, we will consider a simple example in the following code,
ValueInsertion.groovy

[code lang=”java”]import groovy.text.*

def day = [‘day’ : ‘Holiday’]
def message = "Today is ${day} ";

def templateEngine = new SimpleTemplateEngine()
def template = templateEngine.createTemplate(message)

Writable object = template.make(day)
println object[/code]

The above code declares a map object called day which has one entry (key and value). The key is 'day' and the value for the key 'day' is Holiday. Next the program creates a template like string object called 'message' whose value is 'Today is ${day}'. Note that this templated message has a single place-holder which is denoted by ${day}. We want this place-holder to replace with the value 'Holiday' whose value is taken from the map 'day'.
The next section of the code creates the Simple Template Engine for creating templates. Next, the template object is created for the message by calling the method, TemplateEngine.createTemplate(message). Note that till now a string object is made to look like a template object with place-holders. For passing values to the templated text, we have to call the method Template.make() by passing in a map of values as shown below,

[code lang=”java”]Writable object = template.make(day)[/code]

The return type of this method is a Writable object which will contain the substituted text. In our example, the binding expression in the template text as represented by ${day} and the key that we pass for making the template ['day' : 'Holiday'] should be one and the same.
The output for the above code is,

[code lang=”java”]Today is ["day":"Holiday"][/code]

3.2) JSP Syntax based Substitution

Another most common way of using place-holders is to use the JSP-based syntax for coding scriplets. For example, consider the following code,
SimpleTemplateText1.groovy

[code lang=”java”]import groovy.text.*

def templateMessage =
"Web site:" + "";

def values = [‘webSite’ : ‘www.javabeat.net’,
]

SimpleTemplateEngine templateEngine = new SimpleTemplateEngine ()
def template = templateEngine.createTemplate(templateMessage)

Writable writable = template.make(values)
println writable.toString()[/code]

In the above example, <%= expression %> has been used instead of ${object}. The rest of the code remains the same. However there are minor differences between these two expressions. In the former, the expression is evaluated and the value is inserted whereas in the latter case, the value of the object is directly inserted.
The output for the above code will be as follows,

[code lang=”java”]Web site:www.javabeat.net[/code]

3.3) Evaluating Groovy Code

In the above examples, we have seen that the Groovy Expression will be evaluated and the result will be inserted directly into the embedding text. Now, let us see how to evaluate Groovy expressions alone. Consider the example,
SimpleTemplateText2.groovy

[code lang=”java”]import groovy.text.Template
import groovy.text.SimpleTemplateEngine

def text = ‘Weather is here at ‘
def binding = [
"temperature" : "very cold",
"location" : "Bangalore"
]

def engine = new SimpleTemplateEngine()
template = engine.createTemplate(text).make(binding)

println template[/code]

In the above case, the object text has scripts in the following format '<% ... %>'. In such cases, the expression alone will be evaluated and the result wont be appended into the surrounding text. Here is the output of the above program,

[code lang=”java”]Weather is very cold here at Bangalore[/code]

3.4) Reading text from file

ReadTemplateTextFromFile.groovy

[code lang=”java”]import groovy.text.*
import java.io.*

def templateFile = new File(".\\src\\mydata.template")
def data = [
‘name’ : ‘Raja’,
‘designation’ : ‘Software Engineer’,
‘location’ : ‘Bangalore’,
]

def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(templateFile)
def writable = template.make(data)

println writable[/code]

Till now, we have seen that the Groovy template text is hard-coded directly into the source files. Now, let us see how to externalize the template text by keeping it in a file called 'mydata.template'. The content of the file is as follows,
mydata.template

[code lang=”java”]mydata.tempalte

${name}
${designation}
${location}[/code]

The above XML file has three place-holders for name, designation and location. Back to the source code, we have defined a map of values for these three identifiers like,

[code lang=”java”]def data = [
‘name’ : ‘Raja’,
‘designation’ : ‘Software Engineer’,
‘location’ : ‘Bangalore’,
][/code]

The file object is represented by the object 'templateFile' which is shown below,

[code lang=”java”]def templateFile = new File(".\\src\\mydata.template")[/code]

And this file object is passed to the template engine for reading the text content as follows,

[code lang=”java”]def template = engine.createTemplate(templateFile)[/code]

3.5) GString Template Engine

GStringTemplateText1.groovy

[code lang=”java”]import groovy.text.*

def templateText =
"Call me after \n" +
"We will meet on ";

def valuesForTemplate = [
‘time’ : ‘6.00 OM’,
‘day’ : ‘Sunday evening’
]

GStringTemplateEngine templateEngine = new GStringTemplateEngine()
def template = templateEngine.createTemplate(templateText)

Writable writable = template.make(valuesForTemplate)
println writable.toString()[/code]

Various Template Engines are available in Groovy for template processing namely SimpleTemplateEngine, XmlTemplateEngine and GStringTemplateEngine. Till now, we have been using SimpleTemplateEngine for simple cases and if we want to go for template processing with performance in mind, then GStringTemplateEngine will be a better choice. XmlTemplateEngine takes care of reading the template text and writing the substituted text from and back to the XML file for fine tuning purposes and it takes care of formatting also.

4) Conclusion

In this article, we have covered the Groovy Template API. The Template API is very short and simple and it can be used widely for text processing and substitution. In the beginning of this article, we happened to see about Templates along with examples. Following that, we have explored the Template API, along with classes and interfaces with Groovy. To get a feel over the API, this various samples have been provided in the later end of the article.
The following are some of the popular articles published in Javabeat. Also you can refer the list of groovy articles and groovy books from our website. Please read the articles and post your feedback about the quality of the content.

  • Creating JSON using Groovy
  • Introduction to Groovy Server Pages (GSP)
  • Introduction to groovy

If you are interested in receiving the future java articles from us, please subscribe here.

Filed Under: Groovy Tagged With: Groovy, Templates in Groovy

Closures in Groovy

April 5, 2008 by Krishna Srinivasan Leave a Comment

1) Introduction to Groovy Closure

In this article, let us look into one of the important features supported in Groovy, the Closures. Groovy is an object-oriented scripting language in which the syntax resembles Java. Not all languages support the concept of Closures directly, although they may provide indirect support, that too with so many limitations and restrictions. This article will make you familiar with the concepts of Groovy Closures and will provide considerable amount of code snippets to make the understanding clearer. This article assumes that the reader is having sufficient knowledge in Groovy Programming and first-time readers may look into the Introductory Article on Groovy before proceeding with this article.

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

2) Closures

To say in simple words, a Closure definition is a block of code that can be re-used any number of times. The definition may look more or less like the definition of a function or a method. A Closure resembles a function or a method in many aspects, however there are subtle differences between them. For example, a Closure may take any number of arguments like a function. A Closure has a return value like a method. A closure can be re-used and referenced any number of times and anywhere similar to a method.
It is clear that a Closure is very similar to a function in many aspects, but the difference is that a Closure can be passed as an argument to a function. A programming language like Java supports similar kind of Closures through anonymous Inner classes. For example, consider the following piece of code,

[code lang=”java”]Button button = new Button();
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent actionEvent)
{
// Do something here.
}
});[/code]

In the above code, the method Button.addActionListener() will take an argument of type ActionListener. We have defined something which is of type ActionListener and has included a method actionPerformed() within it. This type cannot be used elsewhere in the code since we don’t have any reference to it. One possible way to re-use the reference is to have something like the following,

[code lang=”java”]ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent actionEvent)
{
// Do something here.
}
};

Button button = new Button();
button.addActionListener(actionListener);[/code]

To understand the need to have Closures, let us analyze the situation in this way. You have some simple piece of logic (such as printing the state of an object) and you want this logic to be re-used by some common group of objects. The more traditional way to arrive at the solution for this problem is to define a method with suitable argument list and then to call this method. However, in an object-oriented programming language like Java, methods doesn’t exist on their own. They have to be embedded within a class. It doesn’t look nice to create a new type (in the form of a class) and to embed a simple behavior in the form of a method. This is where Closures come in. They are simply a named type for some set of statements containing some useful logic. The named type can then be re-used any number of times.
The same problem exists with callbacks. Classes with the design of call-backs in mind, usually have a well-defined interface along with methods. And the client application (or the caller) has to define an implementation class conforming to the interface which often results in defining new types. This will result in the many smaller classes in the Application. One form of solution to these kind of problems is manifested in the form of Closures.

3) Groovy Closures

3.1) Simple Closures

Let us look into the syntax for defining and making use of Closures. The syntax of a closure definition looks like this,

[code lang=”java”]ClosureName =
{
Parameter List -&gt;

Set of statements.
}[/code]

The syntax is simple (although it may not look like that at the very first glance). Let us get into the example. If we want to define a closure called 'helloClosure', then we can define something like this,

[code lang=”java”]helloClosure =
{
println "Hello";
}[/code]

Note that in the above definition, the closure name is 'helloClosure' and since we don’t want this closure to accept any parameters, we have left the list of parameters that should follow after the brace '{' as blank. Next follows the block section which may contain any number of statements.
Let us look into the following sample,
SimpleClosure.java

[code lang=”java”]public class SimpleClosure
{
def testClosure =
{
println "Test Closure";
}

public static void main(String[] args)
{
ClosureTest object = new ClosureTest();
object.testClosure();
}
}[/code]

We have defined a closure called 'testClosure' with the 'def' (meaning for definition) keyword. This closure doesn’t accept any arguments. Simply defining the closure doesn’t provide any purpose unless someone calls that explicitly. In the main method, we have created an object for the class 'SimpleClosure' and have invoked the closure 'testClosure' in function-like syntax.

3.2) Closures with Arguments

In this section, let us see how to define Closures that takes arguments. As we have already seen, Closures, like functions may take any number of arguments. For example, consider the following code snippet,
ClosureWithArguments.java

[code lang=”java”]public class ClosureWithArguments
{
def addClosure =
{
int one, int two -&gt;

println "Number one is " + one;
println "Number two is " + two;
return one + two;
}

public static void main(String[] args)
{
ClosureWithArguments object = new ClosureWithArguments();
def result = object.addClosure(10, 20);
println "Result from closure is " + result;

result = object.addClosure(130, 230);
println "Result from closure is " + result;
}
}[/code]

In the above code, we have defined a closure called 'addClosure'. Note the parameter list (int one, int two) that is following after the brace '{'. Following that is the symbol ‘->’ which is used as a separator between the parameter list and the set of statements to follow. The code prints the arguments passed to this function before returning the result.
The caller (main method) calls this Closure using the same function-like syntax passing two arguments.

3.3) Different ways of calling a Closure

We have seen how to invoke or call a Closure in the above sections. For example, if the Closure Name is 'myClosure', then this closure can be invoked through the expressioin 'myClosure()'.
CallingClosures.java

[code lang=”java”]public class CallingClosures
{
def testClosure =
{
println "Test Closure";
}

public static void main(String[] args)
{
CallingClosures object = new CallingClosures();
object.testClosure();
object.testClosure.call();
object.testClosure.doCall();
}
}[/code]

However, there are other alternative ways of calling a Closure as mentioned above. Every closure has default methods (implicit methods, so no need to declare them) namely call() and doCall() so we can also call the closures in this manner.

3.4) The Closure class

It should be noted that all Closure definitions will be resolved to some Java class at run-time. So all Closures are just like any other objects. And it is not surprising that the class name of such closure objects seems to be 'Closure'. It means that the following code will work fine.
ClosureClassTest.java

[code lang=”java”]public class ClosureClassTest
{
def testClosure =
{
println "Test Closure";
}

public static void main(String[] args)
{
ClosureClassTest object = new ClosureClassTest ();

Closure closureObjectForTest = object.testClosure;
closureObjectForTest();
closureObjectForTest.call();
closureObjectForTest.doCall();
}
}[/code]

The above code tries to assign the closure 'testClosure' to the object 'closureObjectForTest' which is of type 'Closure'. This is perfectly legal, since all Closure objects are of type 'Closure'.

3.5) Closure Currying

At times, we may need to create multiple number of Closure objects whose argument lists to some extent will be similar. For example, consider the following Closure 'getNoOfRuns' which takes two arguments, one is the name of the country and the other one being the name of the player. And we wish to make Closure calls four times with the following values,

  • Country-> India, PlayerName-> Sachin
  • Country-> India, PlayerName-> Ganguly
  • Country-> Pakistan, PlayerName-> Afridi
  • Country-> Pakistan, PlayerName-> Salman

Examine the first two set of invocations. Both are taking the value 'India' as the first argument. And in the 3rd and the 4th invocation, the argument value 'Pakistan' is common. Now, analyze the following code where we will see a better way of making invocations to the Closure.
ClosureCurrying.java

[code lang=”java”]class ClosureCurrying
{

def getNoOfRuns =
{
String country, String playerName -&gt;

if (country.equals("India"))
{
if (playerName.equals("Sachin"))
{
return 15806;
}
else if (playerName.equals("Ganguly"))
{
return 11319;
}
}
else if (country.equals("Pakistan"))
{
if (playerName.equals("Afridi"))
{
return 5226;
}
else if (playerName.equals("Salman"))
{
return 1159;
}
}
return -1;
}

public static void main(String[] args)
{
ClosureCurrying object = new ClosureCurrying();

def indianTeam = object.getNoOfRuns.curry("India");

def result = indianTeam("Sachin");
println "No. of runs scored by Sachin " + result;

result = indianTeam("Ganguly");
println "No. of runs scored by Ganguly " + result;

def pakistanTeam = object.getNoOfRuns.curry("Pakistan");

result = pakistanTeam("Afridi");
println "No. of runs scored by Afridi " + result;

result = pakistanTeam("Salman");
println "No. of runs scored by Salman " + result;
}
}[/code]

We have referenced the Closure 'getNoOfRuns' and has called the method 'curry()' on that with the value 'India' as its argument. Let us imagine that the method 'curry()' will create a new object with the countryName being set to 'India'. Now if want to get the number of runs for the player 'Sachin', then simply invoke the Curried Closure (the Closure that was obtained after calling the 'curry()' method) with the value 'Sachin'. The same applies for 'Ganguly' and for the rest of the players.

3.6) Closures as Arguments to another Functions

Till now, we have seen how to define and call Closures. In this section, we will see how to pass a Closure as an argument to some other function. Consider the following code snippet,
PassingClosuresTest.java

[code lang=”java”]class PassingClosuresTest
{

def testClosure =
{
println "Test Closure";
}

void acceptClosure(Closure closure)
{
closure.call();
}

public static void main(String[] args)
{
PassingClosuresTest object =
new PassingClosuresTest();
Closure closureObject = object.testClosure;
object.acceptClosure(closureObject);
}
}[/code]

In the above sample, we have defined a Closure called 'testClosure' and have defined another method which is taking an argument of type 'Closure'. In the main method, we have assigned the 'testClosure' to the object 'closureObject' which is of type 'Closure' and the same is passed to the method 'acceptClosure()' method.

3.7) Making use of Closures

In this section, let us make use of Closures being passed as arguments. For example, consider the following Class which wraps the string array objects. The decorate() method accepts an argument of type 'Closure'. The logic within the method iterates over the strings and the Closure being passed as argument to this method is invoked by passing the iterated resultant string object itself as argument.
DecoratedStringArrayClosureTest.java

[code lang=”java”]class DecoratedStringArrayClosureTest
{
def strs = null;
public DecoratedStringArrayClosureTest(def strs)
{
this.strs = strs;
}

public void decorate(Closure closure)
{
for (String temp in strs)
{
closure.call(temp);
}
}

def DecoratedClosure =
{
String element -&gt;
println "##" + element + "##";
}

public static void main(String[] args)
{
def numbers = ["one", "two", "three"];
DecoratedStringArrayClosureTest object =
new DecoratedStringArrayClosureTest(numbers);

Closure decoratedClosureObject = object.DecoratedClosure;
object.decorate(decoratedClosureObject);
}
}[/code]

The Decorated Closure decorates the string passed to it by surrounding the string with ‘#’ symbols.

4) Conclusion

In this article, we understand the need for Closures and saw how Closures stand as a better replacement for defining a new type even for simpler cases. We also dealt in detail about the various usage cases of Closures in Groovy Scripting Language along with plenty of code samples.
The following are some of the popular articles published in Javabeat.Please read the articles and post your feedback about the quality of the content.

  • Creating JSON using Groovy
  • Introduction to Groovy Server Pages (GSP)
  • Introduction to groovy

If you are interested in receiving the future java articles from us, please subscribe here.

Filed Under: Groovy Tagged With: Closures, Closures in Groovy, Groovy

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved