SlideShare una empresa de Scribd logo
1 de 73
GGUP Paris
Groovy Grails User Group

    Session inaugurale
      10 Juin 2010



 Introduction à Groovy
   et son écosystème
  par Guillaume Laforge
Luis Arias   Guillaume Laforge   Stéphane Maldini
 Balsamiq      SpringSource          doc4web
                  VMWare
Heeuu,
mais qu’est-ce
qu’on fait ici ?


  Au choix !
des présentations...
des débats...
un bon restau...
coding dojos...
Let’s start!
Groovy
                                                                 intro and ecosystem


                                                          by Guillaume Laforge
                                                        Groovy Project Manager




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

Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   13
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
A little story




Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   15
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
nda
               Ag e                                                                                             • Introduction to Groovy




Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.                 17
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
nda
               Ag e                                                                                             • The Groovy Ecosystem




Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.               43
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
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
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
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
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
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
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
Spock testing
 framework
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
nda
               Ag e                                                                                             • Summary

                                                                                                                •Q & A




Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.          67
Make your life easier
Great fit for
Domain-Specific
    Languages
Rich and active
ecosystem
Question & Answers




Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited.   71
What’s
next?
 Grails
 Griffon
 Gradle
 Spock
 GPars
 Easyb
   ...
Picture credits
   •     http://www.flickr.com/photos/featheredtar/2305070061/                                                •      http://www.flickr.com/photos/joaomoura/2317171808/sizes/l/

   •     http://www.thedailygreen.com/cm/thedailygreen/images/WT/                                             •      http://www.flickr.com/photos/wiccked/132687067/
         christmas-tree-with-gifts-flipbook.jpg                                                               •      http://www.flickr.com/photos/timsamoff/252370986/sizes/l/
   •     http://www.flickr.com/photos/chicoer2001/188468490/                                                  •      http://www.flickr.com/photos/29738009@N08/2975466425/sizes/l/

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

   •     http://www.flickr.com/photos/epsos/3384297473/                                                       •      http://www.flickr.com/photos/yogi/1281980605/sizes/l/
                                                                                                              •      http://www.flickr.com/photos/dorseygraphics/1336468896/sizes/l/
   •     http://media.techeblog.com/images/clapboard.jpg (clap)
                                                                                                              •      http://www.flickr.com/photos/xcbiker/386876546/sizes/l/
   •     http://www.flickr.com/photos/diegocupolo/3614879332/ (flower
         power)                                                                                               •      http://www.flickr.com/photos/pietel/152403711/sizes/o/

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

   •     http://www.partybox.co.uk/data/partyimages/                                                          •      http://keremkosaner.files.wordpress.com/2008/04/
                                                                                                                     softwaredevelopment.gif
         250x250/6ftcutoutaustinpowers.jpg (austin powers)
                                                                                                              •      http://www.jouy.inra.fr
   •     http://www.flickr.com/photos/27663074@N07/3413698337/
         (jeepers creepers)                                                                                   •      http://www.flickr.com/photos/ejpphoto/408101818/sizes/o/

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

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

   •     http://www.flickr.com/photos/romainguy/230416692/sizes/l/                                            •      http://www.flickr.com/photos/wwworks/2222523978/ (earth)

   •     http://www.flickr.com/photos/addictive_picasso/2874279971/sizes/l/                                   •      http://static-p3.fotolia.com/jpg/
                                                                                                                     00/01/64/30/400_F_1643044_YrBQoPnt0SC5gHAueG0bhx20yCSL42.jpg
   •     http://www.flickr.com/photos/huangjiahui/3127634297/sizes/l/                                                (trafic light)
   •     http://www.flickr.com/photos/25831000@N08/3064515804/sizes/o/                                        •      http://aldaria02.a.l.pic.centerblog.net/lz2levrz.jpg (griffon)
   •     http://www.flickr.com/photos/lanier67/3147696168/sizes/l/                                            •      http://www.flickr.com/photos/geishaboy500/104137788/ (soap)
   •     http://www.flickr.com/photos/ktb/4916063/sizes/o/                                                    •      Matriochka http://lang.russe.free.fr/images/matriochka.jpg

   •     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




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

Más contenido relacionado

Similar a Session inaugurale du Groovy User Group Paris

Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyAndres Almiray
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java DevelopersAndres Almiray
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle GroovyDeepak Bhagat
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaJohn Leach
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Jim Driscoll
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovymanishkp84
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークTsuyoshi Yamamoto
 
Groovy And Grails JUG Padova
Groovy And Grails JUG PadovaGroovy And Grails JUG Padova
Groovy And Grails JUG PadovaJohn Leach
 
Eclipsecon09 Introduction To Groovy
Eclipsecon09 Introduction To GroovyEclipsecon09 Introduction To Groovy
Eclipsecon09 Introduction To GroovyAndres Almiray
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemKostas Saidis
 
Groovy And Grails JUG Trento
Groovy And Grails JUG TrentoGroovy And Grails JUG Trento
Groovy And Grails JUG TrentoJohn Leach
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applicationsrohitnayak
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyAndres Almiray
 

Similar a Session inaugurale du Groovy User Group Paris (20)

Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG Sardegna
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovy
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
 
Groovy And Grails JUG Padova
Groovy And Grails JUG PadovaGroovy And Grails JUG Padova
Groovy And Grails JUG Padova
 
Eclipsecon09 Introduction To Groovy
Eclipsecon09 Introduction To GroovyEclipsecon09 Introduction To Groovy
Eclipsecon09 Introduction To Groovy
 
The Groovy Way
The Groovy WayThe Groovy Way
The Groovy Way
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
 
Groovy And Grails JUG Trento
Groovy And Grails JUG TrentoGroovy And Grails JUG Trento
Groovy And Grails JUG Trento
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applications
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
 

Más de Guillaume Laforge

Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Guillaume Laforge
 
Groovy workshop à Mix-IT 2013
Groovy workshop à Mix-IT 2013Groovy workshop à Mix-IT 2013
Groovy workshop à Mix-IT 2013Guillaume Laforge
 
Les nouveautés de Groovy 2 -- Mix-IT 2013
Les nouveautés de Groovy 2 -- Mix-IT 2013Les nouveautés de Groovy 2 -- Mix-IT 2013
Les nouveautés de Groovy 2 -- Mix-IT 2013Guillaume Laforge
 
Groovy 2.0 update at Devoxx 2012
Groovy 2.0 update at Devoxx 2012Groovy 2.0 update at Devoxx 2012
Groovy 2.0 update at Devoxx 2012Guillaume Laforge
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
 
Groovy update at SpringOne2GX 2012
Groovy update at SpringOne2GX 2012Groovy update at SpringOne2GX 2012
Groovy update at SpringOne2GX 2012Guillaume Laforge
 
Groovy 1.8 et 2.0 au BreizhC@mp 2012
Groovy 1.8 et 2.0 au BreizhC@mp 2012Groovy 1.8 et 2.0 au BreizhC@mp 2012
Groovy 1.8 et 2.0 au BreizhC@mp 2012Guillaume Laforge
 
Groovy 1.8 and 2.0 at GR8Conf Europe 2012
Groovy 1.8 and 2.0 at GR8Conf Europe 2012Groovy 1.8 and 2.0 at GR8Conf Europe 2012
Groovy 1.8 and 2.0 at GR8Conf Europe 2012Guillaume Laforge
 
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume Laforge
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume LaforgeGroovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume Laforge
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume LaforgeGuillaume Laforge
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGuillaume Laforge
 
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011Guillaume Laforge
 
GPars et PrettyTime - Paris JUG 2011 - Guillaume Laforge
GPars et PrettyTime - Paris JUG 2011 - Guillaume LaforgeGPars et PrettyTime - Paris JUG 2011 - Guillaume Laforge
GPars et PrettyTime - Paris JUG 2011 - Guillaume LaforgeGuillaume Laforge
 
Groovy Update - Guillaume Laforge - Greach 2011
Groovy Update - Guillaume Laforge - Greach 2011Groovy Update - Guillaume Laforge - Greach 2011
Groovy Update - Guillaume Laforge - Greach 2011Guillaume Laforge
 
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011Guillaume Laforge
 
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...Guillaume Laforge
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Guillaume Laforge
 

Más de Guillaume Laforge (20)

Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013
 
Groovy workshop à Mix-IT 2013
Groovy workshop à Mix-IT 2013Groovy workshop à Mix-IT 2013
Groovy workshop à Mix-IT 2013
 
Les nouveautés de Groovy 2 -- Mix-IT 2013
Les nouveautés de Groovy 2 -- Mix-IT 2013Les nouveautés de Groovy 2 -- Mix-IT 2013
Les nouveautés de Groovy 2 -- Mix-IT 2013
 
Groovy 2 and beyond
Groovy 2 and beyondGroovy 2 and beyond
Groovy 2 and beyond
 
Groovy 2.0 update at Devoxx 2012
Groovy 2.0 update at Devoxx 2012Groovy 2.0 update at Devoxx 2012
Groovy 2.0 update at Devoxx 2012
 
Groovy 2.0 webinar
Groovy 2.0 webinarGroovy 2.0 webinar
Groovy 2.0 webinar
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012
 
Groovy update at SpringOne2GX 2012
Groovy update at SpringOne2GX 2012Groovy update at SpringOne2GX 2012
Groovy update at SpringOne2GX 2012
 
JavaOne 2012 Groovy update
JavaOne 2012 Groovy updateJavaOne 2012 Groovy update
JavaOne 2012 Groovy update
 
Groovy 1.8 et 2.0 au BreizhC@mp 2012
Groovy 1.8 et 2.0 au BreizhC@mp 2012Groovy 1.8 et 2.0 au BreizhC@mp 2012
Groovy 1.8 et 2.0 au BreizhC@mp 2012
 
Groovy 1.8 and 2.0 at GR8Conf Europe 2012
Groovy 1.8 and 2.0 at GR8Conf Europe 2012Groovy 1.8 and 2.0 at GR8Conf Europe 2012
Groovy 1.8 and 2.0 at GR8Conf Europe 2012
 
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume Laforge
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume LaforgeGroovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume Laforge
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume Laforge
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific Languages
 
Whats new in Groovy 2.0?
Whats new in Groovy 2.0?Whats new in Groovy 2.0?
Whats new in Groovy 2.0?
 
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
 
GPars et PrettyTime - Paris JUG 2011 - Guillaume Laforge
GPars et PrettyTime - Paris JUG 2011 - Guillaume LaforgeGPars et PrettyTime - Paris JUG 2011 - Guillaume Laforge
GPars et PrettyTime - Paris JUG 2011 - Guillaume Laforge
 
Groovy Update - Guillaume Laforge - Greach 2011
Groovy Update - Guillaume Laforge - Greach 2011Groovy Update - Guillaume Laforge - Greach 2011
Groovy Update - Guillaume Laforge - Greach 2011
 
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
 
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
 

Último

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 

Último (20)

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 

Session inaugurale du Groovy User Group Paris

  • 1. GGUP Paris Groovy Grails User Group Session inaugurale 10 Juin 2010 Introduction à Groovy et son écosystème par Guillaume Laforge
  • 2. Luis Arias Guillaume Laforge Stéphane Maldini Balsamiq SpringSource doc4web VMWare
  • 3.
  • 4.
  • 5.
  • 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
  • 68. Make your life easier
  • 71. Question & Answers Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 71
  • 72. What’s next? Grails Griffon Gradle Spock GPars Easyb ...
  • 73. Picture credits • http://www.flickr.com/photos/featheredtar/2305070061/ • http://www.flickr.com/photos/joaomoura/2317171808/sizes/l/ • http://www.thedailygreen.com/cm/thedailygreen/images/WT/ • http://www.flickr.com/photos/wiccked/132687067/ christmas-tree-with-gifts-flipbook.jpg • http://www.flickr.com/photos/timsamoff/252370986/sizes/l/ • http://www.flickr.com/photos/chicoer2001/188468490/ • http://www.flickr.com/photos/29738009@N08/2975466425/sizes/l/ • http://www.flickr.com/photos/olibac/4054644737/ • http://www.flickr.com/photos/howie_berlin/180121635/sizes/o/ • http://www.flickr.com/photos/epsos/3384297473/ • http://www.flickr.com/photos/yogi/1281980605/sizes/l/ • http://www.flickr.com/photos/dorseygraphics/1336468896/sizes/l/ • http://media.techeblog.com/images/clapboard.jpg (clap) • http://www.flickr.com/photos/xcbiker/386876546/sizes/l/ • http://www.flickr.com/photos/diegocupolo/3614879332/ (flower power) • http://www.flickr.com/photos/pietel/152403711/sizes/o/ • http://www.flickr.com/photos/oskay/237442629/sizes/m/ (danger) • http://www.flickr.com/photos/forezt/192554677/sizes/o/ • http://www.partybox.co.uk/data/partyimages/ • http://keremkosaner.files.wordpress.com/2008/04/ softwaredevelopment.gif 250x250/6ftcutoutaustinpowers.jpg (austin powers) • http://www.jouy.inra.fr • http://www.flickr.com/photos/27663074@N07/3413698337/ (jeepers creepers) • http://www.flickr.com/photos/ejpphoto/408101818/sizes/o/ • http://www.flickr.com/photos/wheatfields/420088151/sizes/l/ • http://www.flickr.com/photos/solaro/2127576608/sizes/l/ • http://www.flickr.com/photos/therefromhere/518053737/sizes/l/ • http://www.flickr.com/photos/biggreymare/2846899405/sizes/l/ • http://www.flickr.com/photos/romainguy/230416692/sizes/l/ • http://www.flickr.com/photos/wwworks/2222523978/ (earth) • http://www.flickr.com/photos/addictive_picasso/2874279971/sizes/l/ • http://static-p3.fotolia.com/jpg/ 00/01/64/30/400_F_1643044_YrBQoPnt0SC5gHAueG0bhx20yCSL42.jpg • http://www.flickr.com/photos/huangjiahui/3127634297/sizes/l/ (trafic light) • http://www.flickr.com/photos/25831000@N08/3064515804/sizes/o/ • http://aldaria02.a.l.pic.centerblog.net/lz2levrz.jpg (griffon) • http://www.flickr.com/photos/lanier67/3147696168/sizes/l/ • http://www.flickr.com/photos/geishaboy500/104137788/ (soap) • http://www.flickr.com/photos/ktb/4916063/sizes/o/ • Matriochka http://lang.russe.free.fr/images/matriochka.jpg • 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 Copyright 2010 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 73

Notas del editor