Session inaugurale du Groovy User Group Paris

73
GGUP Paris Groovy Grails User Group Session inaugurale 10 Juin 2010 Introduction à Groovy et son écosystème par Guillaume Laforge

Transcript of Session inaugurale du Groovy User Group Paris

Page 1: Session inaugurale du Groovy User Group Paris

GGUP ParisGroovy Grails User Group

Session inaugurale10 Juin 2010

Introduction à Groovy et son écosystème

par Guillaume Laforge

Page 2: Session inaugurale du Groovy User Group Paris

Luis AriasBalsamiq

Guillaume LaforgeSpringSource

VMWare

Stéphane Maldinidoc4web

Page 3: Session inaugurale du Groovy User Group Paris
Page 4: Session inaugurale du Groovy User Group Paris
Page 5: Session inaugurale du Groovy User Group Paris
Page 6: Session inaugurale du Groovy User Group Paris

Heeuu, mais qu’est-ce qu’on fait ici ?

Au choix !

Page 7: Session inaugurale du Groovy User Group Paris

des présentations...

Page 8: Session inaugurale du Groovy User Group Paris

des débats...

Page 9: Session inaugurale du Groovy User Group Paris

un bon restau...

Page 10: Session inaugurale du Groovy User Group Paris

coding dojos...

Page 11: Session inaugurale du Groovy User Group Paris

Let’s start!

Page 12: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Groovy intro and ecosystem

by Guillaume LaforgeGroovy Project Manager

Page 13: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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...

13

Page 14: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Contact information

• Email–[email protected]

• Twitter–@glaforge

• Blog–http://glaforge.free.fr/blog/groovy

• Groovy mailing-lists–http://old.nabble.com/codehaus---Groovy-f11866.html

14

Page 15: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

A little story

15

Page 16: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Agenda• Introduction to Groovy

–syntax basics–useful APIs

• Rich ecosystem

16

Page 17: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Agenda• Introduction to Groovy

17

Page 18: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

• 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

18

Groovy in a few words

Page 19: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

19

Page 20: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Mandatory Hello World

• Java style...

20

public class HelloWorld { private String name;

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) {

HelloWorld helloWorld = new HelloWorld();

helloWorld.setName("Groovy");

System.out.println(helloWorld.greet());

}}

Page 21: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Mandatory Hello World

• Groovy style...

21

public class HelloWorld { private String name;

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) {

HelloWorld helloWorld = new HelloWorld();

helloWorld.setName("Groovy");

System.out.println(helloWorld.greet());

}}

Page 22: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Mandatory Hello World

• Groovy style...

22

class HelloWorld { String name String greet() { "Hello $name" }

}

def helloWorld = new HelloWorld(name: "Groovy")

println helloWorld.greet()

Take 2!

Page 23: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

23

Page 24: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

On Java interoperability

• Groovy is the alternative JVM language providing the best integration with Java

• Mix and match Groovy and Java–even with a cyclic language dependency

• 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)24

JInterface

<<implements>>

GClass

JClass

GInterface

JClass

GClass

<<implements>>

Page 25: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Native syntax constructs

• Listsdef someNumbers = [1, 2, 3, 5, 7, 11]

• Rangesdef range = 1..18

• Mapsdef states = [CA: ‘California’, TX: ‘Texas’]

• Regular expressions~/fo*/‘foo’ =~ /fo*/‘foo’ ==~ /fo*/

25

Page 26: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

GStrings

• Sexiest feature of the language!

• Ability to embed variablesinside strings

26

def firstname = "Guillaume"def lastname = "${firstname} Laforge"

assert lastname == "Guillaume Laforge"

def date = "Today is: ${new Date()}"

def multiline = """Hello,How are you?"""

Page 27: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Closures

• A reusable / assignable code block–⚠ CS 101 for a proper definition

27

def helloPrinter = { println "hello" }

helloPrinter()

def twice = { it * 2 }assert twice(3) == 6assert 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 */ }

Page 28: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Time savers

• The «Groovy Truth»

• Safe graph navigation

• Elvis operator

28

def blank = ""; assert !blank

def empty = []; assert !empty

def order = nullassert order?.customer?.address == null

def name = customer.name ?: "Unknown"

Page 29: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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?

• Add your own extensions!

29

new File("apache.log").eachLine { println it }

(1..100).findAll { it % 2 == 1 }

speakers.groupBy { it.lastname }

"123".padLeft(5, '0')"ls -la".execute()"R3Jvb3Z5IHJvY2tzIQ==".decodeBase64()

Thread.start { /* code to execute */ }

Page 30: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

30

Page 31: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Markup builder

• Producing markup content

• Will yield

31

new MarkupBuilder().languages {

language(name: "Groovy") { feature(coolness: "low", "SQL")

feature(coolness: "high", "Template")

} language(name: "Perl")}

<languages> <language name = "Groovy"> <feature coolness="low">SQL</feature

>

<feature coolness="high">Template</feature>

</language> <language name: "Perl"/></languages>

Page 32: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

XML slurper

• Easily parsing and consumming XML content• Navigating through the nodes as an object graph

32

def xml = """\<languages> <language name="Groovy">

<feature coolness="low">SQL</feature>

<feature coolness="high">Template</feature>

</language> <language name="Perl"/></languages>"""

def root = new XmlSlurper().parseText(xml)

println root.language.feature[1].text()

root.language.feature.findAll{ it['@coolness'] == "low" }

.each{ println it.text() }

Page 33: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Swing builder

• Creating Swing UI with a programmatic descriptive Domain-Specific Language

33

import groovy.swing.SwingBuilder

import java.awt.BorderLayout as BL

def count = 0new SwingBuilder().edt { frame(title: 'Frame', size: [300,300], s

how: true) {

borderLayout() textlabel = label(text: "Click the b

utton!",

constraints: BL.NORTH)

button(text: 'Click Me',

actionPerformed: { count++ textlabel.text = "Clicked ${

count} time(s)."

println "clicked"},

constraints:BL.SOUTH)

}}

Page 34: Session inaugurale du Groovy User Group Paris
Page 35: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Template engine

• Templating capabilities, with embedded GStrings, and scriptlet notation

• A template servlet also exists

35

import groovy.text.SimpleTemplateEngine

def text = '''\Dear <%= firstname %>So nice to meet you in <% print city %>.

${signed}'''

def binding = [firstname: "Guillaume", city: "The Hague",

signed: "MrG"]

def engine = new SimpleTemplateEngine()

template = engine.createTemplate(text).make(binding)

Page 36: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

JDBC facilities

• Transparent resource handling thanks to closures

• A poorman’s dataset notion

36

def sql = Sql.newInstance(url, usr, pwd, driver)

sql.execute("insert into table values ($foo, $bar)")

sql.execute("insert into table values(?,?)", [a, b])

sql.eachRow("select * from USER") { print it.name }

def list = sql.rows("select * from USER")

def set = sql.dataSet("USER")set.add(name: "Johnny", age: 33)set.each { user -> println user.name }

set.findAll { it.age > 22 && it.age < 42 }

Page 37: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

JMX Builder

• Expose, configure JMX beans, export operations, create timers, event handling with closures, and more...

• You could easily monitor your Spring application’s exposed JMX beans through some Groovy script!

37

def jmx = new JmxBuilder()

def beans = jmx.export { bean(new CpuLoadMonitor())

bean(new DiskOccupationMonitor())

}

Page 38: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Ant builder

• Script and reuse any Ant task–FTP, SSH, Javac, file handling, etc.

• Used in Gant and Gradle

38

new AntBuilder().sequential {

def buildClasses = "build/classes"

// create classes directory

mkdir dir: buildClasses // compile sources javac srcdir: "src", destdir: buildClass

es

// jar everything jar destfile: "my.jar", basedir: buildCl

asses

}

Page 39: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

39

@Grab("net.sf.json-lib:json-lib:2.3:jdk15")

import net.sf.json.groovy.*

assert new JsonSlurper().parseText(

new JsonGroovyBuilder().json {

book(title: "Groovy in Action", author: "Guillaume")

}.toString()).book.title == "Groovy in Action"

Page 40: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

40

Page 41: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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>

41

<lang:groovy id="messenger"

refresh-check-delay="5000"

script-source="classpath:Messenger.groovy">

<lang:property name="message" value="Hi" />

</lang:groovy>

<bean id="bookingService" class="x.y.DefaultBookingService">

<property name="messenger" ref="messenger" />

</bean>

Page 42: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Spring integration (2/2)

• Grails provides a Spring bean builder–for programmatically define Spring configurations–more flexible than pure XML declarative descriptions

42

def bb = new grails.spring.BeanBuilder()

bb.beans { adder(AdderImpl) calcBean(CalcImpl)}

def ctx == bb.createApplicationContext()

def calc = ctx.getBean(‘calcBean’)

println calc.doAdd(3, 4)

Page 43: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Agenda• The Groovy Ecosystem

43

Page 44: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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)

44

Page 45: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

•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

45

Gaelyk

Page 46: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

GPars

• Actors, dataflow, concurrency, and more–for harnessing our

multicore platforms

• GPars web site:–http://gpars.codehaus.org

46

Page 47: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

47

Page 48: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Easyb (2/4)

• First, let’s write a story

48

given "an invalid zip code"

and "given the zipcodevalidator is initialized"

when "validate is invoked with the invalid zip code"

then "the validator instance should return false"

Page 49: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Easyb (3/4)

• Let’s write the test itself

• Afterwards, write the code that make the test pass

49

given "an invalid zip code", { invalidzipcode = "221o1"}

and "given the zipcodevalidator is initialized", {

zipvalidate = new ZipCodeValidator()

}

when "validate is invoked with the invalid zip code", {

value = zipvalidate.validate(invalidzipcode)

}

then "the validator instance should return false", {

value.shouldBe false}

Page 50: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Easyb (4/4)

• There’s also the specification format

50

before "initialize zipcodevalidator instance", {

zipvalidate = new ZipCodeValidator();

}

it "should deny invalid zip codes", {

["221o1", "2210", "22010-121o"].each { zip ->

zipvalidate.validate(zip).is false

}}

it "should accept valid zip codes", {

["22101", "22100", "22010-1210"].each { zip ->

zipvalidate.validate(zip).shouldBe true

}}

Page 51: Session inaugurale du Groovy User Group Paris

Spock testing framework

Page 52: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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. »

52

class HelloSpock extends spock.lang.Specification {

    def "can you figure out what I'm up to?"() {

        expect:        name.size() == size

        where:        name | size

"Kirk" | 4 "Spock" | 5 "Scotty" | 6    }}

Page 53: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

53

Condition not satisfied:

max(a, b) == c|   |  |  |  |3   1  3  |  2          false

Page 54: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Spock (3/3)

• Another example of the expressive language

54

    def "subscribers receive published events at least once"() {

      when: publisher.send(event)

      then: (1.._) * subscriber.receive(event)

      where: event << ["started", "paused", "stopped"]

    }

Page 55: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

GMock (1/3)

• GMock is a mocking framework for Groovy

• Mocking capabilities

55

File mockFile = mock(File, constructor("/a/path/file.txt"))

mockFile.getName().returns("file.txt")

play {  def file = new File("/a/path/file.txt")

  assertEquals "file.txt", file.getName()

}

–method calls–property access–static calls–partial mocks

–constructor calls–time matching–order matching–regex method matching

Page 56: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

GMock (2/3)

• Mocking method calls

• Mock static calls

56

def loader = mock()loader.put("fruit").returns("apple")

play {  assertEquals "apple", loader.put("fruit")

}

def mockMath = mock(Math)mockMath.static.random().returns(0.5)

play {   assertEquals 0.5, Math.random()

}

Page 57: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

GMock (3/3)

57

• Expecting exceptions

• Time matching–never, once, atLeastOnce, atMostOnce, stub, times,

atLeast, atMost

loader.put("throw exception").raises(RuntimeException, "an exception")

mockLoader.load(2).returns(3).atLeastOnce()

play {    assertEquals 3, mockLoader.load(2)

    assertEquals 3, mockLoader.load(2)

}

Page 58: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Gant

• Gant is a tool for scripting Ant tasks using Groovy instead of XML to specify the logic

58

includeTargets << gant.targets.Clean

cleanPattern << ['**/*~', '**/*.bak']

cleanDirectory << 'build'

target(stuff: 'A target to do some stuff.') {

println 'Stuff' depends clean echo message: 'A default message from A

nt.'

otherStuff()}

target(otherStuff: 'A target to do some other stuff') {

println 'OtherStuff'

echo message: 'Another message from Ant.'

clean()}

setDefaultTarget stuff

Page 59: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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. »

59

Page 60: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Gradle (2/2)

• For example, for a classical Java project

60

usePlugin ‘java’

repositories { mavenCentral()}

dependencies { compile group: ‘commons-collection’,

module: ‘commons-collection’, version: ‘3.2’

testCompile group: ‘junit’,

module: ‘junit’, version: ‘4.+’

}

Page 61: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

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

61

Page 62: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

HTTPBuilder (1/3)

• HTTPBuilder provides a convenient builder API for complex HTTP requests

62

def http = new HTTPBuilder( 'http://ajax.googleapis.com' )

http.request(GET, JSON) {

uri.path = '/ajax/services/search/web'

uri.query = [v: '1.0', q: 'Calvin and Hobbes']

headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'

response.success = { resp, json ->

println resp.statusLine

json.responseData.results.each {

println " ${it.titleNoFormatting} : ${it.visibleUrl}"

} }}

Page 63: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

HTTPBuilder (2/3)

• Posting to a URL

63

import groovyx.net.http.HTTPBuilderimport static groovyx.net.http.ContentType.URLENC def http = new HTTPBuilder( 'http://twitter.com/statuses/' )def postBody = [status: 'update!', source: 'httpbuilder']

http.post( path: 'update.xml', body: postBody,           requestContentType: URLENC ) { resp ->    println "Tweet response status: ${resp.statusLine}"   assert resp.statusLine.statusCode == 200}

Page 64: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

HTTPBuilder (3/3)

• Posting XML content to a URL

64

http.request(POST, XML) {   body = {     auth {       user 'Bob'       password 'pass'     }   }}

Page 65: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

GroovyWS (1/2)

• Publishing and consuming WS-I compliant SOAP web services

• Can also deal with complex objects

65

import groovyx.net.ws.WSClient

def proxy = new WSClient(

"http://www.w3schools.com/webservices/tempconvert.asmx?WSDL",

this.class.classLoader)

proxy.initialize()

def result = proxy.CelsiusToFahrenheit(0)

println "You are probably freezing at ${result} degrees Farhenheit"

Page 66: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

GroovyWS (2/2)

• Publishing a service–considering a service

–publishing the service

66

class MathService {

double add(double arg0, double arg1) { arg0 + arg1 }

double square(double arg0) { arg0 * arg0 }

}

import groovyx.net.ws.WSServer

def server = new WSServer()

server.setNode("MathService", "http://localhost:6980/MathService")

server.start()

Page 67: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Agenda• Summary

• Q & A

67

Page 68: Session inaugurale du Groovy User Group Paris

Make your life easier

Page 69: Session inaugurale du Groovy User Group Paris

Great fit for Domain-Specific

Languages

Page 70: Session inaugurale du Groovy User Group Paris

Rich and active ecosystem

Page 71: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Question & Answers

71

Page 72: Session inaugurale du Groovy User Group Paris

What’s next?

GrailsGriffonGradleSpockGParsEasyb

...

Page 73: Session inaugurale du Groovy User Group Paris

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Picture credits

• http://www.flickr.com/photos/featheredtar/2305070061/

• http://www.thedailygreen.com/cm/thedailygreen/images/WT/christmas-tree-with-gifts-flipbook.jpg

• http://www.flickr.com/photos/chicoer2001/188468490/

• http://www.flickr.com/photos/olibac/4054644737/

• http://www.flickr.com/photos/epsos/3384297473/

• http://media.techeblog.com/images/clapboard.jpg (clap)

• http://www.flickr.com/photos/diegocupolo/3614879332/ (flower power)

• http://www.flickr.com/photos/oskay/237442629/sizes/m/ (danger)

• http://www.partybox.co.uk/data/partyimages/250x250/6ftcutoutaustinpowers.jpg (austin powers)

• http://www.flickr.com/photos/27663074@N07/3413698337/ (jeepers creepers)

• http://www.flickr.com/photos/wheatfields/420088151/sizes/l/

• http://www.flickr.com/photos/therefromhere/518053737/sizes/l/

• http://www.flickr.com/photos/romainguy/230416692/sizes/l/

• http://www.flickr.com/photos/addictive_picasso/2874279971/sizes/l/

• http://www.flickr.com/photos/huangjiahui/3127634297/sizes/l/

• http://www.flickr.com/photos/25831000@N08/3064515804/sizes/o/

• http://www.flickr.com/photos/lanier67/3147696168/sizes/l/

• http://www.flickr.com/photos/ktb/4916063/sizes/o/

• http://www.flickr.com/photos/nathonline/918128338/sizes/l/

• http://www.flickr.com/photos/kevinsteele/39300193/sizes/l/

• http://commons.wikimedia.org/wiki/File:Brueghel-tower-of-babel.jpg

• http://commons.wikimedia.org/wiki/File:Platypus.jpg

• http://www.flickr.com/photos/joaomoura/2317171808/sizes/l/

• http://www.flickr.com/photos/wiccked/132687067/

• http://www.flickr.com/photos/timsamoff/252370986/sizes/l/

• http://www.flickr.com/photos/29738009@N08/2975466425/sizes/l/

• http://www.flickr.com/photos/howie_berlin/180121635/sizes/o/

• http://www.flickr.com/photos/yogi/1281980605/sizes/l/

• http://www.flickr.com/photos/dorseygraphics/1336468896/sizes/l/

• http://www.flickr.com/photos/xcbiker/386876546/sizes/l/

• http://www.flickr.com/photos/pietel/152403711/sizes/o/

• http://www.flickr.com/photos/forezt/192554677/sizes/o/

• http://keremkosaner.files.wordpress.com/2008/04/softwaredevelopment.gif

• http://www.jouy.inra.fr

• http://www.flickr.com/photos/ejpphoto/408101818/sizes/o/

• http://www.flickr.com/photos/solaro/2127576608/sizes/l/

• http://www.flickr.com/photos/biggreymare/2846899405/sizes/l/

• http://www.flickr.com/photos/wwworks/2222523978/ (earth)

• http://static-p3.fotolia.com/jpg/00/01/64/30/400_F_1643044_YrBQoPnt0SC5gHAueG0bhx20yCSL42.jpg (trafic light)

• http://aldaria02.a.l.pic.centerblog.net/lz2levrz.jpg (griffon)

• http://www.flickr.com/photos/geishaboy500/104137788/ (soap)

• Matriochka http://lang.russe.free.fr/images/matriochka.jpg

73