SlideShare a Scribd company logo
1 of 40
Welcome To… Groovy!
– The Catalyst Language for Programmers
Presentation By
-Isuru Samaraweera
Agenda
• Introduction to Groovy
• Key Features
• Closures
• Operator Overloading
• Array Slicing and looping
• Collections
• Dynamic Methods/Mixins and Properties
• Regular Expressions
• File IO
• Database Operations
What is Groovy?
• Java-like scripting language for the JVM
• Dynamic Language
• Inspired by Ruby,Python,SmallTalk and Perl
• Open Source language
– Apache2.0 license
– dev@groovy.apache.org
– users@groovy.apache.org
• Seamless integration with Java
– Follow the mantra…Java is Groovy,Groovy is Java 
• Web Application Development
– Groovelets,GSP,Grapplet
• Sole alternative dynamic language for the JVM fully supporting frameworks like Spring, Hibernate
– Grails
– Coding by Convention
• Mobile Application Support 
• Official web site http://www.groovy-lang.org/
Installation and Configuration
• Prerequisites
– JDK1.4 or higher installed and system path should point to %JAVA_HOME%/bin
• Download Groovy distribution from http://www.groovy-lang.org/download.html
• Unzip the groovy archive
– Set the GROOVY_HOME environment variables.
– Add %GROOVY_HOME%bin to your system path
– Try opening groovyConsole.bat
• Eclipse Plug-in
– https://github.com/groovy/groovy-eclipse/wiki
• IntelliJ Idea Plug-in-Community edition
– http://www.jetbrains.net
Key Language Features
• Pure Object Oriented 3.times { println "hello" }
• Dynamic Typing/Duck typing
• Closures
• Currying
• Operator Overloading
• Array Slicing
• Dynamic Methods
• Expandos
• Static imports
• Annotations
• Covariant return types
• POGO support
• Mixins
Java Vs. Groovy No of line Comparison
• Java Code
for (String item : new String [] {"Rod", "Carlos", "Chris"})
{
if (item.length() <= 4)
{
System.out.println(item);
}
}
• Groovy Code
["Rod", "Carlos", "Chris"].findAll{it.size() <= 4}.each{println it}
/*A Typical Groovy Class*/
class Customer
{
// properties
Integer id
String name
Date dob
// sample code
static void main(args)
{
def customer = new Customer(id:1, name:"Gromit", dob:new Date())
println("Hello ${customer.getName()}")
customer.setName(“James”)
println("Hello ${customer.getName()}")
}
}
Java Vs. Groovy No of line Comparison
Closures
• A block of code that can access variables in the scope where it is declared or
outside
• Higher order functions
• A closure will have a default parameter named it if you do not define one
def x = { println it }
• And here's how you call it (two options):
x('Hello, world!')
x.call('Hello, world')
Closure Arguments(Typed or Untyped)
• Untyped Arguments
def isList = { i -> i instanceof List }
if (isList([]))
{
println "This is a List“
}
• Typed Arguments
def prefix = {
String s ->
while (s.length() < 17)
{
s = "0$s"
}
s // return keyword is not required
}
def id = prefix "1234" // parentheses are not required
Closures as arguments and Recursion
• Closures can be passed as arguments
• Consider the each() method on java.util.Map:
System.properties.each { println it.key }
• Recursion
• lambda is annonymous 
def fac =
{
int i -> i == 1 ? 1 : i * call(i - 1)
}
println fac(10)
Currying
• Currying is a programming technique that transforms a function into
another while fixing one or more input values
def multiply = { x, y -> return x * y } // closure
def triple = multiply.curry(3)
// triple = { y -> return 3 * y }
def quadruple = multiply.curry(4)
// quadruple = { y -> return 4 * y }
def p = triple.call(4) // explicit call
def q = quadruple(5) // implicit call
println "p: ${p}" // p is 12
println "q: ${q}" // q is 20
Currying contd..
def lSubtract = { x, y -> return x - y }
def rSubtract = { y, x -> return x - y }
def dec = rSubtract.curry(1)
// dec = { x -> return x - 1 }
def cent = lSubtract.curry(100)
// cent = { y -> return 100 - y }
def p = dec.call(5) // explicit call
def q = cent(25) // implicit call
println "p: ${p}" // p is 4
println "q: ${q}" // q is 75
Variable Arguments
int sum(int... someInts)
{
//ellipsis notation
def total = 0
for (int i = 0; i < someInts.size(); i++)
total += someInts[i]
return total
}
assert sum(1) == 1
assert sum(1, 2) == 3
Operator Overloading ! - 1
it does it by following a naming convention for methods.
Operation Method
a+b a.Plus(b)
a-b a.minus(b)
a*b a.multiply(b)
a**b a.power(b)
a/b a.div(b)
a % b a.mod(b)
a | b a.or(b)
a & b a.and(b)
Operator Overloading ! - 2
a ^ b a.xor(b)
a++ or ++a a.next()
a-- or --a a.previous()
a[b] a.getAt(b)
a[b] = c a.putAt(b, c)
a << b a.leftShift(b)
a >> b a.rightShift(b)
switch(a) { case(b) : } b.isCase(a)
~a a.bitwiseNegate()
-a a.negative()
+a a.positive()
Operator Overloading ! - 3
text = "Programing" - "ing" + "er"
assert "Programer" == text
list = [1,2,3]
list += [4,5,6]
assert [1,2,3,4,5,6] == list
list << 7 // list.leftShift(7) -> list.add(7)
assert [1,2,3,4,5,6,7] == list
s = "A" * 5
assert s == "AAAAA“
s = "ABCDE"
assert "BC" == s[1..2]
s.getAt([1..2]); ranged operation
assert "C" == s[2] // s.getAt(2) -> s.charAt(2)
Looping
• General for loop and while loop
• Classical for loop
def x = 0
for ( i in 0..9 ) //RANGE
{ x += i }
assert x == 45 // iterate over a list
• Iterate over a list
x = 0
for ( i in [0, 1, 2, 3, 4] ) //LIST
{ x += i }
assert x == 10
def a = [1,2,3,4,5]
a[1..-1]
OUTPUT : [2, 3, 4, 5]
def a = [1,2,3,4,5]
a[1..<-1]
OUTPUT: [2, 1]
Array Slicing
Elvis Operator
• Elvis Operator alternative to ternary operator
//traditional ternary operator
String name = “Sam";
String displayName = name != null ? name : "Unknown";
//elvis operator
String name = “Sam"
String displayName = name ? name : "Unknown"
//eliminate DRY
String name = “Sam"
String displayName = name ?: "Unknown"
Agenda
• Introduction to Groovy
• Key Features
• Closures
• Operator Overloading
• Array Slicing and looping
• Collections
• Dynamic Methods and Properties
• Regular Expressions
• File IO
• Database Operations
• Unified Field and Programming Languages
Collections in Groovy
– Lists
– Ranges
– Maps
– Expandos (Dynamic Objects)
Lists
• Lists have been implemented in Groovy as ArrayLists which store elements of type Object.
• Create a list  def myList = [1,2,3.6,-9.01,“hello”,“a string”, new Date()]
• Create an empty list  myList = [ ]
• Size of a list  myList.size()
• Accessing an element of list  myList.get( 1 ) or myList[ 1 ] are same.
• Add elements to a list  myList << 0 << -1 << ‘hello’
• Add a list to a list  myList << [1,2] << someOtherList
• New ways of adding elements to a list  myList += 3; myList += [3,5]
• Flattening a list of lists
[ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
• Nulls are inserted if required.
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
Lists contd..
• Closures as a way to do common updates
myList = myList.collect { it * 2 }
• Closures as a way of operations
[1, 2, 3].find{ it > 1 } == 2
[1, 2, 3].findAll{ it > 1 } == [2, 3]
Similar keywords are every and any.
• To add all elements in a list  [1,2,3,4,5,6].sum() == 21
• Other operations available on a list :
– Find max. and min. elements
– Use –(minus) sign to remove elements from a list.
– Stack operations (push, pop) can be done on a list.
– Count method gives the number of elements equal to the one passed in method call.
– Sort method will sort a list in ascending order.
Reverse will reverse a list.
Range
• Ranges allow you to create a list of sequential values.
• Ranges defined with the .. notation are inclusive, that is they contain both values.
• def myRange = 5..8 This will make a range 5,6,7,8
• A range can be in both orders, increasing, as well as decreasing.
• They are accessed same as Lists.
example: myRange += 4..-3 makes myRange as 5,6,7,8,4,3,2,1,0,-1,-2,-3
• Even characters can be added to a range. myRange += ‘a’..’d’
• And same strings with different last characters can be added myRange += ‘AAB’..’AAD’.
• They find their usage in loops. Example for(count in start..end)
• They can be used in switch statements too. Example
switch(value){
case 1..10: --------;
case 11..25: -------;
default: -------;}
• They can be used to create Lists
[ 1, *3..5, 7, *9..<12 ] == [1,3,4,5,7,9,10,11]
Maps
• Maps have been implemented in Groovy as LinkedhashMap which store elements of type
key:value. By default, Groovy takes key as a String.
• Example: def myMap = [name:“Alan", likes:“bread", id:1234]
• Empty map is defined as myMap = [ : ]
• Values in a map are accessed using key, as usually.
• Maps also act like beans so you can use the property notation to get/set items inside the
Map provided that the keys are Strings which are valid Groovy identifiers. Ex:
def map = [name:"Gromit", likes:"cheese", id:1234]
assert map.name == "Gromit"
assert map.id == 1234
• Similar operations as that on Lists can be performed on Maps too.
Expandos (The Dynamic Object)
• An Expando is like a Map in Groovy or an object in Javascript that do not have to have their
properties in advance.
• It allows you to create dynamic objects by making use of Groovy's closure mechanisms.
• An Expando is different from a map in that you can provide synthetic methods that you can
call on the object.
• Example:
def player = new Expando()
player.name = "Dierk"
player.greeting = { "Hello, my name is $name" }
println player.greeting()
player.name = "Jochen"
println player.greeting()
Note: The closure has access to the properties assigned to the Expando, even though these
values may change over time.
Agenda
• Introduction to Groovy
• Key Features
• Closures
• Operator Overloading
• Array Slicing and looping
• Collections
• Dynamic Methods/Mixins and Properties
• Regular Expressions
• File IO
• Database Operations
• Unified Field and Programming Languages
Groovy Way of Handling…
– Dynamic Methods and Properties
– Regular Expressions
– File I/O
– Database Connectivity
Dynamic Method Invocation
• You can invoke a method even if you don't know the method name until it is
invoked:
class Dog
{ def bark() { println "woof!" }
def sit() { println "(sitting)" }
def jump() { println "boing!" }
}
def doAction( animal, action ){
animal."$action"() //action name is passed at invocation
}
def rex = new Dog()
doAction( rex, "bark" ) //prints 'woof!‘
doAction( rex, "jump" ) //prints 'boing!'
Dynamic Methods/mixins
george = new Wombat()
george.mixin("say") { something-> println something }
george.say("Hello, world!")
george = new Wombat().mixin(FighterType)
william = new Wombat()
georage.getFighter() // returns
william.getFighter()//error
Dynamic Properties
• You can also override property access using the getProperty and setProperty
property access hooks, Dynamically
class Expandable
{
def storage = [:] //Empty MAP
def getProperty(String name) { storage[name] } //AUTO RETURN
void setProperty(String name, value) { storage[name] = value }
}
def e = new Expandable()
e.foo = "bar"
println e.foo //OUTPUT: bar
Regular Expressions
• Groovy supports regular expressions natively using the ~"pattern" expression,
• Which compiles a Java Pattern object from the given pattern string.
• Groovy also supports the =~ (create Matcher) and ==~ (matches regex) operators.
• Packages that are used in Groovy for RegEx
– import java.util.regex.Matcher
– import java.util.regex.Pattern
• Regular expression support is imported from Java.
def pattern = ~/foo/
assert pattern instanceof Pattern
assert pattern.matcher("foo").matches()
def matcher = "cheesecheese" =~ /cheese/
assert matcher instanceof Matcher
answer = matcher.replaceAll("edam")
def cheese = ("cheesecheese" =~ /cheese/).replaceFirst("nice") assert
cheese == "nicecheese"
Works with standard Java Reader/Writer , InputStream/OutputStream ,File and URL classes
Message Passing … Using Closures
new File("foo.txt").eachLine { line -> println(line) }
Don’t Bother about Resource Closing Mechanism Groovy Methods will handle it.
def fields = ["a":"1", "b":"2", "c":"3"]
new File("Foo.txt").withWriter { out -> fields.each() { key, value ->
out.writeLine("${key}=${value}") }
}
- No Reader / Writer Object Handling
Handle the resource for you via a closure - which will automatically close down any resource
if an exception occurs
- No Data Piping (Stream Management)
- No Exception Handling
The eachLine() method ensures that the file resource is correctly closed. Similarly if an
exception occurs while reading, the resource will be closed too.
File Input / Output
Executing External Processes
Groovy provides a simple way to execute command line processes.
def process = "ls -l".execute()
process.in.eachLine { line -> println line }
====================
Process p = "cmd /c dir".execute()
println "${p.text}“
====================
def initialSize = 4096
def outStream = new ByteArrayOutputStream(initialSize) //STREAMS
def errStream = new ByteArrayOutputStream(initialSize)
def proc = "ls.exe".execute()
proc.consumeProcessOutput(outStream, errStream)
proc.waitFor() println 'out:n' + outStream println 'err:n' + errStream
SQL can be more Groovy - 1
• You can perform queries and SQL statements, passing in variables easily with
proper handling of statements, connections and exception handling.
import groovy.sql.Sql
def foo = 'cake‘
def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb",
"user",
"pswd",
"com.mysql.jdbc.Driver")
database.eachRow("select * from FOOD where type=${foo}“)
{ println "Smith likes ${it.name}" }
Thanks to closures.
SQL can be more Groovy - 2
• You can perform queries and SQL statements, passing in variables easily with
proper handling of statements, connections and exception handling.
import groovy.sql.Sql
def foo = 'cheese‘
def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb",
"user",
"pswd",
"com.mysql.jdbc.Driver")
def answer = 0
sql.eachRow("select count(*) from FOOD where type=${foo}")
{ row -> answer = row[0] }
Println (“Our menu has $answer dishes to choose from!)
Thanks to closures.
SQL can be more Groovy - 3
• You can perform queries and SQL statements, passing in variables easily with
proper handling of statements, connections and exception handling.
import groovy.sql.Sql
def foo = 'cheese‘
def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb",
"user",
"pswd",
"com.mysql.jdbc.Driver")
def food = database.dataSet('FOOD')
def cheese = food.findAll { it.type == 'cheese' }
cheese.each { println “${it.name} will be delicious" }
Thanks to closures.
Why to Thank Closures ?
A typical JDBC Program should have these Steps
1. Loading a database driver
2. Creating a oracle JDBC Connection
3. Creating a JDBC Statement object
4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//or any other driver
} catch(Exception x){
System.out.println( "Unable to load the driver class!" );
}
try {
Connection con = DriverManager.getConnection(url, userid, password);
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
String createString="create table Employees(“+"Employee_ID INTEGER,”+"Name VARCHAR(30))";
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Reduced code noise in Groovy
-Simple code is beautiful code
Groovy Will Handle all those common tasks for you,
- including Exception Handling, Connection - ResultSet Closing, etc..
import groovy.sql.Sql
class GroovySqlExample1
{
static void main(args)
{
database = Sql.newInstance("jdbc:mysql://localhost:3306/words",
"words", "words", "org.gjt.mm.mysql.Driver")
database.eachRow("select * from word")
{ row | println row.word_id + " " + row.spelling } //CLOSURE
wid = 999
spelling = "Nefarious"
pospeech = "Adjective"
database.execute("insert into word (word_id, spelling, part_of_speech)
values (${wid}, ${spelling}, ${pospeech})")
val = database.execute("select * from word where word_id = ?", [5])
//Negetive Indexing
sql.eachRow("select * from word")
{ grs | println "-1 = " + grs.getAt(-1) //prints part_of_speech
println "2 = " + grs.getAt(2) //prints part_of_speech }
}
}
Groovy unleashed

More Related Content

What's hot

PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
 
Scala jeff
Scala jeffScala jeff
Scala jeffjeff kit
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3Matthew Turland
 
SPL: The Undiscovered Library - DataStructures
SPL: The Undiscovered Library -  DataStructuresSPL: The Undiscovered Library -  DataStructures
SPL: The Undiscovered Library - DataStructuresMark Baker
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)David de Boer
 
Php data structures – beyond spl (online version)
Php data structures – beyond spl (online version)Php data structures – beyond spl (online version)
Php data structures – beyond spl (online version)Mark Baker
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slidejonycse
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Bozhidar Boshnakov
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance TriviaNikita Popov
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functionalHackraft
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1Hackraft
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsMark Baker
 

What's hot (20)

PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)
 
Scala jeff
Scala jeffScala jeff
Scala jeff
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
SPL: The Undiscovered Library - DataStructures
SPL: The Undiscovered Library -  DataStructuresSPL: The Undiscovered Library -  DataStructures
SPL: The Undiscovered Library - DataStructures
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
 
Php data structures – beyond spl (online version)
Php data structures – beyond spl (online version)Php data structures – beyond spl (online version)
Php data structures – beyond spl (online version)
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 

Viewers also liked

Day3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_en
Day3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_enDay3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_en
Day3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_enicgfmconference
 
Summer training vhdl
Summer training vhdlSummer training vhdl
Summer training vhdlArshit Rai
 
Raby yasou3 el ghaly (2)
Raby yasou3 el ghaly (2)Raby yasou3 el ghaly (2)
Raby yasou3 el ghaly (2)At Minacenter
 
Otevrena data v CR - aktualni stav (brezen 2013)
Otevrena data v CR - aktualni stav (brezen 2013)Otevrena data v CR - aktualni stav (brezen 2013)
Otevrena data v CR - aktualni stav (brezen 2013)Martin Necasky
 
Audience feedback survey monkey
Audience feedback   survey monkeyAudience feedback   survey monkey
Audience feedback survey monkeyEttyHope
 
Ms excel-da-2062dari#2
Ms excel-da-2062dari#2Ms excel-da-2062dari#2
Ms excel-da-2062dari#2spankarmyman
 
Thomas Paine[1]
Thomas Paine[1]Thomas Paine[1]
Thomas Paine[1]spillwd
 
Nadoceds ppt
Nadoceds pptNadoceds ppt
Nadoceds pptnado-web
 
Wtl 2010
Wtl 2010Wtl 2010
Wtl 2010sap382s
 
20150116株式会社火燵研修ver.1.9.8
20150116株式会社火燵研修ver.1.9.820150116株式会社火燵研修ver.1.9.8
20150116株式会社火燵研修ver.1.9.8hoshinakamata1
 
suzhou powerpint presantion
suzhou powerpint presantionsuzhou powerpint presantion
suzhou powerpint presantionkyungtae97
 
Commscope-Andrew C240-JMSM-65
Commscope-Andrew C240-JMSM-65Commscope-Andrew C240-JMSM-65
Commscope-Andrew C240-JMSM-65savomir
 

Viewers also liked (17)

Day3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_en
Day3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_enDay3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_en
Day3 sp1 icgfm-aid_data presentation_final_2014_dustinhomer_en
 
8 березня
8 березня8 березня
8 березня
 
Summer training vhdl
Summer training vhdlSummer training vhdl
Summer training vhdl
 
Raby yasou3 el ghaly (2)
Raby yasou3 el ghaly (2)Raby yasou3 el ghaly (2)
Raby yasou3 el ghaly (2)
 
Otevrena data v CR - aktualni stav (brezen 2013)
Otevrena data v CR - aktualni stav (brezen 2013)Otevrena data v CR - aktualni stav (brezen 2013)
Otevrena data v CR - aktualni stav (brezen 2013)
 
Audience feedback survey monkey
Audience feedback   survey monkeyAudience feedback   survey monkey
Audience feedback survey monkey
 
Ms excel-da-2062dari#2
Ms excel-da-2062dari#2Ms excel-da-2062dari#2
Ms excel-da-2062dari#2
 
Thomas Paine[1]
Thomas Paine[1]Thomas Paine[1]
Thomas Paine[1]
 
Toetsen in de elo
Toetsen in de eloToetsen in de elo
Toetsen in de elo
 
BBC foaf talk
BBC foaf talkBBC foaf talk
BBC foaf talk
 
Nadoceds ppt
Nadoceds pptNadoceds ppt
Nadoceds ppt
 
Wtl 2010
Wtl 2010Wtl 2010
Wtl 2010
 
The Geeza'S
The Geeza'SThe Geeza'S
The Geeza'S
 
20150116株式会社火燵研修ver.1.9.8
20150116株式会社火燵研修ver.1.9.820150116株式会社火燵研修ver.1.9.8
20150116株式会社火燵研修ver.1.9.8
 
suzhou powerpint presantion
suzhou powerpint presantionsuzhou powerpint presantion
suzhou powerpint presantion
 
Commscope-Andrew C240-JMSM-65
Commscope-Andrew C240-JMSM-65Commscope-Andrew C240-JMSM-65
Commscope-Andrew C240-JMSM-65
 
Netto Azubi-Ehrung
Netto Azubi-Ehrung Netto Azubi-Ehrung
Netto Azubi-Ehrung
 

Similar to Groovy unleashed

Groovy presentation
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Joachim Baumann
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreWeb Zhao
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl courseMarc Logghe
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekyoavrubin
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in GroovyJim Driscoll
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redisjimbojsb
 

Similar to Groovy unleashed (20)

Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Groovy
GroovyGroovy
Groovy
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in Groovy
 
Perl basics for pentesters part 2
Perl basics for pentesters part 2Perl basics for pentesters part 2
Perl basics for pentesters part 2
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
05php
05php05php
05php
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 

Recently uploaded

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Groovy unleashed

  • 1. Welcome To… Groovy! – The Catalyst Language for Programmers Presentation By -Isuru Samaraweera
  • 2. Agenda • Introduction to Groovy • Key Features • Closures • Operator Overloading • Array Slicing and looping • Collections • Dynamic Methods/Mixins and Properties • Regular Expressions • File IO • Database Operations
  • 3. What is Groovy? • Java-like scripting language for the JVM • Dynamic Language • Inspired by Ruby,Python,SmallTalk and Perl • Open Source language – Apache2.0 license – dev@groovy.apache.org – users@groovy.apache.org • Seamless integration with Java – Follow the mantra…Java is Groovy,Groovy is Java  • Web Application Development – Groovelets,GSP,Grapplet • Sole alternative dynamic language for the JVM fully supporting frameworks like Spring, Hibernate – Grails – Coding by Convention • Mobile Application Support  • Official web site http://www.groovy-lang.org/
  • 4. Installation and Configuration • Prerequisites – JDK1.4 or higher installed and system path should point to %JAVA_HOME%/bin • Download Groovy distribution from http://www.groovy-lang.org/download.html • Unzip the groovy archive – Set the GROOVY_HOME environment variables. – Add %GROOVY_HOME%bin to your system path – Try opening groovyConsole.bat • Eclipse Plug-in – https://github.com/groovy/groovy-eclipse/wiki • IntelliJ Idea Plug-in-Community edition – http://www.jetbrains.net
  • 5. Key Language Features • Pure Object Oriented 3.times { println "hello" } • Dynamic Typing/Duck typing • Closures • Currying • Operator Overloading • Array Slicing • Dynamic Methods • Expandos • Static imports • Annotations • Covariant return types • POGO support • Mixins
  • 6. Java Vs. Groovy No of line Comparison • Java Code for (String item : new String [] {"Rod", "Carlos", "Chris"}) { if (item.length() <= 4) { System.out.println(item); } } • Groovy Code ["Rod", "Carlos", "Chris"].findAll{it.size() <= 4}.each{println it}
  • 7. /*A Typical Groovy Class*/ class Customer { // properties Integer id String name Date dob // sample code static void main(args) { def customer = new Customer(id:1, name:"Gromit", dob:new Date()) println("Hello ${customer.getName()}") customer.setName(“James”) println("Hello ${customer.getName()}") } } Java Vs. Groovy No of line Comparison
  • 8. Closures • A block of code that can access variables in the scope where it is declared or outside • Higher order functions • A closure will have a default parameter named it if you do not define one def x = { println it } • And here's how you call it (two options): x('Hello, world!') x.call('Hello, world')
  • 9. Closure Arguments(Typed or Untyped) • Untyped Arguments def isList = { i -> i instanceof List } if (isList([])) { println "This is a List“ } • Typed Arguments def prefix = { String s -> while (s.length() < 17) { s = "0$s" } s // return keyword is not required } def id = prefix "1234" // parentheses are not required
  • 10. Closures as arguments and Recursion • Closures can be passed as arguments • Consider the each() method on java.util.Map: System.properties.each { println it.key } • Recursion • lambda is annonymous  def fac = { int i -> i == 1 ? 1 : i * call(i - 1) } println fac(10)
  • 11. Currying • Currying is a programming technique that transforms a function into another while fixing one or more input values def multiply = { x, y -> return x * y } // closure def triple = multiply.curry(3) // triple = { y -> return 3 * y } def quadruple = multiply.curry(4) // quadruple = { y -> return 4 * y } def p = triple.call(4) // explicit call def q = quadruple(5) // implicit call println "p: ${p}" // p is 12 println "q: ${q}" // q is 20
  • 12. Currying contd.. def lSubtract = { x, y -> return x - y } def rSubtract = { y, x -> return x - y } def dec = rSubtract.curry(1) // dec = { x -> return x - 1 } def cent = lSubtract.curry(100) // cent = { y -> return 100 - y } def p = dec.call(5) // explicit call def q = cent(25) // implicit call println "p: ${p}" // p is 4 println "q: ${q}" // q is 75
  • 13. Variable Arguments int sum(int... someInts) { //ellipsis notation def total = 0 for (int i = 0; i < someInts.size(); i++) total += someInts[i] return total } assert sum(1) == 1 assert sum(1, 2) == 3
  • 14. Operator Overloading ! - 1 it does it by following a naming convention for methods. Operation Method a+b a.Plus(b) a-b a.minus(b) a*b a.multiply(b) a**b a.power(b) a/b a.div(b) a % b a.mod(b) a | b a.or(b) a & b a.and(b)
  • 15. Operator Overloading ! - 2 a ^ b a.xor(b) a++ or ++a a.next() a-- or --a a.previous() a[b] a.getAt(b) a[b] = c a.putAt(b, c) a << b a.leftShift(b) a >> b a.rightShift(b) switch(a) { case(b) : } b.isCase(a) ~a a.bitwiseNegate() -a a.negative() +a a.positive()
  • 16. Operator Overloading ! - 3 text = "Programing" - "ing" + "er" assert "Programer" == text list = [1,2,3] list += [4,5,6] assert [1,2,3,4,5,6] == list list << 7 // list.leftShift(7) -> list.add(7) assert [1,2,3,4,5,6,7] == list s = "A" * 5 assert s == "AAAAA“ s = "ABCDE" assert "BC" == s[1..2] s.getAt([1..2]); ranged operation assert "C" == s[2] // s.getAt(2) -> s.charAt(2)
  • 17. Looping • General for loop and while loop • Classical for loop def x = 0 for ( i in 0..9 ) //RANGE { x += i } assert x == 45 // iterate over a list • Iterate over a list x = 0 for ( i in [0, 1, 2, 3, 4] ) //LIST { x += i } assert x == 10
  • 18. def a = [1,2,3,4,5] a[1..-1] OUTPUT : [2, 3, 4, 5] def a = [1,2,3,4,5] a[1..<-1] OUTPUT: [2, 1] Array Slicing
  • 19. Elvis Operator • Elvis Operator alternative to ternary operator //traditional ternary operator String name = “Sam"; String displayName = name != null ? name : "Unknown"; //elvis operator String name = “Sam" String displayName = name ? name : "Unknown" //eliminate DRY String name = “Sam" String displayName = name ?: "Unknown"
  • 20. Agenda • Introduction to Groovy • Key Features • Closures • Operator Overloading • Array Slicing and looping • Collections • Dynamic Methods and Properties • Regular Expressions • File IO • Database Operations • Unified Field and Programming Languages
  • 21. Collections in Groovy – Lists – Ranges – Maps – Expandos (Dynamic Objects)
  • 22. Lists • Lists have been implemented in Groovy as ArrayLists which store elements of type Object. • Create a list  def myList = [1,2,3.6,-9.01,“hello”,“a string”, new Date()] • Create an empty list  myList = [ ] • Size of a list  myList.size() • Accessing an element of list  myList.get( 1 ) or myList[ 1 ] are same. • Add elements to a list  myList << 0 << -1 << ‘hello’ • Add a list to a list  myList << [1,2] << someOtherList • New ways of adding elements to a list  myList += 3; myList += [3,5] • Flattening a list of lists [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9] • Nulls are inserted if required. list = ['a', 'b', 'z', 'e', 'u', 'v', 'g'] list[8] = 'x' list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
  • 23. Lists contd.. • Closures as a way to do common updates myList = myList.collect { it * 2 } • Closures as a way of operations [1, 2, 3].find{ it > 1 } == 2 [1, 2, 3].findAll{ it > 1 } == [2, 3] Similar keywords are every and any. • To add all elements in a list  [1,2,3,4,5,6].sum() == 21 • Other operations available on a list : – Find max. and min. elements – Use –(minus) sign to remove elements from a list. – Stack operations (push, pop) can be done on a list. – Count method gives the number of elements equal to the one passed in method call. – Sort method will sort a list in ascending order. Reverse will reverse a list.
  • 24. Range • Ranges allow you to create a list of sequential values. • Ranges defined with the .. notation are inclusive, that is they contain both values. • def myRange = 5..8 This will make a range 5,6,7,8 • A range can be in both orders, increasing, as well as decreasing. • They are accessed same as Lists. example: myRange += 4..-3 makes myRange as 5,6,7,8,4,3,2,1,0,-1,-2,-3 • Even characters can be added to a range. myRange += ‘a’..’d’ • And same strings with different last characters can be added myRange += ‘AAB’..’AAD’. • They find their usage in loops. Example for(count in start..end) • They can be used in switch statements too. Example switch(value){ case 1..10: --------; case 11..25: -------; default: -------;} • They can be used to create Lists [ 1, *3..5, 7, *9..<12 ] == [1,3,4,5,7,9,10,11]
  • 25. Maps • Maps have been implemented in Groovy as LinkedhashMap which store elements of type key:value. By default, Groovy takes key as a String. • Example: def myMap = [name:“Alan", likes:“bread", id:1234] • Empty map is defined as myMap = [ : ] • Values in a map are accessed using key, as usually. • Maps also act like beans so you can use the property notation to get/set items inside the Map provided that the keys are Strings which are valid Groovy identifiers. Ex: def map = [name:"Gromit", likes:"cheese", id:1234] assert map.name == "Gromit" assert map.id == 1234 • Similar operations as that on Lists can be performed on Maps too.
  • 26. Expandos (The Dynamic Object) • An Expando is like a Map in Groovy or an object in Javascript that do not have to have their properties in advance. • It allows you to create dynamic objects by making use of Groovy's closure mechanisms. • An Expando is different from a map in that you can provide synthetic methods that you can call on the object. • Example: def player = new Expando() player.name = "Dierk" player.greeting = { "Hello, my name is $name" } println player.greeting() player.name = "Jochen" println player.greeting() Note: The closure has access to the properties assigned to the Expando, even though these values may change over time.
  • 27. Agenda • Introduction to Groovy • Key Features • Closures • Operator Overloading • Array Slicing and looping • Collections • Dynamic Methods/Mixins and Properties • Regular Expressions • File IO • Database Operations • Unified Field and Programming Languages
  • 28. Groovy Way of Handling… – Dynamic Methods and Properties – Regular Expressions – File I/O – Database Connectivity
  • 29. Dynamic Method Invocation • You can invoke a method even if you don't know the method name until it is invoked: class Dog { def bark() { println "woof!" } def sit() { println "(sitting)" } def jump() { println "boing!" } } def doAction( animal, action ){ animal."$action"() //action name is passed at invocation } def rex = new Dog() doAction( rex, "bark" ) //prints 'woof!‘ doAction( rex, "jump" ) //prints 'boing!'
  • 30. Dynamic Methods/mixins george = new Wombat() george.mixin("say") { something-> println something } george.say("Hello, world!") george = new Wombat().mixin(FighterType) william = new Wombat() georage.getFighter() // returns william.getFighter()//error
  • 31. Dynamic Properties • You can also override property access using the getProperty and setProperty property access hooks, Dynamically class Expandable { def storage = [:] //Empty MAP def getProperty(String name) { storage[name] } //AUTO RETURN void setProperty(String name, value) { storage[name] = value } } def e = new Expandable() e.foo = "bar" println e.foo //OUTPUT: bar
  • 32. Regular Expressions • Groovy supports regular expressions natively using the ~"pattern" expression, • Which compiles a Java Pattern object from the given pattern string. • Groovy also supports the =~ (create Matcher) and ==~ (matches regex) operators. • Packages that are used in Groovy for RegEx – import java.util.regex.Matcher – import java.util.regex.Pattern • Regular expression support is imported from Java. def pattern = ~/foo/ assert pattern instanceof Pattern assert pattern.matcher("foo").matches() def matcher = "cheesecheese" =~ /cheese/ assert matcher instanceof Matcher answer = matcher.replaceAll("edam") def cheese = ("cheesecheese" =~ /cheese/).replaceFirst("nice") assert cheese == "nicecheese"
  • 33. Works with standard Java Reader/Writer , InputStream/OutputStream ,File and URL classes Message Passing … Using Closures new File("foo.txt").eachLine { line -> println(line) } Don’t Bother about Resource Closing Mechanism Groovy Methods will handle it. def fields = ["a":"1", "b":"2", "c":"3"] new File("Foo.txt").withWriter { out -> fields.each() { key, value -> out.writeLine("${key}=${value}") } } - No Reader / Writer Object Handling Handle the resource for you via a closure - which will automatically close down any resource if an exception occurs - No Data Piping (Stream Management) - No Exception Handling The eachLine() method ensures that the file resource is correctly closed. Similarly if an exception occurs while reading, the resource will be closed too. File Input / Output
  • 34. Executing External Processes Groovy provides a simple way to execute command line processes. def process = "ls -l".execute() process.in.eachLine { line -> println line } ==================== Process p = "cmd /c dir".execute() println "${p.text}“ ==================== def initialSize = 4096 def outStream = new ByteArrayOutputStream(initialSize) //STREAMS def errStream = new ByteArrayOutputStream(initialSize) def proc = "ls.exe".execute() proc.consumeProcessOutput(outStream, errStream) proc.waitFor() println 'out:n' + outStream println 'err:n' + errStream
  • 35. SQL can be more Groovy - 1 • You can perform queries and SQL statements, passing in variables easily with proper handling of statements, connections and exception handling. import groovy.sql.Sql def foo = 'cake‘ def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver") database.eachRow("select * from FOOD where type=${foo}“) { println "Smith likes ${it.name}" } Thanks to closures.
  • 36. SQL can be more Groovy - 2 • You can perform queries and SQL statements, passing in variables easily with proper handling of statements, connections and exception handling. import groovy.sql.Sql def foo = 'cheese‘ def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver") def answer = 0 sql.eachRow("select count(*) from FOOD where type=${foo}") { row -> answer = row[0] } Println (“Our menu has $answer dishes to choose from!) Thanks to closures.
  • 37. SQL can be more Groovy - 3 • You can perform queries and SQL statements, passing in variables easily with proper handling of statements, connections and exception handling. import groovy.sql.Sql def foo = 'cheese‘ def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver") def food = database.dataSet('FOOD') def cheese = food.findAll { it.type == 'cheese' } cheese.each { println “${it.name} will be delicious" } Thanks to closures.
  • 38. Why to Thank Closures ? A typical JDBC Program should have these Steps 1. Loading a database driver 2. Creating a oracle JDBC Connection 3. Creating a JDBC Statement object 4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet. try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//or any other driver } catch(Exception x){ System.out.println( "Unable to load the driver class!" ); } try { Connection con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } String createString="create table Employees(“+"Employee_ID INTEGER,”+"Name VARCHAR(30))"; try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); }
  • 39. Reduced code noise in Groovy -Simple code is beautiful code Groovy Will Handle all those common tasks for you, - including Exception Handling, Connection - ResultSet Closing, etc.. import groovy.sql.Sql class GroovySqlExample1 { static void main(args) { database = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words", "words", "org.gjt.mm.mysql.Driver") database.eachRow("select * from word") { row | println row.word_id + " " + row.spelling } //CLOSURE wid = 999 spelling = "Nefarious" pospeech = "Adjective" database.execute("insert into word (word_id, spelling, part_of_speech) values (${wid}, ${spelling}, ${pospeech})") val = database.execute("select * from word where word_id = ?", [5]) //Negetive Indexing sql.eachRow("select * from word") { grs | println "-1 = " + grs.getAt(-1) //prints part_of_speech println "2 = " + grs.getAt(2) //prints part_of_speech } } }