Groovy Programming Cookbook
Groovy Programming Cookbook
Contents
Preface
Apache Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar
to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform, is dynamically
compiled to Java Virtual Machine (JVM) bytecode, and interoperates with other Java code and libraries. Groovy uses a Java-like
curly-bracket syntax. Most Java code is also syntactically valid Groovy, although semantics may be different.
Groovy 1.0 was released on January 2, 2007, and Groovy 2.0 in July, 2012. Since version 2, Groovy can also be compiled
statically, offering type inference and performance very close to that of Java. Groovy 2.4 was the last major release under Pivotal
Software’s sponsorship which ended in March 2015. Groovy has since changed its governance structure to a Project Management
Committee (PMC) in the Apache Software Foundation. (Source: https://bit.ly/2bIoaO4)
In this ebook, we provide a compilation of GWT examples that will help you kick-start your own projects. We cover a wide
range of topics, from sample applications and interview questions, to Callback functionality and various widgets. With our
straightforward tutorials, you will be able to get your own projects up and running in minimum time.
Groovy Programming Cookbook viii
JCGs (Java Code Geeks) is an independent online community focused on creating the ultimate Java to Java developers resource
center; targeted at the technical architect, technical team lead (senior developer), project manager and junior developers alike.
JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by domain experts, articles, tutorials, reviews,
announcements, code snippets and open source projects.
You can find them online at https://www.javacodegeeks.com/
Groovy Programming Cookbook 1 / 75
Chapter 1
In this article we will see how easy it is to write scripting in Groovy, with a practical example that serves a common use case.
As you would probably know, Groovy is a JVM Language which is defined to run on top of Java Virtual Machine. Having said
that it borrows all Java’s capabilities alongside providing its own extra features to simplify the tasks of the developers to achieve
things in a easy and efficient manner.
Pre-requisite: The readers are expected to have a good exposure on Java programming language and the basic SQL (like table
creation, inserting and reading values from a table etc.,) alongside a beginner level introduction to the Groovy at least to start
off with. However we will cover the required aspects of the elementary semantics of Groovy, wherever required during the flow.
You can read a good set of introductory tutorials of Groovy here.
1.1 Environment
The examples shown below are executed in the Command Prompt / Shell and the GroovyConsole. But they are guaranteed to
work with any of the IDEs (like Eclipse, IntelliJ IDEA, Netbeans) through the respective plugins. The examples are executed
with the Groovy Version Groovy Version: 2.4.3.
For our example Order Processing System, we will use MySQL open source database. We use MySQL V 5.6 for Windows, with
JDBC driver for MySQL - MySQL JDBC Connector 5.1.29.
Script is an executable program which is accomplished to automate the mundane tasks in a simple and easy manner that requires
a minimal or no human intervention thereby resulting in time saving. However there are various scripting languges and tools with
their owns pros and cons depending on the features they have to offer, the simplified syntax they have in store, the limitations
they have by nature etc.,
In general, the scripting languages have one thing in common - their simplified syntax and ease of use as that is the main attracting
point to the users (or developers) who aims to get the job done quickly and efficiently.
Groovy is a programming language which can be used as a Scripting language due to its very simplified syntax which is very
easy to use. If you are an experienced Java professional for more than 5 years and have explored Groovy for sometime, you
would undoubtedly agree with the above statement.
We will see an example of an Order Processing System where we will get the details related to an order in a flat file (a pipe
separated / delimited) file where each line contains the information pertaining to an order. We will parse (read and process) the
line entries from the file and add an Order for each line into the Database to store it permanently.
Groovy Programming Cookbook 2 / 75
For the sake of our example, imagine a system that dumps such a flat file in our file system at regular intervals. Our Groovy
Script will continuously monitor the same directory in the file system at regular intervals for the new files. Upon finding the files,
it will process them and move the files into a different directory, so as not to process them in the next iteration.
We will be using Groovy language basics for covering this example like String Concatenation, Collections - List and Map, File
Handling, SQL Handling etc., You may please check the References section at the bottom of this article to have a quick glance
on each of the topics to facilitate your understanding of scripts.
For our order processing script, we will do the following in order as a step by step approach.
• Business Model (Domain Object) - We will create a Domain Object (Business Object) to carry all the information of an order
as a single entity, otherwise it will be tedious and an overhead if we were to pass all the individual attributes of an order. It is a
common practice to wrap all the relevant attribute into an Object of a corresponding class. In Java, it is called as POJO (Plain
Old Java Object) where in Groovy it is called as POGO (Plain Old Groovy Object).
• Application Business Scripts - We will write a few simple Groovy scripts for creating random Order entries and write them
into a delimited file (pipe separated) in a directory so that our Database scripts will be able to parse (read and process) them
for inserting them into Database.
• Database Scripts - We will write a few simple Groovy Scripts to interact with the database for creating a Database Table,
reading the records from the table, truncating the table (wiping off the records), dropping a table etc., with a help of a JDBC
Driver (MySQL JDBC Connector).
In this section, we will write a few simple Groovy Scripts pertaining to the business purpose.
This is a very essential script that carries the class structure for a POGO (Plain Old Groovy Object) to have the essential properties
of an Order - like the Order Id, Date, Customer Name, Currency, Price, Country, Payment Mode etc.,
We need to carry all the properties of an Order in a single entity - which is a Wrapper Object. It is also called as BO (Business
Object) or a DTO (Data Transfer Object) - due to its nature of transferring the data from one layer to another within an application.
We will need to create as many as objects based on the number of order entries. The ratio between the order entry in a flat file Vs
the Order POGO instance will be 1:1.
The following Groovy scripts has different member variables for each of the Order attributes/properties plus few methods to be
used for a common usage - like toString() to print the state of an object in a meaningful manner, initOrder() - a method
to initialize an object with a line of text being read from the text file etc.,
Please remember the fact that Groovy does not really mandate the presence of a semicolon at the end of every executable
statement as in Java. This is one of the many significant ease of uses of Groovy.
All the scripts in this article will be under a package com.javacodegeeks.example.groovy.scripting which helps
us to organize all the related classes and scripts in a same folder/directory (which is called as a Package in Java’s term).
We will compile this Groovy class using groovyc Order.groovy so that the compiled .class file gets generated in a folder
matching with com/javacodegeeks/example/groovy/scripting in the present directory. It will be referred by other
scripts to load the Order class.
Order.groovy
Groovy Programming Cookbook 3 / 75
// package statement should be the very first executable statement in any script
// packaging helps us to organize the classes into a related folder
package com.javacodegeeks.example.groovy.scripting
/**
* A POGO (Plain Old Groovy Object) used as a DTO (Data Transfer Object)
* or a BO (Business Object) which will carry the essential particulars
* of an Order
*/
class Order
{
/** Self explanining fields and the default values for the few */
//unique value from Database to denote a particular order
def id = 0
def customerName, country=’India’, price
def currency=’INR’, paymentMode=’Cash’
def orderDate // will be the current time in DB during insert
/**
* A method to format the value with the specified pattern (format),
* useful in having a fixed width while displaying in Console
*/
def String format(format, value)
{
String.format(format, value)
}
/**
* A method to parse a line of text and initialize an Order instance
* with the parsed tokens
*/
def initOrder(strAsCSV)
{
// tokenize() will split the line of text into tokens, and trimmed to
// remove the extra spaces if any
// the tokens are assigned to the variables in order - as per
// the declaration on the left side
this.customerName=nameParsed
this.country=countryParsed
this.price=priceParsed
this.currency=currencyParsed
this.paymentMode=modeParsed
return this
}
/**
* An overridden toString() method of this Order class to have a
* meaningful display wherever it is invoked (which otherwise
* will be a typical hashcode and the classname)
*/
def String toString()
{
//preparing the output in a fixed width format via format() method defined above
def output = String.format("%-15s", customerName) + " | " +
String.format("%-10s", country) + " | " + String.format("%-8s", price) + " | " ←-
+
Groovy Programming Cookbook 4 / 75
// add the Id if it is valid (not zero - meaning it was inserted in the database)
if(id!=0)
output = String.format("%-5s", id) + " | " + output
output
}
}
Let us just quickly test the Order.groovy to ensure that this class behaves as expected. This will be very important to complete
one module perfectly so that we can be comfortable in proceeding with the rest of the scripts. This is the best and recommended
practice for the correctness of the script execution.
This script will have 3 different Order instances created and printed on the screen. The script has a self explaining comment at
every other step.
TestOrder.groovy
package com.javacodegeeks.example.groovy.scripting
/**
* A straight forward way to instantiate and initialize an Order instance
* Field name and value is separated by a colon (:) and
* each name value pair is separated by a commma (,)
*/
def order = new Order(customerName: ’Raghavan’, country : ’India’, id : ’1’,
price : ’2351’, currency: ’INR’, paymentMode : ’Card’)
println order
/**
* Another approach to initialize the Order instance where
* one property or field is intialized during instantiation (invoking the constructor)
* and rest of the properties are initialized separately
*/
def order2 = new Order(customerName: ’Kannan’)
order2.country=’Hong Kong’
order2.id=’2’
order2.price=’1121’
order2.currency=’HKD’
println order2
/**
* Yet another way to initialize the Order instance with one complete line of formatted ←-
line
* pipe separated values ("|")
*/
def lineAsCSV = "Ganesh | Hong Kong | 1542.99 | HKD | Cheque |"
def order3 = new Order().initOrder(lineAsCSV)
println order3
The output in each line consists of the different pieces of an Order each separated by a pipe character. The output being displayed
is generated out of the toString() method of the Order.groovy class. The fields displayed are Order Id (if not null),
Customer Name, Country, Amount, Currency, Payment Mode
The first two instances are having the order Id because it was given during the instantiation. However the 3rd order instance did
NOT have the Order Id and hence the output is slightly different from the first 2 instances. The 3rd instance is very important
because the actual lines in the flat file will resemble the same as we will not have the order Id at first. It will be created after
inserting the record into database, as it should be typically an auto-generated Id.
Now that we have made our Business Object - Order.groovy and we had also tested that successfully, we will proceed further
with the next step. We will create some random Order instances and write them into a text file in a delimited - pipe separated
format.
This class have all few set of names, country and currencies, amounts and payment modes in separate data structures (List and
Map) - using which we will pickup some values at random to constitute an Order instance. We will generate a random number
to be used as an index (pointer) to the corresponding data structure.
This script will generate a set of entries based on a max limit that is configured in the script itself - noOfRecords, which can be
passed as a command line argument if needed. Otherwise this will have a default value of 5 - meaning 5 entries will be generated
and stored in a text file.
TestOrderRandomBulk.groovy
package com.javacodegeeks.example.groovy.scripting
int noOfRecords = 5
for(int i = 0; i
writer.writeLine outputToWrite
}
println ""
println "Contents are written to the file -> [$fileName] in the directory [$baseDir]"
println ""
Contents are written to the file -> [outputTest.txt] in the directory [outputFiles]
***********
== COMPLETED ==
***********
As you see, the script produced 5 different Order Instances with random values picked up from the respective data structure and
stored each Order instance as a pipe separated values. Each order instance was accumulated and all the lines were stored in a text
file - outputTest.txt in the directory outputFiles.
At the end of the script, we had read the same file outputTest.text and printed the contents of the file into screen - for our
quick and easy verification.
We saw how to write a script to write a set of Order Instances into a text file. We will see how to generate a similar set of random
entries at regular intervals by making the script sleep for a while in between. This is to simulate a real time environment where
one system will be dumping the flat files at regular intervals in a shared location where the other system will be watching the files
for processing further.
For the sake of brevity, we will make our script execute 2 iterations where each iteration will generate 5 random Order instances
and store them in a separate text file whose names will have the timestamp appended for distinguishing with each other.
Groovy Programming Cookbook 7 / 75
The script will generate the files in outputTest.txt_count_<yyyyMMdd_HHmmss> pattern. We have an utility method
getNow() to give the present date and time in the prescribed format, which we will call everytime while writing to a new file.
The output file will be written in the same directory, which will be processed by a next database script which, after processing
will move the file into a different target directory to avoid these files being reprocessed in the subsequent iterations.
As usual the script below has a good documentation at every step that will be self explanatory for the readers to follow along.
TestOrderRandomInterval.groovy
package com.javacodegeeks.example.groovy.scripting
def getNow() {
new Date().format("yyyyMMdd_HHmmss")
}
println ""
// interval to let this script sleep (1000ms=1s, here it will be for 1 min)
def SLEEP_INTERVAL = 1000*60*1;
for(int i = 0; i
writer.writeLine outputToWrite
}
println getNow() + " : Contents are written to the file -> [$fileName] in the directory ←-
[$baseDir]"
println ""
println getNow() + " ...... Script will sleep for ${SLEEP_INTERVAL} milliseconds [1000 ←-
ms=1s]......"
println " "
sleep(SLEEP_INTERVAL)
println getNow() + " .............. Script awaken ......................"
println ""
}
***********
== COMPLETED ==
***********
As explained above, the script had produced two different flat (text) files with the pattern outputTest.txt_ with a sequence number
along with the date and time pattern to distinguish the files from each other. We had also retrieved the file contents and displayed
in the console for our quick verification.
We will see in the next subsection how to process these order entries for storing them into the database.
We have completed our scripts for producing the flat files to cater to the business needs. Now we need a place to store the data
values into a permanent storage - a Database. Like how we created a main POGO Order.groovy to use it as a Business
Object for our business oriented scripts, we need a database table to store the specific attributes of an Order, which were carried
in an instance of Order class.
We will see in the subsequent sub-sections how we will write the simple groovy scripts to create a database table, insert or store
values into the table, retrieve the values from the table, truncate (or wipe off the entries) from the table for us to clean and start
over again, drop the database etc.,
Please ensure you have the MySQL database installed in your machine and you have the MySQL JDBC Connector Jar file
before you proceed with the rest of the scripts in this section.
You may read a suitable tutorial or the MySQL website for installing the database in to your machine.
A database is a different entity and it needs to be connected to before we could actually do any operation with it. After finising
our operation we should close the connection as a best practice so that the database can support further clients and connections
in a better manner.
We need certain important properties about the database like the Server IP Address or hostname where the database is running,
the port number to which the database service is listening for client requests, the database type - like Oracle, DB2, MySQL
etc., , the actual name of the database we need to connect to, the JDBC (Java Database Connectivity) driver url using which the
underlying Java based Programming Language will talk to the database.
As we will have a few different scripts dealing with the database and each of them will need the same properties, it is better
to capture them in a separate file and be it referred in all the relevant scripts whichever needs those properties. The advantage
of doing this practice is if at all we need to make a change in any of the properties, we can do so in a single place rather than
changing in all the files where it was referred individually.
Before we could write the separate database related scripts, we should see the configuration file (or a properties file in Java
terminology) as to how we can store the values. The below db.properties stores the properties in a key,value pair
where each pair is entered in a separate line and each key value pair is stored in the format key=value, where key is the actual
key we will be referring to pick up the value from the file and the value is the actual value of the property.
Groovy Programming Cookbook 10 / 75
The configuration file can be of any extension but it is a standard practice to have it stored in the meaningful .properties
extension.
The lines starting with a # will be treated as a comment and will be ignored. It is more like a // in a Java like Programming
language to indicate a meaningful description or a comment.
db.properties
# Properties needed to construct a JDBC URL programmatically inside a script
db.type=mysql
db.host=localhost
db.port=3306
db.name=test
# Username and password for authenticating the client everytime a database connection is ←-
obtained
db.user=root
db.pwd=root
# The JDBC Driver class that needs to be loaded from the classpath (mysql-connector-x.y.z. ←-
jar)
# which does the actual talking to the database from within the Java based Programming ←-
language
db.driver=com.mysql.jdbc.Driver
We will write a script to parse the database configuration file so that we can read and process the values and get them stored in
to respective variables of a class. This way we can use these variables from the class any number of times we need, otherwise
we may need to read it from the configuration file which is typically be slow and a time consuming operation when compared to
reading it from the Groovy object variable.
The below Groovy script will read the configuration file from the file system and parse the values and store them into respective
variables. To make it efficient reading, we read them through static initializer blocks which will be executed only once during
the class loading time. The values read will be retained until the script completes its execution or the JVM shuts down. Just to
verify the properties being read, we will print them in the console via a helper method called printValues().
We will compile this Groovy class using groovyc DBProps.groovy so that the compiled .class file gets generated in a
folder matching with com/javacodegeeks/example/groovy/scripting in the present directory. It will be referred
by other scripts to load the Order class.
dbProperties.groovy
package com.javacodegeeks.example.groovy.scripting
class DBProps
{
// meaningful class level variables for each of the db properties
static String dbType, dbHost, dbPort, dbName, dbUser, dbPwd, dbUrl, dbDriver, dbTblName
//static initializer block (gets invoked when the class is loaded and only once)
static
{
Groovy Programming Cookbook 11 / 75
static printValues()
{
println "Db Type : " + DBProps.dbType
println "Db Name : " + DBProps.dbName
println "Db Host : " + DBProps.dbHost
println "Db Port : " + DBProps.dbPort
println "Db User : " + DBProps.dbUser
println "Db Pwd : " + DBProps.dbPwd
println "Db URL : " + DBProps.dbUrl
println "JDBC Driver : " + DBProps.dbDriver
println "Table Name : " + DBProps.dbTblName
}
}
As you see, the values read from the configuration / properties file were stored into a respective variables of a class, which will
be referred in different other scripts for the efficient and ease of use.
We will now write a Groovy script to create a database table GroovyScriptTest to capture the Order related information
for our example. This table will have a placeholder to store every bit of information about our Order - as we discussed in
Groovy Programming Cookbook 12 / 75
Business Object in the Order.groovy. However the data types and declaration in the database may be little different from the
Programming language(s).
For executing the database scripts, you should specify the directory where the MySQL JDBC Jar file is present, as a classpath
option while invoking the groovy script. For example, to invoke the below script the command should be groovy -clas
spath C:commonj2eelibsmysql-connector-java-5.1.29-bin.jar dbCreateTable.groovy, where the
mysql jar file mysql-connector-java-5.1.29-bin.jar is present in the directory C:commonj2eelibs
dbCreateTable.groovy
package com.javacodegeeks.example.groovy.scripting
sql.execute ’’’
CREATE TABLE ’’’ + tableName + ’’’
(
Id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(30),
COUNTRY VARCHAR(20),
PRICE FLOAT(8,2),
CURRENCY VARCHAR(3),
PAYMENT_MODE VARCHAR(10),
ORDER_DATE DATETIME DEFAULT CURRENT_TIMESTAMP
);
’’’
The above script created a table named GroovyScriptTest in the MySQL database named test with the columns Id being
auto-generated primary key (unique value per row), Name of String datatype with maximum 30 characters limit, country of String
datatype of maximum 20 characters limit, price of floating data type of 8 digits with 2 digits for precision, currency as a String
datatype of 30 characters limit, Payment_Mode of String datatype of 10 characters limit and Order_date of datetime datatype
with the default value of the current date and time in the System, if not specified.
Now that we had created a table in the MySQL database, let us write/ insert some data into the table from a flat file. We had
already executed a script TestOrderRandomBulk.groovy where it had produced a flat file outputTest.txt in the
directory outputFiles. The below script dbInsertValueSingleFile.groovyy will read the same flat file and insert
into the GroovyScriptTest table.
Groovy Programming Cookbook 13 / 75
dbInsertValueSingleFile.groovy
package com.javacodegeeks.example.groovy.scripting
import groovy.sql.Sql
def baseDir="./outputFiles"
def fileName = ’outputTest.txt’
// a list to hold the list of valid (non-empty) lines in the flat file
def list = new File(baseDir, fileName).readLines()*.trim()
def orderList = []
list.each { it ->
// Consider ONLY the non-empty lines in the flat file
if(it.trim().length() > 0)
orderList.add(new Order().initOrder(it))
}
***********
== COMPLETED ==
***********
Groovy Programming Cookbook 14 / 75
The above script successfully read the flat file and inserted each line as a separate Order entry in the database table. The output
confirmed that there were 5 Order instances successfully inserted.
Let us verify the values inserted in the database table with another script as discussed in the next subsection.
Let us write a simple Groovy script to get the total number of rows present in the database table.
dbSelectTotal.groovy
package com.javacodegeeks.example.groovy.scripting
import groovy.sql.Sql
def totatlRows
Let us write yet another Groovy script to retrieve all the rows available in the GroovyScriptTest database table.
dbSelectRows.groovy
package com.javacodegeeks.example.groovy.scripting
import groovy.sql.Sql
def totalRows
query=’’’
Select
Id, Name, Country, Price, Currency, Payment_Mode, Order_Date
from
’’’ + tableName
// declare the individual variables to hold the respective values from database
def id, name, country, orderNo, price, currency, mode, orderDate
// a variable to hold an Order Instance prepared out of the values extracted from database
def order
sql.query(query) { rs ->
while(rs.next())
{
// extract each field from the resultset(rs) and
// store them in separate variables
id = rs.getString(1)
name = rs.getString(2)
country = rs.getString(3)
price = rs.getString(4)
currency = rs.getString(5)
mode = rs.getString(6)
orderDate = rs.getString(7)
******************************************************************
Id | Customer Name | Country | Price | Currency | Payment Mode | Order Date ←-
|
******************************************************************
1 | Manoj | USA | 9877.12 | USD | Cheque | 2016-04-15 ←-
16:53:14.0 |
2 | Jhanani | Canada | 4567.00 | CAD | Cash | 2016-04-15 ←-
16:53:14.0 |
3 | Kanna | Singapore | 9877.12 | SGD | Card | 2016-04-15 ←-
16:53:14.0 |
4 | Karthiga | Saudi | 9877.12 | SAR | Cash | 2016-04-15 ←-
16:53:14.0 |
5 | Saravanan | Australia | 8998.11 | AUD | Cheque | 2016-04-15 ←-
16:53:14.0 |
******************************************************************
As you see, the above script extracted all the 5 rows from the database table and created a separate Order Instance using the
values, in an iteration. All those Order instances were printed with the help of toString() method that helps us to get the
values of an Order Instance with a fixed width - to have a better visual aid while displaying. The values are displayed with the
headers to make it meaningful to indicate which value belongs to which column.
Please observe the values for Id column where it is in sequence starting from 1 to 5. It was because we declared the syntax for
the column while creating the database table as an auto generated, identity column.
Now we had successfully inserted the records from a single flat file and also verified the total record count plus extracted all the
rows available in a table. We will enhance the script further to make it process the files in iteration at regular intervals while
letting the script sleep for a while. The duration for sleeping, number of iterations are configured in the script.
Note: This script will look for the files with the matching pattern outputTest.txt_count_<yyyyMMdd_HHmmss> which
were generated out of the script TestOrderRandomInterval.groovy
Groovy Programming Cookbook 17 / 75
For the brevity, the script will process two iterations and will exit. However, to make it execute indefinitely, you can make the
while loop as follows.
while(true) {
...
}
dbInsertValueInterval.groovy
package com.javacodegeeks.example.groovy.scripting
import groovy.sql.Sql
import groovy.io.FileType
// an utility method to print the current date and time in a specified format
def getNow()
{
new Date().format("yyyyMMdd_HHmmss")
}
while(i++
fileName = file.name
fileNameMatches = false
if(fileName.startsWith(fileNamePattern))
{
println "Processing the file -> $fileName"
fileNameMatches = true
}
if(fileNameMatches)
{
// store all the lines from a file into a List, after trimming the spaces on ←-
each line
list = new File(baseDir, fileName).readLines()*.trim()
orderList = []
// Process only the valid (non-empty) lines and prepare an Order instance
// by calling the initOrder() method by passing the pipe delimited line of text
list.each { it ->
Groovy Programming Cookbook 18 / 75
if(it.trim().length()>0)
orderList.add(new Order().initOrder(it))
}
println ""
println getNow() + " ... script will sleep for ${SLEEP_INTERVAL} milliseconds..."
println ""
sleep(SLEEP_INTERVAL)
println getNow() + " ......... script awaken ........ "
println ""
}
*******************************************************------------
20160415_172226 =========== SCANNING for files matching with outputTest.txt_ ←-
===================
*******************************************************------------
*******************************************************------------
Groovy Programming Cookbook 19 / 75
***********
== COMPLETED ==
***********
You can verify the total values inserted by executing the dbSelectRows.groovy where it will display all the rows in the
table with a fixed width column for each of the values as we saw in section 6.6.
We will also see a Groovy Script to truncate the database table. Truncating helps to retain the table structure but wipe off (delete)
all the rows in the table. It will be helpful whenever you want to start the operations afresh from the beginning.
Once the table is truncated successfully, you can insert the values again, for which the auto-generated Id value will start from 1.
dbTruncateTable.groovy
package com.javacodegeeks.example.groovy.scripting
import groovy.sql.Sql
At times we need to drop the table to start everything afresh. Let us write a simple Groovy script for dropping the table from the
database.
Once the table is dropped successfully, you need to recreate the table by executing the script dbCreateTable.groovy before
you can insert the values.
dbDropTable.groovy
package com.javacodegeeks.example.groovy.scripting
import groovy.sql.Sql
1.7 Conclusion
Hope you had enjoyed this article - Groovy Script Tutorial for Beginners. In this article we have seen how to write simple Groovy
scripts to create a Business Object, generate random Order entries, write them into a text file, read the flat file and parse the order
entries, read a property/configuration file for the database related values, create a database table, store values into a table, read
the values from the table, truncate and drop the table.
Though the article aimed at a practical scenario, there may be few different conditions and best practices for a requirement if any
different you have at hand. In such case, you are required to go through the documentation of the respective language constructs
for a better scripting.
You may please refer the following URLs for further reading.
This is an example of how to write scripting in Groovy, tested with the Command Prompt / Shell and Groovy Console against
Groovy Version 2.4.3.
Download
You can download the full source code of this example here: Groovy Scripting Tutorial. Please read the ReadMe.txt file for
how to execute the scripts.
Groovy Programming Cookbook 21 / 75
Chapter 2
In this article we will see how to have a Dictionary in Groovy. Groovy does not have a built in dictionary like Python language.
However we can use the Map data structure for manipulating a Dictionary.
To understand this article, the reader should have a better understanding of how Map works in Groovy. You can read this
Groovy-Map-Example for the same.
2.1 Environment
The examples shown below are executed in the Command Prompt / Shell. But they are guaranteed to work with any of the
IDEs (like Eclipse, IntelliJ IDEA, Netbeans) through the respective plugins. The examples are executed with the Groovy Version
Groovy Version: 2.4.3.
Ideally a Dictionary is a Collection of things being stored under a key-value pair and that can be retrieved quickly anytime on
demand. Though we would achieve the Dictionary via a Map, we need to have few boundaries set.
A Map will allow a null key or value to be set in the collection. However a dictionary is not supposed to have a null key or value,
which otherwise will defeat its purpose. Hence, we will have to restrict the same in our Groovy code.
As far as the key/value pairs are concerned, they can be any valid identifiers and the objects. However if you are putting an
Object of a custom class (your implementation) as a value, you need to ensure the equals() and hashCode() methods are
implemented appropriately, as it is still based on Java Map Interface which works on Hashing. The good implementation of these
two methods will guarantee an efficient and collision-free manipulation of key-value in the collection.
2.3 Examples
In this example, let us have a custom class to facilitate a Dictionary with the validations in place to ensure there are no null
key/values added. It is mandatory otherwise the Map interface will allow the null key / value by default. As explained above, this
will only ensure the right implementation of a Dictionary.
GroovyCustomDictionary.groovy
package com.javacodegeeks.example.groovy.util;
class Dictionary
{
def key
def value
if(value==null)
throw new RuntimeException("Null value is not permitted")
}
def printInfo() {
println "myDict Custom Object : ${this}"
println " "
}
}
In this example, we will load the inputs from a text file country-capital.txt which has got a few countries and their
capitals in each line as a comma separated value. We will load this text file and create a Dictionary (Map) at runtime.
The country-capital.txt file has the following contents (for simplicity, only few lines of the file is shown below).
GroovyCountryCapitalDictionary.groovy
# Ref URL : https://www.countries-ofthe-world.com/capitals-of-the-world.html
Afghanishtan, Kabul
Groovy Programming Cookbook 24 / 75
Australia, Canberra
Austria, Vienna
Bahamas, Nassau
Bahrain, Manama
The following example shows the pattern of how a Dictionary can be used in a real world as follows.
• A Dictionary is created with the fixed set of inputs parsed out of a text file (by excluding comments and blank lines)
• Inputs are validated for not being NULL before getting added into the Dictionary Collection
• Program is executed in a Command line with two different options - 1. Print the Dictionary Contents 2. Get the country or
capital matching with the input passed in the command line
• Program warns and assists the user with the Usage Information if the arguments are inappropriate
• Program does NOT facilitate addition/removal of entries to and from Dictionary.
GroovyCountryCapitalDictionary.groovy
package com.javacodegeeks.example.groovy.util;
def validLines = []
if(value==null)
throw new RuntimeException("Null value is not permitted")
}
def printUsage() {
def scriptName = this.class.getSimpleName()
println ""
println "[Usage] Please use any of the following : "
println " 1. $scriptName <[Country:] [Capital:]"
println " 2. $scriptName print --> to print the dictionary"
System.exit(1)
}
def handleInvalidArgs() {
println " "
println " ## Please specify the input in proper format"
printUsage()
}
if(args.length<1) {
printUsage()
}
if(args[0].equalsIgnoreCase("print")) {
println " "
println "Total Elements in Dictionary : " + dict.size()
println " "
println " Dictionary Contents "
println "***********-----------"
println dict
System.exit(0)
}
else
{
def argType
def argTokens
def inputArg = args[0]
argTokens = args[0].tokenize(’:’)
if(argTokens.size()<2) {
handleInvalidArgs()
}
argType = argTokens[0]
if(argType.equalsIgnoreCase("country")) {
def countryAlphabet = argTokens[1]
println ""
println "Country starts with ’${countryAlphabet}’ : "
println getCountryStartsWith("${countryAlphabet}")
}
else if(argType.equalsIgnoreCase("capital")) {
def capitalAlphabet = argTokens[1]
println ""
println "Capital starts with ’${capitalAlphabet}’ : "
Groovy Programming Cookbook 26 / 75
println getCapitalStartsWith("${capitalAlphabet}")
}
else {
handleInvalidArgs()
}
}
The above script produces the following output when simply executed without any arguments. The output displayed will be the
Usage information with the format.
[Usage] Please use any of the following :
1. GroovyCountryCapitalDictionary <[Country:] [Capital:]
2. GroovyCountryCapitalDictionary print --> to print the dictionary
When you specify the starting alphabet(s) of a Country that you are looking for, the program displays the output with the countries
matching with the characters/alphabets specified in the command line.
groovy GroovyCountryCapitalDictionary.groovy Country:I
You can also specify the alphabet(s) for the Capital, as follows.
groovy GroovyCountryCapitalDictionary.groovy Capital:A
If the input pattern is wrong, the program displays the Usage information to give a correct input next time. Note that the below
invocation of the program does NOT have the starting alphabet, which is purposefully omitted.
groovy GroovyCountryCapitalDictionary.groovy Country:
Hope you found this example series helpful in manipulating the Dictionary in Groovy. For the real scenarios, you are requested
to add more validations and testing to keep the logic appropriate.
You may please refer the following URLs for further reading.
Groovy Map Example from Java Code Geeks Example
Javadoc for Map Interface
GroovyMap API Javadoc
This is an example of how to manipulate a Dictionary in Groovy, tested with the Command Prompt / Shell against Groovy
Version 2.4.3.
Download
You can download the full source code of this example here: Groovy Dictionary Example
Groovy Programming Cookbook 27 / 75
Chapter 3
In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred
data format these days for the exchange of data between the interested parties (client and server), due to its light weight nature
and ease of use.
Groovy has a built in support to work with JSON data - be it with the literal data or the the Java objects in memory. It offers a
simple way to parse and build the data into JSON format.
This article will show the various situations in which you need to have a JSON format.
3.1 Environment
The examples shown below are executed in the Command Prompt / Shell. But they are guaranteed to work with any of the
IDEs (like Eclipse, IntelliJ IDEA, Netbeans) through the respective plugins. The examples are executed with the Groovy Version
Groovy Version: 2.4.3.
Since version 1.8, Groovy offers two classes viz JsonSlurper and JsonBuilder. These classes offer various methods to
help us deal with the JSON data.
JsonSlurper is a parser which reads the input data and gets the JSON content backed up by a Java Collection (Map or List).
By iterating the Collection we can get the required JSON data in the form of Domain Model class (POJO/POGO) to be used
in further layers of the application. The term POJO stands for Plain Old Java Object and POGO stands for Plain Old Groovy
Object. The JsonSlurper can read from various different inputs ranging from literal String, File, URL, Map etc.,
JsonBuilder class helps you to build the JSON data from your existing Domain Class (or POGO). Using the JSONBuilder object
you can either get the JSON data in a ordinary String (which will be compressed and not so good for human reading), prettyPrint
format (neatly formatted content for display which will be human readable), write the data into a file etc.,
In addition to these classes, we have an another useful Utiltity class called JsonOutput.
JSONOutput is a helper class facilitating the transformation of the JSON content from various source formats through its
overloaded method toJson(). You can use the relevant method to get the JSON output from the underlying source which is passed
as argument. It also offers a prettyPrint method for a human readable output.
For example, toJson(String string) produces the JSON representation for the String data passed, whereas toJson(M
ap map) returns the JSON representation for a Map that is passed as an argument.
We will use a mixture of all these in the below set of examples.
Please note that these classes belong to the package groovy.json and this package is NOT imported by default. We need to
explicitly import the classes to be available in our groovy scripts.
Groovy Programming Cookbook 28 / 75
We will see a set of examples for different scenarios to work with JSON output. The source code and output are mostly self
explanatory and hence will have a minimal explanation wherever required.
Let us see a very simple example where we can produce the JSON data from a plain text (literal String) without actually generating
an object. We will use JsonOutput class for this purpose.
JsonLiteral.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonOutput;
Let us see an example where we can generate the JSON output from a POGO (Plain Old Groovy Object).
JsonFromPOGO.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonOutput
class Person
{
String name
int age
String toString()
{
"[Person] name : ${name}, age : ${age}"
}
}
def person = new Person(name:’Raghavan’,age:34)
println "Person Object : " + person
println "Person Object in JSON : " + JsonOutput.toJson(person)
println "JSON Pretty Print"
println "***********-"
// prettyPrint requires a String and NOT an Object
Groovy Programming Cookbook 29 / 75
println JsonOutput.prettyPrint(JsonOutput.toJson(person))
println ""
Please note that we have used two different toJson(..) methods above. Depending on the input argument passed (Object,
List) the corresponding overloaded toJson() method will be invoked.
The above script produces the following output.
Person Object : [Person] name : Raghavan, age : 34
Person Object in JSON : {"age":34,"name":"Raghavan"}
JSON Pretty Print
***********-
{
"age": 34,
"name": "Raghavan"
}
JsonSlurper object gives us a JSON Object as a result of successful parsing of the input content passed to it. It has several
overloaded methods parse() which accepts various different input sources right from literal String, File, URL, Map etc.,
We can use this JSON Object to fetch any properties of our interest by using the relevant hierarchy / relation.
We will see how we can generate the JSON output with the JsonSlurper instance below.
JsonSlurper1Basic.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonSlurper
println ""
println "Individual Attributes"
println "====================="
println "Object.name -> [" + jsonObject.name + "]"
println "Object.year -> [" + jsonObject.year + "]"
Individual Attributes
=====================
Object.name -> [Groovy]
Object.year -> [2005]
In this example, we have used a literal text to be parsed by JsonSlurper instance and as a result we get a JSON Object. You
can see that jsonObject is of type Map (groovy.json.internal.LazyMap).
Later, we can retrieve the properties from a map using the usual dot notation (".") as in jsonObject.name and jsonObject.year
respectively.
We can see how we can pass a literal String with a List object to be parsed by JsonSlurper and how we can manipulate the
contents of a list.
JsonSlurper2List.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonSlurper
3.3.5 Producing JSON data via JSONSlurper and verify the data type of attributes
Below example code snippet shows that we can retrieve the data type of each of the members parsed out of JsonSlurper, which
will be helpful for us to take a cautious decision while passing it further into the application.
JsonSlurper3DataTypes.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonSlurper
In this example, we have used a different way of passing a literal text to JsonSlurper through a set of triple quotes (’) for a
multi-line string literal input.
The above script produces the following output, where you can see the data type of each of the members printed out in order.
Please note that Groovy prefers BigDecimal, unlike Java which prefers a float or double for the floating point values.
JSON Object : [age:23, name:Raghavan, salary:40000.25, temp:98.4]
JSON Object class : class groovy.json.internal.LazyMap
We will see an example of how to read the json file from disk and work with the contents retrieved inside our groovy script.
We will read the contents of the file employee.json and also display the same with and without pretty print for your ease of use
and verification.
JsonSlurper4File.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
The above script produces the following output. You can see the attributes of the object being retrieved from the JSON Object.
JSONObject : [employee:[age:35, country:India, department:Technology, firstName:Raghavan, ←-
lastName:Muthu, project:[manager:Mark, name:Payroll Automation]]]
Individual Attributes
***********-----
JSONObject employee firstName : Raghavan
JSONObject employee age : 35
JSONObject employee project name : Payroll Automation
JsonBuilder class helps you to generate JSON from the Java objects. It is the reverse of JsonSlurper which reads and
parses to get you the JSON Object.
We use JsonBuilder to generate a JSON specific data that can be either written to a file, for example configuration files for an
application, or to a different URL source via a suitable java.io.Writer Implementation class.
The advantage and specialty of the JsonBuilder class is that you can very easily construct an object by specifying the members
and their values in a literal String, without actually creating an instance of a separate POGO class. That is you can build your
object at runtime. This way it is very helpful to create configuration classes which are JSON specific.
Groovy Programming Cookbook 33 / 75
In the below example, the code snippet shows two parts - first generating a JSON object on the fly using the JsonBuilder and then
parsing it into a Java object via JsonSlurper for manipulating its properties one by one.
JsonBuilder1Basic.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
println builder
println ""
println builder.toPrettyString()
/* Part 2 - Parse the Json Content into a JSON Object via JsonSlurper for further usage */
{
"book": {
"title": "Head First Java",
"publisher": "Orielly",
Groovy Programming Cookbook 34 / 75
"author": [
"Kathy Sierra",
"Bert Bates"
],
"year": "2005",
"currency": "USD",
"price": 44.95,
"format": [
"pdf",
"print"
]
}
}
JsonBook Object :
[book:[author:[Kathy Sierra, Bert Bates], currency:USD, format:[pdf, print], price:44.95, ←-
publisher:Orielly, title:Head First Java, year:2005]]
JsonBook Object type : class groovy.json.internal.LazyMap
JsonBook Object size : 1
Book Instance :
[author:[Kathy Sierra, Bert Bates], currency:USD, format:[pdf, print], price:44.95, ←-
publisher:Orielly, title:Head First Java, year:2005]
Book Instance Type : class groovy.json.internal.LazyMap
Book Instance size : 7
Individual Attributes
***********------
Title : Head First Java || Type : class java.lang.String
Author : [Kathy Sierra, Bert Bates] || Type : class java.util.ArrayList || Size : 2
Price : 44.95 || Type : class java.math.BigDecimal
Currency : USD || Type : class java.lang.String
Format : [pdf, print] || Type : class java.util.ArrayList || Size : 2
In this example, we will see how we can generate the JSON data using the JsonBuilder and use its API method to write the
JSON into a file in the disk.
This will be handy when we need to write our JSON specific configuration into a file which can later be read by a Container for
serving our application to users.
In this example will write the contents into a file and subsequently we will read the file contents and display for our verification.
JsonBuilder2File.groovy
package com.javacodegeeks.example.groovy.json;
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
jsonBuilder.config
{
env : "Prod"
database {
host "example.com"
port 3306
type "MySQL"
user ’dbUser’
pass ’dbPass’
Groovy Programming Cookbook 35 / 75
driver ’com.mysql.jdbc.Driver’
}
threadPool 10
useBridge ’Y’
}
println ""
def fileContents = new File(outputFile).text
println "File contents : " + fileContents
println ""
println "File Contents PrettyPrint"
println "========================="
println JsonOutput.prettyPrint(fileContents)
"port": 3306,
"type": "MySQL",
"user": "dbUser",
"pass": "dbPass",
"driver": "com.mysql.jdbc.Driver"
},
"threadPool": 10,
"useBridge": "Y"
}
}
Hope you found this example series helpful in manipulating the JSON data with Groovy scripts, for the simple use cases.
However if you have a different (or advanced) scenario at hand, you are recommended to read the API for the variants of each
class and its methods.
You may please refer the following URLs for further reading.
Groovy Json from Groovy Language Documentation
JsonSlurper Groovy API
JsonBuilder Groovy API
JsonOutput Groovy API
This is an example of how to read and write JSON data in Groovy, tested with the Command Prompt / Shell against Groovy
Version 2.4.3.
Download
You can download the full source code of this example here: Groovy JSON Example
Groovy Programming Cookbook 37 / 75
Chapter 4
4.1 Introduction
String related manipulations have been always important in almost all programming languages. If you are using Groovy, you
will do String manipulation in an easy way. In other words, it is very easy to split, add, manipulate, initialize, escape Strings in
Groovy. In this tutorial I will show you how to use Groovy String efficiently.
4.2 Warmup
class GroovyStringBasic {
static main(args) {
def name = ’John’ // John
println name
println ’The quick brown fox jumps over the lazy dog’.length() // 43
println ’Non-Blocking IO’.indexOf("o") // 1
println ’AngularJS Service vs Factory vs Provider’.substring(32) // ←-
Provider
println ’C# is the best’.replace(’C#’, ’Java’) // Java is the best
println ’I am very angry’.toUpperCase() // I AM VERY ANGRY
}
As in other programming languages, Groovy is also capable of doing basic operations. On line 06 we have defined a String
and then printed it on line 07 as you may guess. On line 09, we have printed the length of the given String. On line 10,
we have printed the index of the first occurrence of character o which is 1. On line 11, we have applied sub string operation
in order to pull string from specific starting point that we desired. Replacement is one of the basic operations in Strings. We have
replaced C# with Java on line 12. And finally, we have changed the case of the string letters by using toUpperCase()
GroovyStringConcat.groovy
package main.javacodegeeks.groovy
class GroovyStringConcat {
static main(args) {
def name = ’John’
def surname = ’Doe’
println ’Hello ’ + name + ’ ’ + surname // Hello John Doe
}
As you can see we have used + sign to concate two given string. There is another way to show two string in combined way.
When you look at following example.
GroovyGString.groovy
package main.javacodegeeks.groovy
class GroovyGString {
static main(args) {
def name = ’John’
def surname = ’Doe’
You will see that, the expression on line 09 compiled as string, but on line 10 the string is printed as it is. The double
quote " is called in Groovy as GStrings and this accepts expressions inside.
4.4 Operators
You can apply math operators to Groovy strings to add, multiply or subtract them. Let’s see following examples.
GroovyOperators.groovy
package main.javacodegeeks.groovy
class GroovyOperators {
static main(args) {
println ’I am very long sentence’ - ’very long ’ // I am sentence
println ’I will ’ + ’ be very long sentence’ // I will be very long ←-
sentence
println ’Ice ’ * 2 + ’ baby’ // Ice Ice baby
}
On line 06, we have removed part of the sentence by using - operator. It is something like removing string by using sub
string, or apply replace operation on a string. This is very simple operation as you see in the example. On line 07, we have
concatenated the strings by using + sign. The strange one is multiplication of the stirng on line 08. When you multiply a
string, that string will be self concatenated it self by multiplication factor.
Groovy Programming Cookbook 39 / 75
You can use triple quote """ for the multiple lined strings like below.
GroovyMultiLinedString.groovy
package main.javacodegeeks.groovy
class GroovyMultiLinedString {
static main(args) {
def multiLine = """
Hi everyone, I will
write lots of things here
because I am not restricted with
one line. I am capable of
multi lines
"""
println multiLine
}
As you can see, we have written multi line string in triple quoted strings and it will printed as it is.
Tokenize is used for splitting Strings by a delimiter. If you do not provide delimiter, it will be splitted by space, tab, or next line.
Let’s see how it works.
GroovyTokenize.groovy
package main.javacodegeeks.groovy
class GroovyTokenize {
static main(args) {
def text = ’Hello World’
println text.tokenize() // [Hello, World]
On line 07, it was delimited by space by default and printed an array with two elements that is [Hello, World]. On
line 10, we have used , as delimiter and it has also delimited to an array. And in last example, it was automatically delimited
by the tab.
4.7 Conclusion
Groovy String is very flexible usage while you are developing application. It lets you to save lots of lines due to its practical
usage. You can do lots of manipulation on Groovy Strings with power of Groovy.
Groovy Programming Cookbook 40 / 75
Download
You can download the full source code of this example as an Eclipse project here: GroovyStringExample
Groovy Programming Cookbook 41 / 75
Chapter 5
5.1 Introduction
A closure is an anonymous code block that can take arguments, return value, and also can be assigned to a variable. When
it comes to Groovy, a closure can contain a variable scope defined outside of the closure expression. Groovy offers extended
features to formal closure definition. By using this features, we can write our code more dynamically by applying closures
to functions as parameter, caling anonymous code blocks inside functions, etc. . . Let’s see closure in action with supporting
examples.
ClosureDeclaration.groovy
package com.javacodegeeks.groovy.closure
class ClosureDeclaration {
static main(args) {
def myClosure = { println "Hello World!" }
myClosure.call() // Hello World!
myClosure() // Hello World!
}
In this example, we have defined a closure on line 06, and then we have called it by using call() function. Alternatively,
you can call closures by acting as function directly as on line 07
Sometimes, we need to pass arguments to the closures to make them more dynamically according to our needs. You can write a
closure that accepts parameters while calling them. Let’s see following example to see how it works.
ClosureParameters.groovy
package com.javacodegeeks.groovy.closure
class ClosureParameters {
Groovy Programming Cookbook 42 / 75
static main(args) {
def squareWithImplicitParameter = { it * it }
println squareWithImplicitParameter(4) // 16
On line 07, we have used implicit argument called it that defines default parameter provided to the closure. In square closure,
we accessed the default parameter with it. Actually, it is equal to below code.
Square function without "it"
def square = {x -> x * x}
println square(4)
And this function takes only one parameter and returns the multiplication of the same number. Remember that, the last line in the
functions returned as default in Groovy language. In ClosureParameters.groovy class on line 10, we have defined
closure with 2 parameters and both of them has explicit types that is int. In same way, it takes two arguments and returns sum
of them. You do not need to provide explicit types, you can use optional types in arguments also. When you look at line 13,
you will see that a has type int, but b don’t. Groovy closures also support default parameter values. On line 16, you need
to provide first argument, but if you do not provide second parameter, it will be 5 as default.
5.4 VarArgs
You can define variable argument in closures for accepting dynamic arguments to closures. Let’s have a look at following
example to see how it works
ClosureVarArgs.groovy
package com.javacodegeeks.groovy.closure
class ClosureVarArgs {
static main(args) {
def combine = { String... names ->
names.join(’,’)
}
As you can see on line 06, we have defined a closure that takes variable arguments with String...names and we have
joined them. Yes, you can also use array as one argument then join them, but this example is for showing how VarArgs can be
used.
Groovy Programming Cookbook 43 / 75
You can pass closure as parameter to another closure easily. Let’s look at following example.
PassingClosure.groovy
package com.javacodegeeks.groovy.closure
class PassingClosure {
static main(args) {
def funcClosure = { x, func ->
func(x)
}
As you can see on line 06 there are two closure parameter, but they are not just a parameter like String or Integer.
When you look at the closure body, we are using func(x). This means, func is an another closure that accepts closure
expression. On line 10, funcClosure([1, 2, 3], { it.size()}), first parameter is a list and second parameter
is a expression that uses it, and that means first parameter of the closure funcClosure
In Groovy, you can compose different closures to simulate compound functions in Math science. In this section, we will simulate
f(g(x)) =.... Let say that, you will sum two numbers and then you will apply square function to sum result. You can do
that by following.
PassingClosure.groovy
package com.javacodegeeks.groovy.closure
class ClosureComposition {
static main(args) {
println squareOfSum(2, 3) // 25
On line 07, we defined sum closure and on line 08 square function. On line 09, we pass sum function to square function
and actually it turns into following.
{ { a, b -> return a + b } * { a, b -> return a + b }}
5.7 Conclusion
Closures helps us to define anonymous-like functions in program to use that closure as parameter or function body. We can
directly call it by using call(), or we can use it as parameter to another closure or function.
Groovy Programming Cookbook 44 / 75
Download
You can download the full source code of this example as an Eclipse project here: GroovyClosureExample
Groovy Programming Cookbook 45 / 75
Chapter 6
6.1 Introduction
Regular Expression is a character sequence defines search pattern especially for pattern matching with strings. You may see
Regular Expression as Regex or Regexp in software world. In this tutorial, I will show you how to use regex operations in
Groovy by using pretty easy methods.
In Groovy, you can define a pattern by using the tilda operator (~) for a String. When you define a pattern by using tilda operator,
you will get a result in a type https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.
html[java.util.regex.Pattern]. And this means, you can apply all the rules that you do in Java code. You can see
quick example below.
GroovyRegex.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegex {
static main(args) {
def ipAddress = ~/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/
println ipAddress.class.name // java.util.regex.Pattern
}
You can see that the pattern class name is java.util.regex.Pattern. In order to test whether if provided string matches
with the pattern, you can use following.
GroovyRegexMatch.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegexMatch {
static main(args) {
def nameRegex = ~’john’
println nameRegex.matcher("john").matches() // true
On line 06, we defined a pattern and we tested string "john" whether it matches with pattern ~’john’ or not on line 07.
On line 09, we have defined a pattern for ip address and checked the string 127.0.0.1 for pattern matching in same way
on line 10.
Groovy lets you to create pattern matchers easily. For example, if you need to test a string if it starts with L and ends with s, you
can use following.
GroovyRegexMatchAdvanced.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegexMatchAdvanced {
static main(args) {
def pattern = ~’L....e’
println pattern.matcher("Little").matches() // true
}
On line 06 we have defined the pattern. It says that, it will start with ’L’ and then has 4 characters, and finally it ends
with ’e’. On line 07, it matches with the string ’Little’ which starts with ’L’, ends with ’e’ and has ’ittl’ in the
middle.
GroovyRegexMatchAdvanced.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegexMatchAdvanced {
static main(args) {
def pattern = ~’L....e’
println pattern.matcher("Little").matches() // true
}
You can also use isCase() for the pattern matching in Groovy. Let say that, you only know the starting and ending letter of the
string and you want to check whetter it matches with the pattern or not. You can use following for that case.
GroovyRegexMatchAdvanced.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegexMatchAdvanced {
static main(args) {
def isCasePattern = ~/L\w+e/
println isCasePattern.isCase("Little")
}
}
Groovy Programming Cookbook 47 / 75
On line 06, the pattern contains starting letter L and ending letter e, it contains any length of whitespace character inside L
and e.
GroovyRegexMatchAdvanced.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegexMatchAdvanced {
static main(args) {
def grepPattern = ~/A\w+/
def cities = [’Alabama’, ’Los Angeles’, ’Arizona’]
println cities.grep(grepPattern) // [Alabama, Arizona]
}
In above example, we have defined our pattern as ~/Aw+/ which means, things that start with A and then we grep the cities that
matches with pattern on line 08.
6.4 Matchers
This is what a matchers is. We have called matches() function over matchers. In Groovy, there is a easier way to define
matchers and run matches() function. You can see below for example matcher.
GroovyRegexMatcher.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegexMatcher {
static main(args) {
def matcher = ("127.0.0.1" =~ /([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/)
println matcher.class.name // java.util.regex.Matcher
}
As you can see, we have used =~ for defining a matcher. As a result, we got an object that instance of https://docs.ora
cle.com/javase/7/docs/api/java/util/regex/Matcher.html[java.util.regex.Matcher]. You can
call this an IP address matcher. Let’s see a couple of examples to understand matcher deeper.
GroovyRegexMatcher.groovy
package com.javacodegeeks.groovy.regex
class GroovyRegexMatcher {
static main(args) {
def numbers = (’5 is greater than 4’ =~ /\d+/)
println numbers // java.util.regex.Matcher[pattern=\d+ region=0,19 ←-
lastmatch=]
println numbers.size() // 2
println numbers[0] // 5
}
}
Groovy Programming Cookbook 48 / 75
In above example, on line 06 we have defined a matcher ’5 is greater than 4’ =~ /d+/ which says that some-
thing matches with numbers. This will find two numbers in string which are 5, and 4. On line 07, it prints the value of the
matcher object. If you want to get the values found by matcher, you can use array notation as on line 09.
6.5 Conclusion
Groovy lets us to use regex as in the java but it has some extra features and easy usages. There are two section in regex world
which are Pattern and Matcher. Pattern is the regular expression we define. Matcher is an expression with provided string and
the regular expression. We call matches() function over matchers to find the things you want
Download
You can download the full source code of this example as an Eclipse project here: GroovyRegexExample
Groovy Programming Cookbook 49 / 75
Chapter 7
7.1 Introduction
Groovy collect() is used for iterate through collections to apply closure to each element. In this tutorial, we will see how to use
collect() for collection operations. Let’s get started
7.2 Collect
When you have a look at the method signatures of collect below, we will see that collect can be executed with default closure
which is Closure.IDENTITY, with a closure, or with a supplied collector and closure
Overloaded Methods
public List collect()
public List collect(Closure transform)
public Collection collect(Collection collector, Closure transform)
Let say that you have a list of fruits and you want to apply uppercase operation to each element of fruit list. You can do that by
following code.
GroovyCollect.groovy
package com.javacodegeeks.groovy.collect
class GroovyCollect {
static main(args) {
def fruits = ["Banana", "Apple", "Grape", "Pear"]
def upperCaseFruits = fruits.collect { it.toUpperCase() }
println upperCaseFruits // [BANANA, APPLE, GRAPE, PEAR]
}
As you can see on line 07, upperCase() function applied to each element, and it there means current element while
iterating. As we said above, collect function takes closure as parameter and our closure here is { it.toUpperCase() }.
Let me give you another example. You have Fruit class and you want to construct Fruit object list by using fruit list. You
can do that by simply apply new Fruit object creation closure to the collect function. You can see example below.
GroovyCollectForClass.groovy
Groovy Programming Cookbook 50 / 75
package com.javacodegeeks.groovy.collect
import groovy.transform.ToString
class GroovyCollectForClass {
static main(args) {
def fruits = ["Banana", "Apple", "Grape", "Pear"]
def fruitObjects = fruits.collect { new Fruit(name: it) }
println fruitObjects // [com.javacodegeeks.groovy.collect.Fruit(name:Banana ←-
, amount:0), com.javacodegeeks.groovy.collect.Fruit(name:Apple, amount ←-
:0), com.javacodegeeks.groovy.collect.Fruit(name:Grape, amount:0), com. ←-
javacodegeeks.groovy.collect.Fruit(name:Pear, amount:0)]
}
@ToString(includeNames = true)
class Fruit {
def name
def amount = 0
}
On line 16, we have declared a class with an annotation @ToString(includeNames =true) to show field names to
be shown when we print class object. After class declaration, we apply object creation new Fruit(name:it) on line
09. While iterating fruit elements, the closure will be like this, new Fruit(name:"Banana"), new Fruit(name:
"Apple"), new Fruit(name:"Grape"), new Fruit(name:"Pear")
Sometimes, you may need to start collect operation wiht an initial list, or whenever you collect an element, you may need to add
it to different type of collection instead of list. In that case, you can use a supplementary collectors beside the closure in side
collect() function. Let say that, you have initial fruit list, and you wan to collect another fruit list by providing initial fruit
list to collect function as supplementary collector. You can see following example to understand what is going on.
GroovyCollectWithCollector.groovy
package com.javacodegeeks.groovy.collect
class GroovyCollectWithCollector {
static main(args) {
def initialFruits = ["Orange", "Lemon"]
def fruits = ["Banana", "Apple", "Grape", "Pear"]
def totalFruits = fruits.collect(initialFruits, { it.toUpperCase() })
As you can see on line 10, collect operation started with initialFruits and closure applied to fruits elements. When
you supply a collector to collect() function, you will get a modified version of the collector as you can see on line 11.
initialFruits list has also changed, because it is the collector we supplied and collect result will be populated in that
variable..
Let say that, you have list of fruits like below.
Groovy Programming Cookbook 51 / 75
and you want to get distinct value of fruits. You can do that by using following.
GroovyCollectWithCollectorDistinct.groovy
package com.javacodegeeks.groovy.collect
class GroovyCollectWithCollectorDistinct {
static main(args) {
def fruits = ["Banana", "Apple", "Grape", "Pear", "Banana"]
def distinctFruits = fruits.collect(new HashSet(), { it })
While you are iterating elements with collect() on line 07, collected elements will be added to collector, and that collector
is a HashSet(). This collection type is for keeping distinct values as you may already remember from Java.
7.4 Conclusion
Groovy has powerful components for the Collections SDK, and one of them is collect(). By using collect(), we have
applied closures to list elements. Also, we have used different overloaded functions of collect() function for using default
collector, or provide our own collectors like HashSet().
Download
You can download the full source code of this example as an Eclipse project here: GroovyCollectExample
Groovy Programming Cookbook 52 / 75
Chapter 8
8.1 Introduction
Date operations may be painful in most of the programming languages. You may spend most of your time to convert dates from
one format to another one. In Groovy, date operations are very easy. Groovy has lots of functions extended from JDK Date API,
this allows us to use date related operations in an easier way. Let’s have a look at how can we use Groovy date extension.
8.2 Warmup
In Java, we use Date or Calendar in for specific cases. Date class is a simple class and it has backward compatibility. If you
want to do some date arithmetic operations, use Calendar class instead. In Groovy, we can use both Date or Calendar.
You can see following example for initializing and getting current date.
GroovyDateInitialization.groovy
package com.javacodegeeks.groovy.date
class GroovyDateInitialization {
static main(args) {
def date = new Date()
println date // Sat Sep 26 19:22:50 EEST 2015
As you can see, date variable is a simple date, but calendar has a value class with some instance variables. I have provided
only one instance variable, because it is very long. This is simple in Java too, but what about parsing?
Date parsing is the operation of conversion date string to date object. You can simply parse date string to date object easily like
below.
GroovyDateParsing.groovy
Groovy Programming Cookbook 53 / 75
package com.javacodegeeks.groovy.date
class GroovyDateParsing {
static main(args) {
def date = new Date().parse("dd.MM.yyy", ’18.05.1988’)
println date // Wed May 18 00:00:00 EEST 1988
On line 08, we used parse function to parse provided date string by using date format provided as first argument. In line
11, hour, minute, and seconds parameters provided in the format and date string in order to be parse extended date. In first
example on line 08, it printed 00:00:00, because we did not provided hour, minute, and seconds section. You can have a look
at here to see full date formats.
Sometimes, we need to format date object into desired format. In Groovy, you can use format function to format date object.
You can see a quick example below.
GroovyDateFormatting.groovy
package com.javacodegeeks.groovy.date
class GroovyDateFormatting {
static main(args) {
def date = new Date().parse("dd.MM.yyy", ’18.05.1988’)
def formattedDate = date.format("dd/MM/yyy")
println formattedDate // 18/05/1988
}
In this example, we simply parsed the date string into a date object on line 08, and then we have formatted that date object by
using format function on line 09. In order to format a date object, you can provide date format as argument.
The main advantage of the Groovy date extension is the doing arithmetic operations on date object. If you have used Joda Time
before, you will be very familiar to this topic. Let say that, you have a date and you want to find the date object which is 5 days
after from previous date. In order to do that, you can use following example.
GroovyDateArithmetic.groovy
package com.javacodegeeks.groovy.date
class GroovyDateArithmetic {
Groovy Programming Cookbook 54 / 75
static main(args) {
def date = new Date().parse("dd.MM.yyy", ’18.05.1988’)
datePlus = datePlus + 5
datePlus = datePlus.plus(5)
dateMinus = dateMinus - 10
dateMinus = dateMinus.minus(10)
In above example, we have done some arithmetic operations. First, we have cloned date to two variables dateMinus, and
datePlus to simulate two different dates. In order to increment date object by 5 days, we have used datePlus =datePlus
+ 5 on line 11. Alternatively you can use plus function like on line 15. In same way, we have decremented the
dateMinus by 10 by using subtracting sign in dateMinus =dateMinus -10. Alternatively, you can use minus function
like on line 23. We have also find the dates between two dates dateMinus and datePlus by using the range(..) function
in Groovy. You can see the date ranges on line 29.
In some cases, you may need to get year, month, date values separately from date objects, or you may need to set those fields in
date objects separately. Subscript operators helps us to get that specific values. In fact, Groovy uses getAt() and putAt()
respectively to get and set specific subscript fields in date object. Let’s see some examples.
GroovyDateSubscriptOperators.groovy
package com.javacodegeeks.groovy.date
class GroovyDateSubscriptOperators {
static main(args) {
def date = new Date().parse("dd.MM.yyy", ’18.05.1988’)
date[YEAR] = 1999
Groovy Programming Cookbook 55 / 75
date[MONTH] = 7
date[DATE] = 20
In this example, on line 10, 11, and 12 we get the year, month, and day value from date object. This is something like
getting value from map by providing the map key. But, where did YEAR, MONTH, and DATE come from? They come from the
static import import static java.util.Calendar.* on line 03. Be careful about the month value on line
11, and it is the index of the month. You can also set month, year, and day values like setting a map on line 14, 15, and 16.
8.7 Conclusion
Date operations are the operations that we used during software development and it is really painful on converting dates from
one format to another. In Groovy, this operations are very simplified, and you can easily perform date operations like applying
arithmetic in Math. You can parse date string, format a date object, increment - decrement date, and apply subscript operators on
date objects without using any third party libraries.
Download
You can download the full source code of the project here: GroovyDateExample
Groovy Programming Cookbook 56 / 75
Chapter 9
9.1 Introduction
In previous tutorials, we have mentioned about Groovy List and provided lots of examples. In this tutorial, I will show you how
to use Groovy arrays. Even if array and list seems to be same, they have differences in common. For example, arrays have fixed
size while lists have dynamic size that means you can add item as much as you can after initialization of the list. If you try to
add item to array with a size bigger than initial size of the array after initialization, you will get MissingMethodException or
ArrayIndexOutOfBoundsException. After some theory, let’s see some Groovy arrays in action.
In Groovy, you can declare array in Java style or Groovy style. Let’s have a look at following example for array declaration.
GroovyArrayDeclaration.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayDeclaration {
static main(args) {
def birds = new String[3]
birds[0] = "Parrot"
birds.putAt(1, "Cockatiel")
birds[2] = "Pigeon"
As you can see in the example, you can declare an array with a size, and then you can put elements in different ways in Java
style. In second example, the array is directly declared with initial values. Also, it has been casted to the String that means this
array has elements of type String.
Groovy Programming Cookbook 57 / 75
In Groovy, you can access array item by using square bracket with an index ([index]) or using getAt(index) function.
Let’s have a look at following example to see what is going on.
GroovyArrayAccessItem.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayAccessItem {
static main(args) {
As you may already know, it is easy to understand the case on line 09, line 10 and line 11. They are simple operations
to get items on specific index. What about on line 13? Why we use negative index? It is simple, when you use negative index,
it will be accessed from the end of the array with 1 based index. When you say -1 it means the first element from the end. And
in same way, when you say -3, it means third element from the end.
As we said earlier, if you try to add items to an array with a bigger size than the fixed length, you will get an exception as in the
example below.
GroovyAddItemException.groovy
package com.javacodegeeks.groovy.array
class GroovyAddItemException {
static main(args) {
def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[]
On line 08, the method << belongs to list, that is why we got MissingMethodException. On line 10 we have
exception due to overflow the size of the array wit a size 3.
In Java, you can use size() method for the list, and length method for the arrays in order to get actual size of the object. In
Groovy, it has been simplified and you can use size method for both arrays or lists. You can see simple example below.
Groovy Programming Cookbook 58 / 75
GroovyArrayLength.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayLength {
static main(args) {
def birds = ["Parrot", "Cockatiel", "Pigeon"] as String[]
println birds.length // 3
println birds.size() // 3
}
Let say that, you have array of numbers. You can easily find the minimum and maximum value by using the min() and max()
functions over arrays as below.
GroovyArrayMinMax.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayMinMax {
static main(args) {
On line 09 and line 10 you can easily understand the case but, the trick on line 14 and line 15 is, the minimum
and maximum value is determined by the length of the current string value. Let say that you are iterating to find minimum and
maximum value, it means current value in the array.
Removing item here is not actually removing item from array. It is something like assign the array with one item removed version
to another variable. Let see it in action.
GroovyArrayRemoveItem.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayRemoveItem {
static main(args) {
Groovy Programming Cookbook 59 / 75
As you can see on line 09, we are using subtracting method to remove one item and assign final version to another variable.
It is not removed from the original array actually as you can see on line 11. However, you can see another array without
"Parrot" on line 13.
If you are interacting with collections, you may need to do ordering operations time to time. For example, you may want to
reverse array, or sort the array items. You can see following example to see how it looks like.
GroovyArrayOrdering.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayOrdering {
static main(args) {
In above example, array is reversed and items printed on the screen in reverse way on line 09. Also, array sorted in alphabetical
order by using sort() function. You can see it on line 11
You can perform lookup operations on arrays. In following example we will reverse every item text and also we will find an item
by matching a provided regex. Let’s do it.
GroovyArrayLookup.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayLookup {
static main(args) {
On line 11, we have iterated by using collect function and reversed each item by using reverse() function. Again,
it stands for the current item in the code. On line 13, we have used find function to find specific item by using regular
expression.
9.10 Conversion
You can also convert array to list in Groovy easily. You can see following example for simple usage.
GroovyArrayConversion.groovy
package com.javacodegeeks.groovy.array
class GroovyArrayConversion {
static main(args) {
On line 09, we have used toList function to convert array to list. When you check the class name of birdList you will see
it is instance of java.util.ArrayList. As you can guess, you can convert list to array. Check out line 13 and it is easily
casted to array. You can check the class name on line 15, and you will see it is [Ljava.lang.String;
9.11 Conclusion
To sum up, array and list has same properties in common, but there are major differences between array and list. One of the well
known difference is array has fixed size and list has dynamic size in usage. If you try to add more item bigger than the array size,
you will get exception. Additionally, you can perform many operations on array like list.
Download
You can download the full source code of the project here: GroovyArrayExample
Groovy Programming Cookbook 61 / 75
Chapter 10
10.1 Introduction
In this tutorial, I will show you how to use Groovy Console to run your Groovy scripts and also give you some details about
Groovy Console itself. Actually, there are several ways to run Groovy scripts. You can run it on your favourite IDE, you can
run it from command line, or you can use Groovy Console to run your scripts. Groovy Console is a Swing GUI for perform
several operations to your Groovy scripts. You may want to use Groovy Console to write and run Groovy scripts instead of IDE
or command line. Let’s see features together.
In Groovy Console, there are lots of actions that you can see below.
Groovy Programming Cookbook 62 / 75
Most of them are the actions that you may already know, but you can have a look at below to refresh your knowledge.
• Action 1 is for creating new script to write your code in a fresh area
• Action 2 is for Opening file
• Action 3 is for Saving your code as project
• Action 4 and Action 5 are for Undo and Redo respectively
• Action 6, 7, 8 are for Cut, Copy, Paste respectively
• Action 9 is for looking up something with in your code
• Action 10 is for Replacing text with another text within your code
• In Groovy Console, your executing actions are kept historically. You can go forward and backward along running history with
Action 11 and Action 12
• Action 13 is for Running your current script
• Action 14 is for Interrupting current running script
I assume you have already installed Groovy on your computer and added GROOVY_HOME/bin to your PATH to run groovy
binaries. You can open Groovy console by executing groovyconsole command. You will see Groovy Console GUI like
following.
Groovy Programming Cookbook 63 / 75
There are two area in the GUI: Input Area, Output Area. You can write your code in Input Area and click Run button at the top
right of the GUI (or Ctrl + Enter), and see result in Output Area as below.
Groovy Programming Cookbook 64 / 75
As you can see, there are only codes in the output area, because results are printed in the command line console where you started
Groovy Console from. If you want to see results also in the output area, you need to enable Capture Standard Output like
below.
Groovy Programming Cookbook 65 / 75
You can also open Groovy script file by using File > Open menu and the script will loaded in the input area. Then you can run
loaded script.
Additionally, you can run only selected portion of the code in Input Area. If you select a section in the Input Area and click Run
Selection (or Ctrl + Shift + R) in the Script menu, only the selected code will be executed as below.
Groovy Programming Cookbook 66 / 75
10.5 Interruption
You can interrupt current running script in Groovy Console after enabling interruption by selecting Script > Allow Interruption
menu. What I mean by interruption here is interrupting current thread in running script. For example, in order to interrupt
following script.
try {
while(1) {
println "something"
Thread.currentThread().sleep(500)
}
} catch(InterruptedException ex) {
println "Interrupted from Groovy Console"
}
You can first Run script and then you can click Interrupt button on the right side of the Run button. You will see an output like
below.
Groovy Programming Cookbook 67 / 75
If you want to use Groovy Console within your Java or Groovy application, you can easily embed Groovy Console by using
following example.
package main.java.javacodegeeks.groovyconsole
import groovy.ui.Console;
class GroovyConsole {
static main(args) {
Console console = new Console();
console.setVariable("name", "John");
console.setVariable("surname", "Doe");
console.run();
}
When you execute above script, you will see Groovy Console opened and variables name and surname will be predefined.
And you will be able to use that variables. You can see an example below.
Groovy Programming Cookbook 68 / 75
As you can see, we are able to use $name and $surname even if we did not explicitly defined them.
10.7 Conclusion
Groovy Console is an alternative to Groovy Sh or your favourite IDE. You can quickly write your code and execute to see what is
going on with entire Groovy code. Also, you can embed Groovy Console to your application to define some variables to console
and run it with that variables.
Download
You can download the full source code of the project here: GroovyConsoleExample
Groovy Programming Cookbook 69 / 75
Chapter 11
Grails is an open source framework based on Groovy and Java. It also supports MVC architecture to for developing web
application.
This tutorial will describe more details about Grails and represent a simple web application with Grails.
11.1 Groovy
Groovy is a dynamic object-oriented programming language for the Java platform. It is compiled to Java Virtual Machine (JVM)
byte code and integrates with all existing Java classes and libraries.
Grails uses Spring MVC as the underlying web application framework to implement the web applications based on Model-View-
Controller (MVC) design pattern. It includes three core framework components: Controller, Domain, and Grails Servlet Page.
The diagram below shows how different part of Grails works together.
Groovy Programming Cookbook 70 / 75
11.2.1 Controller
The GrailsDispatcherServlet uses SpringDispatcherServlet to bootstrap the Grails environment. There is a single Spring MVC
controller called SimpleGrailsController which handles all Grails controller requests.The SimpleGrailsController delegates to a
class called SimpleGrailsControllerHelper that actually handles the client request and look up a controller for the request. The
Controller which is responsible for transferring the domain to view, also determines which gsp should render the view.
11.2.2 Domain
Domain stores the data that can be used by controllers and views. Controllers might create a model or may be just process them.
Groovy server pages creates a view for the client response. GSP is responsible for how to display the model to user. It could use
grails tags besides any other UI grails plugin.
This example is implemented in Groovy/Grails Tool Suite and using Grails 2.4.4. Now, lets create a simple application with
Grails.
First, create a Grails Project in GGTS. The GGTS includes Grails, so, if you wish to use a different version of Grails you need to
install it and update the new Grails path in GGTS.
Groovy Programming Cookbook 71 / 75
11.3.1 Controller
We only have one controller here. The UserController is responsible to handle client requests and return proper result when
they submit the form. There is a save method which defined with def. When we declare the return type as def, it means the
method can return any type of object. Inside the method, an instance of User class is created and parameters are set in the domain
object and transfered to the view.
UserController.groovy
package com.java.code.geeks
class UserController {
Groovy Programming Cookbook 72 / 75
def index() {
}
def save() {
def user = new User(params)
user.save()
render (view: "user", model: [user: user])
}
11.3.2 Model
Creating a domain class is very simple in Grails as there is no need to define setter and getter methods. Grails will handles it for
the application.
User.groovy
package com.java.code.geeks
class User {
String firstName
String lastName
11.3.3 View
The following gsp file represents a form to user which includes two items with the same name as model attributes.
index.gsp
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Grails Tutorial</title>
<style>
.form, .text-field, .submit{
margin: 20px;
}
</style>
</head>
<body>
<g:form name="form" controller="user" id="form">
<label>First Name: </label><g:textField name="firstName" value="${ ←-
firstName}" />
<label>Last Name: </label><g:textField name="lastName" value="${ ←-
lastName}" />
<g:actionSubmit value="Submit" action="save"/>
</g:form>
</body>
</html>
Grails uses ${ } to to get model attributes which is firstName and lastName here. When we use
user.gsp
Groovy Programming Cookbook 73 / 75
<!DOCTYPE html>
<html>
<head>
<title>User page</title>
<style>
.user-panel{
margin: 20px;
}
</style>
</head>
<body>
</body>
</html>
Now, it is time to run the web application. To run the web application, click on the Grails Command in the Toolbar and type
run-app in the popup.