SlideShare a Scribd company logo
Seven Groovy usage patterns
          for Java developers

                                 Dierk König
                          dierk.koenig@canoo.com




søndag den 17. maj 2009
Welcome!

                          Dierk König
                           Canoo fellow, www.canoo.com
                           Rich Internet Applications




                           Committer to Groovy and Grails
                           Author: Groovy in Action




søndag den 17. maj 2009
The 7 usage patterns

       •    Super Glue
       •    Liquid Heart
       •    Keyhole Surgery
       •    Smart Configuration
       •    Unlimited Openness
       •    House-Elf Scripts
       •    Prototype

                                  Examples in Groovy




søndag den 17. maj 2009
#1 Super Glue

       • Build application from existing building blocks

       • Java makes perfect infrastructure:
         middleware, frameworks, widget sets, services
       • Scripting makes a flexible (agile) applikation layer:
         views und controller
       • Grails, GSP, JBoss Seam, WebWork, Struts 2 Actions,...
       • Example: combination of XML parser, Java networking
         and Swing widget set in order to build a standard RSS
         feed reader




søndag den 17. maj 2009
Super Glue example: RSS Reader
          def url   ='http://www.groovyblogs.org/feed/rss'
          def items = new XmlParser().parse(url).channel.item
          def cols = 'pubDate title description'.tokenize()

          groovy.swing.SwingBuilder.build {
            frame(id:'f', title: 'Groovy Blogs', visible:true) {
             scrollPane {
               table {
                 tableModel(list: items) {
                    cols.each { col ->
                      closureColumn header: col, read: { it[col].text() }
            }}}}}
            f.pack()
          }



søndag den 17. maj 2009
#2 Liquid Heart

       • Externalize business models

       • Given application structure in Java
       • Allow to learn about the business:
         keep entities, relations, and behaviour flexible through
         scripting
       • Usages: Spring beans, JBoss components,rule engines
         (groovyrules.dev.java.net, JSR-94), Grails,
         enterprise risk management for world-leading insurances

       • Example: calculation rules for bonus allocation


søndag den 17. maj 2009
Liquid Heart example: bonus allocation
          revenue = employee.revenue
          switch(revenue / 1000) {
               case       0..100 : return revenue * 0.04
               case 100..200 : return revenue * 0.05
               case {it > 200} : bonusClub.add(employee)
                                   return revenue * 0.06
          }


          Binding binding = new Binding();
          binding.setVariable("employee", employee);
          binding.setVariable("bonusClub", bonusClub);
          GroovyShell shell = new GroovyShell(binding);
          File script       = new File(filename);
          float bonus       = (float) shell.evaluate(script);




søndag den 17. maj 2009
#3 Keyhole Surgery

       • Minimal-invasive surgery "in vivo"

       • Lots of need for runtime inspection
         and modifications
       • Ad-hoc queries are not foreseeable
       • "Backdoor" for the live execution of scripts
       • Particularly useful for
         product support, failure analysis, hot fixes, emergencies
       • Usages: Oracle JMX Beans, XWiki, SnipSnap, Ant, Canoo
         WebTest, Grails Console, GAE, ULC Admin Console
       • Example: a live Groovy Servlet



søndag den 17. maj 2009
Surgery through a Servlet keyhole

         Problems with the database connection?

          def ds = Config.dataSource
          ds.connection = new DebugConnection(ds.connection)




         Remove malicious users from the servlet context

          users = servletContext.getAttribute('users')
          bad = users.findAll { user -> user.cart.items.any { it.price < 0 } }
          servletContext.setAttribute('users', users - bad)




søndag den 17. maj 2009
#4 Smart Configuration

       • Enhance configuration with logic

       • Replace dumb XML configs
       • Use references, loops, conditionals, inheritance, execution
         logic, runtime environment adaption, ...
       • Typical scenario for domain specific languages (DSLs),
         Groovy Builder, Grails plugins, product customization,
         Groovy for OpenOffice:
         Community Innovation Program Silver Award Winner

       • Example: Navis SPARCS N4


søndag den 17. maj 2009
Smart Config example: container routing

          def ensureEvent = { change ->
               if (! event.getMostRecentEvent(change) {
                     event.postNewEvent(change)
               }
          }


          switch (event.REROUTE_CTR) {
                case 'OutboundCarrierId' :
                           ensureEvent('CHANGE_VSL')
                            break
                      case 'POD' :
                            if (! event.CHANGE_VSL) ensureEvent('CHANGE_POD')
                            break
          }




søndag den 17. maj 2009
#5 Unlimited Openness

       • Every line of code may be changed

       • It's impossible (and not desirable!)
         to design for every possible future
         requirement
       • Allow for easily changing the code
         without tedious setup for compilation
         and deployment
       • Follow the lessons of Perl, PHP, Python,...

       • Example: groovyblogs.org, PillarOne


søndag den 17. maj 2009
#6 House Elf

       • Delegate the housework

       • Build automation, continuous integration, deployment,
         installer, service monitoring, reports, statistics, automated
         documentation, functional tests, HTML scraping, Web
         remote control, XML-RPC, WebServices
       • Usages with Ant, Maven, AntBuilder, Gant, Gradle, Canoo
         WebTest, Grails scaffolding, ...

       • Examples: hooking scripts into Ant




søndag den 17. maj 2009
House Elf: musical Ant
          <groovy>
          import org.apache.tools.ant.*
          import org.jfugue.*
          project.addBuildListener(new PlayListener())
          class PlayListener implements BuildListener {
               def play = { new Player().play(new Pattern(it)) }
               void buildStarted(event)   {}
               void buildFinished(event) { }
               void messageLogged(event) { }
               void targetStarted(event) { play("D E") }
               void targetFinished(event) { play("C5maj") }
               void taskStarted(event)    {}
               void taskFinished(event)   {}
          }
          </groovy>



søndag den 17. maj 2009
House Elf: musical Ant
          <groovy>
          import org.apache.tools.ant.*
          import org.jfugue.*
          project.addBuildListener(new PlayListener())
          class PlayListener implements BuildListener {
               def play = { new Player().play(new Pattern(it)) }




               void targetStarted(event) { play("D E") }
               void targetFinished(event) { play("C5maj") }



          }
          </groovy>



søndag den 17. maj 2009
House Elf: musical Ant
          <groovy>
          import org.apache.tools.ant.*
          import org.jfugue.*



               def play = { new Player().play(new Pattern(it)) }




               void targetStarted(event) { play("D E") }
               void targetFinished(event) { play("C5maj") }


          project.addBuildListener(player as BuildListener)
          }
          </groovy>



søndag den 17. maj 2009
House Elf: musical Ant
          <groovy>
          import org.apache.tools.ant.*
          import org.jfugue.*



               def play = { new Player().play(new Pattern(it)) }



          def player = [
                          targetStarted:    { play("D E") },
                          targetFinished:   { play("C5maj") }
          ]
          project.addBuildListener(player as BuildListener)
          }
          </groovy>



søndag den 17. maj 2009
House Elf: musical Ant
          <groovy>
          import org.apache.tools.ant.*
          import org.jfugue.*


          def play        = { new Player().play(new Pattern(it)) }
          def player = [
                  targetStarted : { play "D E"     },
                  targetFinished : { play "C5maj" }
          ]
          project.addBuildListener(player as BuildListener)
          }
          </groovy>




søndag den 17. maj 2009
#7 Prototype

       • Feasibility study on the target platform

       • "Spikes" for technological or algorithmic ideas with more
         expressiveness, quicker feedback, and enhanced analysis
         capabilities
       • Later port to Java is optional
       • Usages: early user feedback about the domain model
         through a functional Grails prototype,
         algorithms for image manipulation

       • Example: prime number disassembly


søndag den 17. maj 2009
Prototype example: prime numbers
          boolean isPrime(x) { return ! (2..<x).any { y -> x % y == 0 } }


          int primeBelow(x) { (x..1).find { isPrime(it) } }


          List primeFactors(x) {
               if (isPrime(x)) return [x]
               int p = primeBelow(x)
               while (p > 1) {
                     if (x % p == 0) return [p, *primeFactors(x.intdiv(p))]
                     p = primeBelow(p-1)
               }
          }


          for (n in 100..110) { println "$n : "+primeFactors(n)}



søndag den 17. maj 2009
Prime numbers: counting modulo ops
          class ModCountCategory {
               static int count = 0
               static int mod(Integer self, Integer argument) {
                     count++
                     return self - argument * self.intdiv(argument)
          } }


          use (ModCountCategory) {
               for (n in 1000..1010) {
                     ModCountCategory.count = 0
                     factors = primeFactors(n)
                     println "$n : $factors".padRight(30) + "(in " +
                            "${ModCountCategory.count}".padLeft(5) + " steps)"
                     assert n == factors.inject(1){result, item -> result *= item }
          }      }



søndag den 17. maj 2009
Pattern Summary

       •    Super Glue
       •    Liquid Heart
       •    Keyhole Surgery
       •    Smart Configuration
       •    Unlimited Openness
       •    House-Elf Scripts
       •    Prototype



                                  Keep groovin' !



søndag den 17. maj 2009
More
        Information

       • Groovy in Action groovy.canoo.com/gina
         Manning, 2007, Foreword by James Gosling
         König mit Glover, Laforge, King, Skeet
       • groovy.codehaus.org, grails.org
         groovyblogs.org, searchgroovy.org




søndag den 17. maj 2009
Questions?

           More patterns in the pipeline:

           Lipstick
           - API enhancements
           Ghost
           - generating invisible code

           <your suggestion here>




søndag den 17. maj 2009

More Related Content

PDF
History & Practices for UniRx(EN)
PDF
How to Write Node.js Module
PPTX
Node.js/io.js Native C++ Addons
PPTX
node.js and native code extensions by example
PDF
Py conkr 20150829_docker-python
PDF
Writing native bindings to node.js in C++
PDF
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
PPTX
The State of JavaScript (2015)
History & Practices for UniRx(EN)
How to Write Node.js Module
Node.js/io.js Native C++ Addons
node.js and native code extensions by example
Py conkr 20150829_docker-python
Writing native bindings to node.js in C++
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
The State of JavaScript (2015)

What's hot (19)

PDF
Introdução ao Desenvolvimento Android com Kotlin
PDF
Global Interpreter Lock: Episode III - cat &lt; /dev/zero > GIL;
PDF
Node.js extensions in C++
KEY
New Design of OneRing
PDF
Rapid web development using tornado web and mongodb
PDF
Deep Dive async/await in Unity with UniTask(EN)
PDF
Aplicações assíncronas no Android com Coroutines & Jetpack
PDF
UniRx - Reactive Extensions for Unity(EN)
ZIP
Javascript Everywhere
PDF
閒聊Python應用在game server的開發
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
PDF
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
PDF
Proxies are Awesome!
KEY
Writing robust Node.js applications
PPTX
Sphinx autodoc - automated api documentation - PyCon.KR 2015
PDF
Job Queue in Golang
PDF
Implementing New Web
PDF
A deep dive into PEP-3156 and the new asyncio module
PDF
BDD - Buzzword Driven Development - Build the next cool app for fun and for.....
Introdução ao Desenvolvimento Android com Kotlin
Global Interpreter Lock: Episode III - cat &lt; /dev/zero > GIL;
Node.js extensions in C++
New Design of OneRing
Rapid web development using tornado web and mongodb
Deep Dive async/await in Unity with UniTask(EN)
Aplicações assíncronas no Android com Coroutines & Jetpack
UniRx - Reactive Extensions for Unity(EN)
Javascript Everywhere
閒聊Python應用在game server的開發
Matthew Eernisse, NodeJs, .toster {webdev}
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
Proxies are Awesome!
Writing robust Node.js applications
Sphinx autodoc - automated api documentation - PyCon.KR 2015
Job Queue in Golang
Implementing New Web
A deep dive into PEP-3156 and the new asyncio module
BDD - Buzzword Driven Development - Build the next cool app for fun and for.....
Ad

Viewers also liked (9)

PPTX
Social media and QR Code promo - Do not feel shy
PDF
Jiří Knesl - Techniky paralelního programování pro 21. století
PDF
Envecon One Stop IT Solution for Maritime and Asset Intensive Industry
DOC
Full Cost White Paper
PPTX
12 tips for successful implementation of erp in a manufacturing company
PPTX
ERP Goal Setting & TCO
PPTX
ERP Pre-Implementation TCO Total Cost of Ownership
PDF
Moving To New AVEVA Technology
PDF
Integrated Engineering Deployment in a New Engineering Office
Social media and QR Code promo - Do not feel shy
Jiří Knesl - Techniky paralelního programování pro 21. století
Envecon One Stop IT Solution for Maritime and Asset Intensive Industry
Full Cost White Paper
12 tips for successful implementation of erp in a manufacturing company
ERP Goal Setting & TCO
ERP Pre-Implementation TCO Total Cost of Ownership
Moving To New AVEVA Technology
Integrated Engineering Deployment in a New Engineering Office
Ad

Similar to GR8Conf 2009: Groovy Usage Patterns by Dierk König (20)

PDF
Groovy On Trading Desk (2010)
PDF
Oscon Java Testing on the Fast Lane
PDF
Automation with Ansible and Containers
PDF
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
PDF
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
PDF
Charla EHU Noviembre 2014 - Desarrollo Web
PDF
HTML5 for the Silverlight Guy
PDF
Cloud meets Fog & Puppet A Story of Version Controlled Infrastructure
PDF
Intro to PHP Testing
PPTX
ECMAScript 6 and the Node Driver
PPT
What's New in Groovy 1.6?
PDF
Atlassian Groovy Plugins
PDF
Construire une application JavaFX 8 avec gradle
PDF
Node azure
PPTX
Job DSL Plugin for Jenkins
ZIP
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
PPTX
Andriy Shalaenko - GO security tips
PPT
Groovy Introduction - JAX Germany - 2008
PDF
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
PDF
Bangpypers april-meetup-2012
Groovy On Trading Desk (2010)
Oscon Java Testing on the Fast Lane
Automation with Ansible and Containers
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
Charla EHU Noviembre 2014 - Desarrollo Web
HTML5 for the Silverlight Guy
Cloud meets Fog & Puppet A Story of Version Controlled Infrastructure
Intro to PHP Testing
ECMAScript 6 and the Node Driver
What's New in Groovy 1.6?
Atlassian Groovy Plugins
Construire une application JavaFX 8 avec gradle
Node azure
Job DSL Plugin for Jenkins
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Andriy Shalaenko - GO security tips
Groovy Introduction - JAX Germany - 2008
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Bangpypers april-meetup-2012

More from GR8Conf (20)

PDF
DevOps Enabling Your Team
PDF
Creating and testing REST contracts with Accurest Gradle
PDF
Mum, I want to be a Groovy full-stack developer
PDF
Metaprogramming with Groovy
PDF
Scraping with Geb
PDF
How to create a conference android app with Groovy and Android
PDF
Ratpack On the Docks
PDF
Groovy Powered Clean Code
PDF
Cut your Grails application to pieces - build feature plugins
PDF
Performance tuning Grails applications
PDF
Ratpack and Grails 3
PDF
Grails & DevOps: continuous integration and delivery in the cloud
PDF
Functional testing your Grails app with GEB
PDF
Deploying, Scaling, and Running Grails on AWS and VPC
PDF
The Grails introduction workshop
PDF
Idiomatic spock
PDF
The Groovy Ecosystem Revisited
PDF
Groovy 3 and the new Groovy Meta Object Protocol in examples
PDF
Integration using Apache Camel and Groovy
PDF
CRaSH the shell for the Java Virtual Machine
DevOps Enabling Your Team
Creating and testing REST contracts with Accurest Gradle
Mum, I want to be a Groovy full-stack developer
Metaprogramming with Groovy
Scraping with Geb
How to create a conference android app with Groovy and Android
Ratpack On the Docks
Groovy Powered Clean Code
Cut your Grails application to pieces - build feature plugins
Performance tuning Grails applications
Ratpack and Grails 3
Grails & DevOps: continuous integration and delivery in the cloud
Functional testing your Grails app with GEB
Deploying, Scaling, and Running Grails on AWS and VPC
The Grails introduction workshop
Idiomatic spock
The Groovy Ecosystem Revisited
Groovy 3 and the new Groovy Meta Object Protocol in examples
Integration using Apache Camel and Groovy
CRaSH the shell for the Java Virtual Machine

Recently uploaded (20)

PDF
TAIPANQQ SITUS MUDAH MENANG DAN MUDAH MAXWIN SEGERA DAFTAR DI TAIPANQQ DAN RA...
PDF
EVs U-5 ONE SHOT Notes_c49f9e68-5eac-4201-bf86-b314ef5930ba.pdf
PPTX
the Honda_ASIMO_Presentation_Updated.pptx
PPTX
genderandsexuality.pptxjjjjjjjjjjjjjjjjjjjj
PDF
Ct.pdffffffffffffffffffffffffffffffffffff
PPT
business model and some other things that
PDF
High-Quality PDF Backlinking for Better Rankings
PPTX
the-solar-system.pptxxxxxxxxxxxxxxxxxxxx
PPTX
asdmadsmammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm.pptx
PPTX
wegen seminar ppt.pptxhkjbkhkjjlhjhjhlhhvg
PPTX
BULAN K3 NASIONAL PowerPt Templates.pptx
PDF
WKA #29: "FALLING FOR CUPID" TRANSCRIPT.pdf
PPTX
Hacking Movie – Best Films on Cybercrime & Digital Intrigue
PPTX
What Makes an Entertainment App Addictive?
PPTX
E8 ssssssssssssssssssssssssssssssssssQ1 0101 PS.pptx
PPTX
History ATA Presentation.pptxhttps://www.slideshare.net/slideshow/role-of-the...
PPTX
The story of Nomuzi and the way she was living
PPTX
SPARSH-SVNITs-Annual-Cultural-Fest presentation for orientation
PDF
Commercial arboriculture Commercial Tree consultant Essex, Kent, Thaxted.pdf
PDF
oppenheimer and the story of the atomic bomb
TAIPANQQ SITUS MUDAH MENANG DAN MUDAH MAXWIN SEGERA DAFTAR DI TAIPANQQ DAN RA...
EVs U-5 ONE SHOT Notes_c49f9e68-5eac-4201-bf86-b314ef5930ba.pdf
the Honda_ASIMO_Presentation_Updated.pptx
genderandsexuality.pptxjjjjjjjjjjjjjjjjjjjj
Ct.pdffffffffffffffffffffffffffffffffffff
business model and some other things that
High-Quality PDF Backlinking for Better Rankings
the-solar-system.pptxxxxxxxxxxxxxxxxxxxx
asdmadsmammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm.pptx
wegen seminar ppt.pptxhkjbkhkjjlhjhjhlhhvg
BULAN K3 NASIONAL PowerPt Templates.pptx
WKA #29: "FALLING FOR CUPID" TRANSCRIPT.pdf
Hacking Movie – Best Films on Cybercrime & Digital Intrigue
What Makes an Entertainment App Addictive?
E8 ssssssssssssssssssssssssssssssssssQ1 0101 PS.pptx
History ATA Presentation.pptxhttps://www.slideshare.net/slideshow/role-of-the...
The story of Nomuzi and the way she was living
SPARSH-SVNITs-Annual-Cultural-Fest presentation for orientation
Commercial arboriculture Commercial Tree consultant Essex, Kent, Thaxted.pdf
oppenheimer and the story of the atomic bomb

GR8Conf 2009: Groovy Usage Patterns by Dierk König

  • 1. Seven Groovy usage patterns for Java developers Dierk König dierk.koenig@canoo.com søndag den 17. maj 2009
  • 2. Welcome! Dierk König Canoo fellow, www.canoo.com Rich Internet Applications Committer to Groovy and Grails Author: Groovy in Action søndag den 17. maj 2009
  • 3. The 7 usage patterns • Super Glue • Liquid Heart • Keyhole Surgery • Smart Configuration • Unlimited Openness • House-Elf Scripts • Prototype Examples in Groovy søndag den 17. maj 2009
  • 4. #1 Super Glue • Build application from existing building blocks • Java makes perfect infrastructure: middleware, frameworks, widget sets, services • Scripting makes a flexible (agile) applikation layer: views und controller • Grails, GSP, JBoss Seam, WebWork, Struts 2 Actions,... • Example: combination of XML parser, Java networking and Swing widget set in order to build a standard RSS feed reader søndag den 17. maj 2009
  • 5. Super Glue example: RSS Reader def url ='http://www.groovyblogs.org/feed/rss' def items = new XmlParser().parse(url).channel.item def cols = 'pubDate title description'.tokenize() groovy.swing.SwingBuilder.build { frame(id:'f', title: 'Groovy Blogs', visible:true) { scrollPane { table { tableModel(list: items) { cols.each { col -> closureColumn header: col, read: { it[col].text() } }}}}} f.pack() } søndag den 17. maj 2009
  • 6. #2 Liquid Heart • Externalize business models • Given application structure in Java • Allow to learn about the business: keep entities, relations, and behaviour flexible through scripting • Usages: Spring beans, JBoss components,rule engines (groovyrules.dev.java.net, JSR-94), Grails, enterprise risk management for world-leading insurances • Example: calculation rules for bonus allocation søndag den 17. maj 2009
  • 7. Liquid Heart example: bonus allocation revenue = employee.revenue switch(revenue / 1000) { case 0..100 : return revenue * 0.04 case 100..200 : return revenue * 0.05 case {it > 200} : bonusClub.add(employee) return revenue * 0.06 } Binding binding = new Binding(); binding.setVariable("employee", employee); binding.setVariable("bonusClub", bonusClub); GroovyShell shell = new GroovyShell(binding); File script = new File(filename); float bonus = (float) shell.evaluate(script); søndag den 17. maj 2009
  • 8. #3 Keyhole Surgery • Minimal-invasive surgery "in vivo" • Lots of need for runtime inspection and modifications • Ad-hoc queries are not foreseeable • "Backdoor" for the live execution of scripts • Particularly useful for product support, failure analysis, hot fixes, emergencies • Usages: Oracle JMX Beans, XWiki, SnipSnap, Ant, Canoo WebTest, Grails Console, GAE, ULC Admin Console • Example: a live Groovy Servlet søndag den 17. maj 2009
  • 9. Surgery through a Servlet keyhole Problems with the database connection? def ds = Config.dataSource ds.connection = new DebugConnection(ds.connection) Remove malicious users from the servlet context users = servletContext.getAttribute('users') bad = users.findAll { user -> user.cart.items.any { it.price < 0 } } servletContext.setAttribute('users', users - bad) søndag den 17. maj 2009
  • 10. #4 Smart Configuration • Enhance configuration with logic • Replace dumb XML configs • Use references, loops, conditionals, inheritance, execution logic, runtime environment adaption, ... • Typical scenario for domain specific languages (DSLs), Groovy Builder, Grails plugins, product customization, Groovy for OpenOffice: Community Innovation Program Silver Award Winner • Example: Navis SPARCS N4 søndag den 17. maj 2009
  • 11. Smart Config example: container routing def ensureEvent = { change -> if (! event.getMostRecentEvent(change) { event.postNewEvent(change) } } switch (event.REROUTE_CTR) { case 'OutboundCarrierId' : ensureEvent('CHANGE_VSL') break case 'POD' : if (! event.CHANGE_VSL) ensureEvent('CHANGE_POD') break } søndag den 17. maj 2009
  • 12. #5 Unlimited Openness • Every line of code may be changed • It's impossible (and not desirable!) to design for every possible future requirement • Allow for easily changing the code without tedious setup for compilation and deployment • Follow the lessons of Perl, PHP, Python,... • Example: groovyblogs.org, PillarOne søndag den 17. maj 2009
  • 13. #6 House Elf • Delegate the housework • Build automation, continuous integration, deployment, installer, service monitoring, reports, statistics, automated documentation, functional tests, HTML scraping, Web remote control, XML-RPC, WebServices • Usages with Ant, Maven, AntBuilder, Gant, Gradle, Canoo WebTest, Grails scaffolding, ... • Examples: hooking scripts into Ant søndag den 17. maj 2009
  • 14. House Elf: musical Ant <groovy> import org.apache.tools.ant.* import org.jfugue.* project.addBuildListener(new PlayListener()) class PlayListener implements BuildListener { def play = { new Player().play(new Pattern(it)) } void buildStarted(event) {} void buildFinished(event) { } void messageLogged(event) { } void targetStarted(event) { play("D E") } void targetFinished(event) { play("C5maj") } void taskStarted(event) {} void taskFinished(event) {} } </groovy> søndag den 17. maj 2009
  • 15. House Elf: musical Ant <groovy> import org.apache.tools.ant.* import org.jfugue.* project.addBuildListener(new PlayListener()) class PlayListener implements BuildListener { def play = { new Player().play(new Pattern(it)) } void targetStarted(event) { play("D E") } void targetFinished(event) { play("C5maj") } } </groovy> søndag den 17. maj 2009
  • 16. House Elf: musical Ant <groovy> import org.apache.tools.ant.* import org.jfugue.* def play = { new Player().play(new Pattern(it)) } void targetStarted(event) { play("D E") } void targetFinished(event) { play("C5maj") } project.addBuildListener(player as BuildListener) } </groovy> søndag den 17. maj 2009
  • 17. House Elf: musical Ant <groovy> import org.apache.tools.ant.* import org.jfugue.* def play = { new Player().play(new Pattern(it)) } def player = [ targetStarted: { play("D E") }, targetFinished: { play("C5maj") } ] project.addBuildListener(player as BuildListener) } </groovy> søndag den 17. maj 2009
  • 18. House Elf: musical Ant <groovy> import org.apache.tools.ant.* import org.jfugue.* def play = { new Player().play(new Pattern(it)) } def player = [ targetStarted : { play "D E" }, targetFinished : { play "C5maj" } ] project.addBuildListener(player as BuildListener) } </groovy> søndag den 17. maj 2009
  • 19. #7 Prototype • Feasibility study on the target platform • "Spikes" for technological or algorithmic ideas with more expressiveness, quicker feedback, and enhanced analysis capabilities • Later port to Java is optional • Usages: early user feedback about the domain model through a functional Grails prototype, algorithms for image manipulation • Example: prime number disassembly søndag den 17. maj 2009
  • 20. Prototype example: prime numbers boolean isPrime(x) { return ! (2..<x).any { y -> x % y == 0 } } int primeBelow(x) { (x..1).find { isPrime(it) } } List primeFactors(x) { if (isPrime(x)) return [x] int p = primeBelow(x) while (p > 1) { if (x % p == 0) return [p, *primeFactors(x.intdiv(p))] p = primeBelow(p-1) } } for (n in 100..110) { println "$n : "+primeFactors(n)} søndag den 17. maj 2009
  • 21. Prime numbers: counting modulo ops class ModCountCategory { static int count = 0 static int mod(Integer self, Integer argument) { count++ return self - argument * self.intdiv(argument) } } use (ModCountCategory) { for (n in 1000..1010) { ModCountCategory.count = 0 factors = primeFactors(n) println "$n : $factors".padRight(30) + "(in " + "${ModCountCategory.count}".padLeft(5) + " steps)" assert n == factors.inject(1){result, item -> result *= item } } } søndag den 17. maj 2009
  • 22. Pattern Summary • Super Glue • Liquid Heart • Keyhole Surgery • Smart Configuration • Unlimited Openness • House-Elf Scripts • Prototype Keep groovin' ! søndag den 17. maj 2009
  • 23. More Information • Groovy in Action groovy.canoo.com/gina Manning, 2007, Foreword by James Gosling König mit Glover, Laforge, King, Skeet • groovy.codehaus.org, grails.org groovyblogs.org, searchgroovy.org søndag den 17. maj 2009
  • 24. Questions? More patterns in the pipeline: Lipstick - API enhancements Ghost - generating invisible code <your suggestion here> søndag den 17. maj 2009