The document summarizes a presentation on Groovy and its ecosystem given by Guillaume Laforge. The presentation introduced Groovy's syntax, features, and rich ecosystem including APIs for markup builders, templating, Swing UI creation, SQL, JMX, and Ant integration. It also discussed Groovy's tight integration with Java and the Spring framework.
12. Groovy
intro and ecosystem
by Guillaume Laforge
Groovy Project Manager
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
13. Guillaume Laforge
• Groovy Project Manager
• JSR-241 Spec Lead
• Head of Groovy Development
at SpringSource / VMWare
• Initiator of the Grails framework
• Castcodeurs! (French Java podcast)
• Co-author of Groovy in Action
• Speaker: JavaOne, QCon, JavaZone, Sun TechDays,
Devoxx, The Spring Experience, SpringOne, JAX,
Dynamic Language World, IJTC, and more...
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13
14. Contact information
• Email
– glaforge@vmware.com
• Twitter
– @glaforge
• Blog
– http://glaforge.free.fr/blog/groovy
• Groovy mailing-lists
– http://old.nabble.com/codehaus---Groovy-f11866.html
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14
15. A little story
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15
16. nda
Ag e • Introduction to Groovy
– syntax basics
– useful APIs
• Rich ecosystem
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16
17. nda
Ag e • Introduction to Groovy
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17
18. Groovy in a few words
• Groovy is a dynamic language for the JVM
– with a Meta Object Protocol
– compiles directly to bytecode
– provides seamless Java interoperability
• Groovy was created in 2003, is hosted at
Codehaus, and is under the Apache license
• Relaxed grammar deriving from Java 5
– annotations, generics, static imports, enums, varargs...
– borrowed good ideas from Ruby, Python, Smalltalk
–flat learning curve for Java developers
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18
19. Features at a glance
• Fully Object-Oriented: same as Java
• Closures: reusable/assignable code blocks
• Properties: no more boring getters/setters
• Optional typing: your choice!
• Various shortcut notations: native syntax for lists,
maps, ranges, regex...
• Handy wrapper APIs: XML, JDBC, template
engine, Swing UIs, collection methods...
• Strong ability for authoring DSLs
• A rich and lively ecosystem of additional modules
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19
20. Mandatory Hello World
• Java public class HelloWorld {
private String name;
style...
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String greet() {
return "Hello " + name;
}
) {
public static void main(String[] args
ld();
HelloWorld helloWorld = new HelloWor
helloWorld.setName("Groovy");
));
System.out.println(helloWorld.greet(
}
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20
21. Mandatory Hello World
• Groovy public class HelloWorld {
private String name;
style...
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String greet() {
return "Hello " + name;
}
) {
public static void main(String[] args
ld();
HelloWorld helloWorld = new HelloWor
helloWorld.setName("Groovy");
));
System.out.println(helloWorld.greet(
}
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21
22. Mandatory Hello World
• Groovy
style...
class HelloWorld {
String name
String greet() { "Hello $name" }
}
def helloWorld =
new HelloWorld(name: "Groovy")
println helloWorld.greet()
Take 2!
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22
23. Syntax basics
• Grammar deriving from Java 5
– annotations, enums, static imports, generics...
• Usual Java keywords, control structures...
• Same APIs
– strings, collections, regex, security, threading...
• Same Object Orientation
– No impedance mismatch!
– Flat learning curve for Java developers!
• But offers additional native syntax constructs
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23
24. On Java interoperability
• Groovy is the alternative JVM language providing
the best integration with Java JInterface GInterface
<<implements>> <<implements>>
• Mix and match Groovy and Java GClass JClass
– even with a cyclic language dependency
JClass GClass
• Groovy comes with a «joint compiler»
– compiling Groovy as Java stubs
– calling the Javac compiler
– compiling the Groovy classes
• Excellent IDE support (Eclipse/IntelliJ/NetBeans)
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24
25. Native syntax constructs
• Lists
def someNumbers = [1, 2, 3, 5, 7, 11]
• Ranges
def range = 1..18
• Maps
def states = [CA: ‘California’, TX: ‘Texas’]
• Regular expressions
~/fo*/
‘foo’ =~ /fo*/
‘foo’ ==~ /fo*/
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25
26. GStrings
• Sexiest feature of the language!
• Ability to embed variables
inside strings
def firstname = "Guillaume"
def lastname = "${firstname} Laforge"
e"
assert lastname == "Guillaume Laforg
def date = "Today is: ${new Date()}"
def multiline = """Hello,
How are you?"""
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26
27. Closures
• A reusable / assignable code block
– CS 101 for a proper definition
}
def helloPrinter = { println "hello"
helloPrinter()
def twice = { it * 2 }
assert twice(3) == 6
assert twice('foo') == 'foofoo'
def mult = { int a, int b -> a * b }
def multBy5 = mult.curry(5)
assert multBy5(4) == 20
def apply(closure) { closure() }
apply { /* do something */ }
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27
28. Time savers
• The «Groovy Truth»
def blank = ""; assert !blank
def empty = []; assert !empty
• Safe graph navigation
def order = null
assert order?.customer?.address == null
• Elvis operator
def name = customer.name ?: "Unknown"
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28
29. GDK: Groovy Development Kit
• Thanks to Groovy’s dynamic nature, we «decorate»
existing JDK classes to add new handy methods
– we can’t extend java.io.File or java.lang.String, can we?
n it }
new File("apache.log").eachLine { printl
(1..100).findAll { it % 2 == 1 }
speakers.groupBy { it.lastname }
"123".padLeft(5, '0')
"ls -la".execute()
)
"R3Jvb3Z5IHJvY2tzIQ==".decodeBase64(
Th read.start { /* code to execute */ }
• Add your own extensions!
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29
30. Now onto APIs!
• After this language crash course,
let’s have a look at the APIs Groovy provides:
– Markup builders and slurpers
– Swing builder
– Template engine
– JDBC facilities
– JMX builder
– Ant scripting
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30
31. Markup builder
• Producing markup content
new MarkupBuilder().languages {
language(name: "Groovy") {
feature(coolness: "low", "SQL")
)
feature(coolness: "high", "Template"
}
language(name: "Perl")
}
• Will yield
<languages>
<language name = "Groovy">
<feature coolness="low">SQL</feature>
ature>
<feature coolness="high">Template</fe
</language>
<language name: "Perl"/>
</languages>
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31
32. XML slurper
• Easily parsing and consumming XML content
• Navigating through the nodes as an object graph
def xml = """
<languages>
<language name="Groovy">
<feature coolness="low">SQL</feature>
ature>
<feature coolness="high">Template</fe
</language>
<language name="Perl"/>
</languages>"""
(xml)
def root = new XmlSlurper().parseText
t()
println root.language.feature[1].tex
] == "low" }
root.lan guage.feature.findAll{ it['@coolness'
.each{ println it.text() }
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32
33. Swing builder
• Creating Swing UI with a programmatic descriptive
Domain-Specific Language
import groovy.swing.SwingBuilder
import java.awt.BorderLayout as BL
def count = 0
new SwingBuilder().edt { ow: true) {
fram e(title: 'Frame', size: [300,300], sh
borderLayout()
tton!",
textlabel = label(text: "Click the bu
constraints: BL.NORTH)
button(text: 'Click Me',
actionPerformed: {
count++
me(s)."
textlabel.text = "Clicked ${count} ti
println "clicked"},
constraints:BL.SOUTH)
}
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33
34.
35. Template engine
• Templating capabilities, with embedded GStrings,
and scriptlet notation
ne
import groovy.text.SimpleTemplateEngi
def text = '''
Dear <%= firstname %>
%>.
So nice to meet you in <% print city
${signed}'''
e",
def binding = [fir stname: "Guillaume", city: "The Hagu
signed: "MrG"]
()
def engine = new SimpleTemplateEngine
ke(binding)
temp late = engine.createTemplate(text).ma
• A template servlet also exists
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35
36. JDBC facilities
• Transparent resource handling thanks to closures
)
def sql = Sql.newInstance(url, usr, pwd, driverar)")
sql.execut e("insert into table values ($foo, $b, b])
, [a
sql.ex ecute("insert into table values(?,?)" .name }
it
sql.ea chRow("select * from USER") { print
ER")
def list = sql.rows("select * from US
• A poorman’s dataset notion
def set = sql.dataSet("USER")
set.add(name: "Johnny", age: 33) ame }
set.each { user -> println user.n 42 }
se t.findAll { it.age > 22 && it.age <
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36
37. JMX Builder
• Expose, configure JMX beans, export operations,
create timers, event handling with closures, and
more...
def jmx = new JmxBuilder()
def beans = jmx.export {
bean(new CpuLoadMonitor())
bean(new DiskOccupationMonitor())
}
• You could easily monitor your Spring application’s
exposed JMX beans through some Groovy script!
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37
38. Ant builder
• Script and reuse any Ant task
– FTP, SSH, Javac, file handling, etc.
new AntBuilder().sequential {
def buildClasses = "build/classes"
// create classes directory
mkdir dir: buildClasses
// compile sources
lasses
javac srcdir: "src", destdir: buildC
// jar everything
dClasses
jar destfile: "my.jar", basedir: buil
}
• Used in Gant and Gradle
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38
39. Grape: a great way for sharing
Groovy scripts
• Grape: Groovy Advanced Packagning Engine
• You can «grab» dependencies in your scripts
– first run will download the dependencies
– next runs, the dependencies will be found in the ivy
cache on your system
jdk15")
@Grab("net.sf.json-lib:json-lib:2.3:
import net.sf.json.groovy.*
assert new JsonSlurper().parseText(
new JsonGroovyBuilder().json { aume")
book(title : "Groovy in Action", author: "Guill
}.toString()
).book.title == "Groovy in Action"
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39
40. Benefits of the Groovy APIs
• Easily share scripts thanks to Grape
– no need to package JARs
–automate all repetitive tasks with Ant builder
• Simple to create reports or generate code with
markup builders or template engines
• You can migrate / inject / modify data with the
SQL facilities accessing your database through JDBC
• Create simple Swing UIs to interact with backends
• You can monitor server farms through JMX
builder
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40
41. Spring integration (1/2)
•Groovy integrated in Spring since 2.0
–ability to define beans in Groovy
–to monitor changes of Groovy beans on the filesystem
–to modify the behaviour of Groovy scripts and beans
–to inline Groovy scripts with <lang:inline-script>
<lang:groovy id="messenger"
refresh-check-delay="5000"
roovy">
script-source="classpath:Messenger.g
"Hi" />
<lang:property name="message" value=
</lang:groovy>
BookingService">
<bean id ="bookingService" class="x.y.Default
nger" />
<property name="messenger" ref="messe
</bean>
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41
42. Spring integration (2/2)
• Grails provides a Spring bean builder
– for programmatically define Spring configurations
– more flexible than pure XML declarative descriptions
)
de f bb = new grails.spring.BeanBuilder(
bb.beans {
adder(AdderImpl)
calcBean(CalcImpl)
}
t()
def ctx == bb.createApplicationContex
def calc = ctx.getBean(‘calcBean’)
println calc.doAdd(3, 4)
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42
43. nda
Ag e • The Groovy Ecosystem
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 43
44. The Groovy Ecosystem
• Many projects based on Groovy
• Serve various purposes:
– build applications (ie. frameworks)
•Grails (web apps), Gaelyk (Google App Engine),
Griffon (Swing apps)
– enhanced testing
•Easyb (BDD), Spock, Gmock (mocking), SoapUI (WS)
– help building projects
•Gant (ant sugar), Gradle (adhoc build system)
– web services interaction
•HTTPBuilder (REST), GroovyWS (SOAP)
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 44
45. Gaelyk
•Groovy on Google App Engine
– Lightweight Groovy tooking for writing
applications in Groovy on GAE/J
– Leverages Groovlets and
Groovy’s template engine
– http://gaelyk.appspot.com
• Groovy Web Console
– http://groovyconsole.appspot.com
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 45
46. GPars
• Actors, dataflow,
concurrency, and more
– for harnessing our
multicore platforms
• GPars web site:
– http://gpars.codehaus.org
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 46
47. Easyb (1/4)
• From the website:
– « Easyb is a behavior driven development (BDD)
framework for the Java platform. By using a specification
based Domain-Specific Language, Easyb aims to enable
executable, yet readable documentation »
• Write specifications in Groovy
• Run them from CLI, Maven, or Ant
– provides various report formats
• BDD == given/when/then paradigm
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 47
48. Easyb (2/4)
• First, let’s write a story
given "an invalid zip code"
itialized"
and "given the zipcodevalidator is in
lid zip code"
wh en "validate is invoked with the inva
return false"
then "the validator instance should
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 48
49. Easyb (3/4)
• Let’s write the test itself
given "an invalid zip code", {
invalidzipcode = "221o1"
}
d", {
and "giv en the zipcodevalidator is initialize
zipvalidate = new ZipCodeValidator()
}
p code", {
when "val idate is invoked with the invalid zi
pcode)
value = zipvalidate.validate(invalidzi
}
e", {
then "the validator instance should return fals
value.shouldBe false
}
• Afterwards, write the code that make the test pass
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 49
50. Easyb (4/4)
• There’s also the specification format
instance", {
before "initialize zipcodevalidator
;
zipvalidate = new ZipCodeValidator()
}
{
it "should deny invalid zip codes", zip ->
[" 221o1", "2210", "22010-121o"].each {
zipvalidate.validate(zip).is false
}
}
{
it "should accept valid zip codes",
{ zip ->
["22101", "22100", "22010-1210"].each
ue
zipvalidate.validate(zip).shouldBe tr
}
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 50
52. Spock (1/3)
• From the horse’s mouth:
– « Spock is a testing and specification framework for Java
and Groovy applications. What makes it stand out from
the crowd is its beautiful and highly expressive
specification language. »
cification {
cl ass HelloSpock extends spock.lang.Spe
() {
def "can you figure out what I'm up to?"
expect:
name.size() == size
where:
name | size
"Kirk" | 4
"Spock" | 5
"Scotty" | 6
}
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 52
53. Spock (2/3)
• Extensible (but transparent) use of AST
transformations to «pervert» the Groovy language
– reuse of labels for the BDD actions
• Spock brought Groovy 1.7’s enhanced asserts
Condition not satisfied:
max(a, b) == c
| | | | |
3 1 3 | 2
false
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 53
54. Spock (3/3)
• Another example of the expressive language
once"() {
def "subscribe rs receive published events at least
when: publisher.send(event)
vent)
then: (1.._) * subscriber.receive(e
"]
where: event << ["started", "paused", "stopped
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 54
55. GMock (1/3)
• GMock is a mocking framework for Groovy
path/file.txt"))
File mo ckFile = mock(File, constructor("/a/
")
mockFile.getName().returns("file.txt
play {
")
def file = new File("/a/path/file.txt
()
assertEquals "file.txt", file.getName
}
• Mocking capabilities
– method calls – constructor calls
– property access – time matching
– static calls – order matching
– partial mocks – regex method matching
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 55
56. GMock (2/3)
• Mocking method calls
def loader = mock()
loader.put("fruit").returns("apple")
play {
fruit")
assertEquals "apple", loader.put("
}
• Mock static calls
def mockMath = mock(Math)
)
mockMath.static.random().returns(0.5
play {
assertEquals 0.5, Math.random()
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 56
57. GMock (3/3)
• Expecting exceptions
ception, "an exception")
loader.put ("throw exception").raises(RuntimeEx
• Time matching
– never, once, atLeastOnce, atMostOnce, stub, times,
atLeast, atMost
)
mockLo ader.load(2).returns(3).atLeastOnce(
play {
2)
assertEquals 3, mockLoader.load(
2)
assertEquals 3, mockLoader.load(
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 57
58. Gant
• Gant is a tool for scripting Ant tasks using Groovy
instead of XML to specify the logic
includeTargets << gant.targets.Clean
]
cleanPattern << ['**/*~', '**/*.bak'
cleanDirectory << 'build'
uff.') {
target(stuff: 'A target to do some st
println 'Stuff'
depends clean
Ant.'
echo message: 'A default message from
otherStuff()
}
her stuff') {
target (otherStuff: 'A target to do some ot
println 'OtherStuff'
Ant.'
echo message: 'Another message from
clean()
}
setDefaultTarget stuff
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 58
59. Gradle (1/2)
• From the website:
« Gradle is an enterprise-grade build system providing:
– A very flexible general purpose build tool like Ant
– Switchable, build-by-convention frameworks à la Maven,
for Java, Groovy and Scala projects
–Groovy build scripts
– Powerful support for multi-project builds
– Dependency management based on Ivy
– Full support for existing Maven or Ivy repository infra
– Support for transitive dependency management
– Ant tasks and builds as first class citizens. »
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 59
60. Gradle (2/2)
• For example, for a classical Java project
usePlugin ‘java’
repositories {
mavenCentral()
}
dependencies {
compile group: ‘commons-collection’,
n: ‘3.2’
module: ‘commons-collection’, versio
testCompile group: ‘junit’,
module: ‘junit’, version: ‘4.+’
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 60
61. Other build and quality tools
• You can use Ant, Gant, Maven (GMaven plugin) or
Gradle to build your projects
– fits nicely in an existing build and continuous
integration infrastructure
• A few Groovy-friendly tools provide handy metrics
– CodeNarc: provides various rules for static analysis of
your Groovy codebase (style, size, braces, naming...)
– Simian: detects duplication in your Groovy code base
– Cobertura, Clover: gives code coverage metrics
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 61
62. HTTPBuilder (1/3)
• HTTPBuilder provides a convenient builder API for
complex HTTP requests
)
def http = new HTTP Builder( 'http://ajax.googleapis.com'
http.request(GET, JSON) {
'
uri.path = '/ajax/services/search/web
Hobbes']
ur i.query = [v: '1.0', q: 'Calvin and
refox/3.0.4'
headers.'User- Agent' = 'Mozilla/5.0 Ubuntu/8.10 Fi
response.success = { resp, json ->
println resp.statusLine
json.responseData.results.each { Url}"
println " ${ it.titleNoFormatting} : ${it.visible
}
}
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 62
63. HTTPBuilder (2/3)
• Posting to a URL
import groovyx.net.http.HTTPBuilder
LENC
import static groovyx.net.http.ContentType.UR
tuses/' )
def htt p = new HTTPBuilder( 'http://twitter.com/sta
tpbuilder']
def postBody = [status: 'update!', source: 'ht
http.post( path: 'update.xml', body: postBody,
->
requestContentType: URLENC ) { resp
usLine}"
println "Tweet response status: ${resp.stat
assert resp.statusLine.statusCode == 200
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 63
64. HTTPBuilder (3/3)
• Posting XML content to a URL
http.request(POST, XML) {
body = {
auth {
user 'Bob'
password 'pass'
}
}
}
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 64
65. GroovyWS (1/2)
• Publishing and consuming WS-I
compliant SOAP web services
import groovyx.net.ws.WSClient
def proxy = new WSClient( asmx?WSDL",
"http://www.w3 schools.com/webservices/tempconvert.
this.class.classLoader)
proxy.initialize()
t(0)
def result = proxy.CelsiusToFahrenhei
grees Farhenheit"
println "You are probably freezing at ${result} de
• Can also deal with complex objects
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 65
66. GroovyWS (2/2)
• Publishing a service
– considering a service
class MathService { }
double add(do uble arg0, double arg1) { arg0 + arg1
g0 }
do uble square(double arg0) { arg0 * ar
}
– publishing the service
import groovyx.net.ws.WSServer
def server = new WSServer() /MathService")
server.setNode(" MathService", "http://localhost:6980
server.start()
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 66
67. nda
Ag e • Summary
•Q & A
Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 67