SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
The   Way


      by Dogaru Gabriel
Agenda
•   What is Groovy ?
•   Candies
•   Closures
•   Dynamic Groovy
•   Groovy builders
•   Integrating java and groovy
•   More Groovy Cool Stuff
#!/usr/bin/ruby
   class Person
   def initialize(lname, fname)
   @lname = lname
   @fname = fname
   end
  attr_reader :lname, :fname
  attr_writer :lname, :fname
  end
  steve = Person.new("Litt", "Stove")
  print "My name is ", steve.fname, " ", steve.lname,
  ".n"
  steve.fname = "Steve"
  print "My name is ", steve.fname, " ", steve.lname,
  ".n"
>
+++++++++[<+++++++>-]<++++.---------.>>
++++++++++[<+++++++++>-]<++.<++++.,
>>>++++++++++.>>+++++++++[<+++++++>
-]<+++.>>+++++++++++[<+++++++++>-]<--
.+++.>>++++++[<+++++>-]<++.>>++++++++
+++[<+++++++++>-]<.>>+++++++++++[<++
++++++++>-]<+.--..>>+++++++++++[<+++++
++++>-]<--.>>+++++++++++[<++++++++++>-]
<.>>+++++++++++[<+++++++++>-]<+.>>++++
++[<+++++>-]<++.>>+++++++++++[<+++++++
+++>-]<+.+++.>>++++++[<+++++>-]<++.>>++
+++++++++[<+++++++++>-]<+++.>>+++++++
++++++++[<+++++++>-]<.+++.-------.>>+++++
+[<+++++>-]<++.>>+++++++++++[<+++++++
+++>-]<.>>+++++++++++[<+++++++++>-]<--
.>>+++++++++++[<++++++++++>-]<-.>>++++
+++++++++++[<+++++++>-]<----.>>++++++++
++.


                                            6
What is Groovy ?
• “Groovy is what Java would look like had it been written
  in the 21st century.”
• an agile and dynamic language for the JVM
• inspired by languages like Python, Ruby and Smalltalk
• compiles straight to Java bytecode, integrates natively
  with java
• compiled or interpreted
• supports Domain-Specific Languages and other compact
  syntax
Other Cool Features
●
    expressive java-like syntax
●
    same oo and libs and java properties
●
    suports strong/weak typing
●
    operator overloading
●
    Gstrings
●
    Closures
●
    Almost 0 learning curve for java developers
J ava                                                            G roovy                                                          G roovy
import java.util.List;                                        import java.util.List;                                          class Speaker {
import java.util.ArrayList;                                   import java.util.ArrayList;                                        def age
                                                                                                                                 String name
public class Speaker {                                        public class Speaker {

                                                                  private Integer age;                                            String toString() {
    private Integer age;
    private String name;                                          private String name;                                              return "${name} - $age"
                                                                                                                                  }
    public String toString() {                                    public String toString() {                                  }
      return name + " - " + age;                                    return name + " - " + age;
    }                                                             }
                                                                                                                              def speakers = [
    public Integer getAge() {                                     public Integer getAge() {                                     new Speaker(name: "john", age: 15) ,
      return age;                                                   return age;                                                 new Speaker (name: "ionel", age: 29)
    }                                                             }                                                           ]

    public void setAge(Integer age) {                             public void setAge(Integer age) {
                                                                    this.age = age;                                           def upper = {it.toString().toUpperCase()}
      this.age = age;
    }                                                             }
                                                                                                                              speakers.findAll{s -> s.age >20}
    public String getName() {                                     public String getName() {                                       .collect(upper).each{println it}
      return name;                                                  return name;
    }                                                             }

    public void setName(String name) {                            public void setName(String name) {
      this.name = name;                                             this.name = name;
    }                                                             }

    public static void main(String[] args) {                      public static void main(String[] args) {
      List<Speaker> speakers = new                                  List<Speaker> speakers = new ArrayList<Speaker>();
        ArrayList<Speaker>();                                       Speaker ion = new Speaker();
      Speaker ion = new Speaker();                                  ion.setName("Ion");
      ion.setName("Ion");                                           ion.setAge(15);
      ion.setAge(15);                                               Speaker john = new Speaker();
      Speaker john = new Speaker();                                 john.setName("John");
      john.setName("John");                                         john.setAge(25);
      john.setAge(25);
                                                                      speakers.add(ion);
        speakers.add(ion);                                            speakers.add(john);
        speakers.add(john);
                                                                      for(Speaker s: speakers){
        for(Speaker s: speakers){                                       if (s.getAge()>20)
          if (s.getAge()>20)                                                System.out.println(s.toString().toUpperCase());
                                                                      }
            System.out.println(s.toString().toUpperCase());       }
        }                                                     }
    }
}
Productivity graph




                     AfterThought planning results
“Good Programmers Are Lazy and Dumb”
                                                           Philipp Lenssen




                        http://blogoscoped.com/archive/2005-08-24-n14.html
Candies 1
 • Automatic Imports
   import   java.lang.*;
   import   java.util.*;
   import   java.net.*;
   import   java.io.*;
   import   java.math.BigInteger;
   import   java.math.BigDecimal;
   import   groovy.lang.*;
   import   groovy.util.*;

• Everything is an object
   3.times{print 'la'}     --->lalala
   3.minus(2) == 3-2
   "lol".equals("lol")
Candies 2
•Optional Semicolons
     msg ="Hello"
     msg +=" World" ;   msg    += "!";
     println msg;
     ===>
     "Hello World!"

     def pizza = new Pizza()
     def deliver = pizza.&deliver()
     deliver



• Optional Parentheses
     println("Hello World!")
     println"Hello World!"
     ===>
     "Hello World!"
Candies 3
• Optional Datatype Declaration (Duck Typing)
  w ="Hello"
  String x ="Hello"
  println w.class
    ===> java.lang.String
  println w.class == x.class
  ===> true




• Optional Exception Handling
  s?.doSomething()
Candies 4
• Optional Return Statements
  String     getFullName(){
           return "${firstName}   ${lastName}"
  }
  //equivalent code
  String getFullName(){
       "${firstName} ${lastName}"
  }


  add(x,y){ x + y}
Operator Overloading
  a+b                       a.plus(b)
  a-b                       a.minus(b)
  a*b                       a.multiply(b)
  a ** b                    a.power(b)
  a/b                       a.div(b)
  a %b                      a.mod(b)
  a|b                       a.or(b)
  a&b                       a.and(b)
  a^b                       a.xor(b)
  a++ or ++a                a.next()
  a-- or --a                a.previous()
  a[b]                      a.getAt(b)
  a[b] = c                  a.putAt(b, c)
  a << b                    a.leftS hift(b)
  a >> b                    a.rightS hift(b)
  switch(a) { case(b) : }   b.isCase(a)
  ~a                        a.bitwiseNegate()
  -a                        a.negative()
  +a                        a.positive()
  a == b                    a.equals(b) or a.compareTo(b) == 0 **
  a != b                    ! a.equals(b)
  a <=> b                   a.compareTo(b)
  a>b                       a.compareTo(b) > 0
  a >= b                    a.compareTo(b) >= 0
  a<b                       a.compareTo(b) < 0
  a <= b                    a.compareTo(b) <= 0
GStrings
'Hello World'
“Hello $world”
/Hello $world/




if (text =~ pattern)println "match"
if (text ==~ pattern) println "match"
matcher ='Groovy is groovy'=~ /(G|g)roovy/
print "Size of matcher is ${matcher.size()} "
println "with elements ${matcher[0]} and ${matcher[1]}."
Closures
•   A Groovy closure is like a "code block" or a method pointer. It is a
    piece of code that is defined and then executed at a later point.
    def clos={param -> println "Hello ${param}"}
    clos.call(1)
    clos('1')
    1.upto(10) {p -> println p}
    1.upto 10,clos

    [1, 2, 3, 4].each {println it}
    def isEven={x -> return (x % 2==0)}
    def isOdd={x -> return ! isEven(x)}
    def filter(list, predicate) {
    return list.findAll(predicate)
    }
    def odds=filter(table, isOdd)
    println “odds: ${odds}”
Lists
def   languages     =   ["Java","Groovy","JRuby"]
languages   <<"Jython"
languages.each{lang        ->println    lang}
languages.each{lang        ->println    lang}
def   others   =    ["Jython","JavaScript"]
languages   +=     others
languages.findAll{      it.startsWith("G")      }
println   languages*.toUpperCase()
languages.pop()


def   scores   =    [80,    90,   70]
println   scores.max()
Maps

def family = [dad:"John", mom:"Jane"]
family.get("dad") == family.dad
family.put("kid","Timmy") == family.kid2 ="Susie"
family.containsValue("John")
def kids = [kid:"Timmy", kid2:"Susie"]
family += kids
Ranges
(1..3).each{println "lla "}
for(i in 1..3){ println
    "Attempt ${i}"
}
def twentiethCentury=1900..<2000    // Range literal
def reversedTen=10..1               // Reversed Range
twentiethCentury.size()             // 100
twentiethCentury.get(0)             // 1900
twentiethCentury.getFrom()          // 1900
twentiethCentury.getTo()            // 1999
twentiethCentury.contains(2000)     // false
twentiethCentury.subList(0, 5)      // 1900..1904
reversedTen[2]                      // 8
reversedTen.isReverse()             // true
Files
new File(".").eachFile{file ->println file}
new File(".").eachFileMatch(~/.*.jsp/){file ->println file}
new File("x.txt").eachLine{line->println line}
file.splitEachLine(" "){words ->println words.size() ; wordCount += words.size() }


File file = new File("hello.txt")
file.write("Hello Worldn")


File src = new File("src.jpg")
new File("dest.jpg").withOutputStream{ out ->
out.write src.readBytes()
}
"cp ${src.name}${dest.name}".execute()
new File("src.txt").delete()
Dynamic Groovy
• “A domain-specific language, unlike a general-purpose
  language, is designed to be useful for a specific task in a
  fixed problem domain .”(MSDN)
Why Groovy
• The compiler doesn’t know much about behavior
• Behaviour completely dynamic at runtime
• Everything’s routed through the Meta Object
  Protocol
   – Method calls, property access, operators…
   – That’s why Groovy is a “dynamic language”
What Groovy offers
• invokeMethod and getProperty
    def invokeMethod(String name, args)
    def getProperty(String name)
    void setProperty(String name, value)
• methodMissing & propertyMissing
    class GORM {
        def methodMissing(String name, args) {
      ….}
    }

• ExpandoMetaClass
    def gstr = "hello $test"
    def emc = new ExpandoMetaClass( gstr.class, false )
    emc.test = { println "test" }
    emc.initialize()
    gstr.metaClass = emc
    gstr.test()
What Groovy offers 2
class Pouncer {
    static pounces(Integer self) {
        (0..<self).inject("") {s, n ->
            s += "boing! "
        }
    }
}
use(Pouncer) {
    assert 3.pounces() == "boing! boing! boing! "
}
1+1= 2!!!! Really ???

String.metaClass.plus={d->
    if (delegate=="maria" && d == "ion") return "ghita"
    delegate.concat d
}

println "maria"+"ion"
println "Tom"+"&"+"Jerry"
1+1= ?
 4.meters + 4.kilo.meters
class Distance {
    static METER = 'meter'
    def dist, type
    Distance(a, b) {dist = a; type = b}
    String toString() {"$dist $type"}
    def plus(b) {
        if (b.type == type) {
            return new Distance(dist + b.dist, type)
        }}}
Integer.metaClass.getMeters = {->
    new Distance(delegate, Distance.METER)
}
Integer.metaClass.getKilo = {->
    delegate * 1000
}
println 4.kilo
println 4.meters
println 4.meters + 4.kilo.meters
Testing and Mocks
def service = [retrieveRate:{ new ExchangeRate(1.45, 0.57) }] as
   ExchangeRateService
def sterlingConverter = new SterlingCurrencyConverter(service)

service = { new ExchangeRate(1.55, 0.56) } as ExchangeRateService
sterlingConverter = new SterlingCurrencyConverter(service)


mockContext1 = new MockFor(ExchangeRateService)
mockContext1.demand.retrieveRate { new ExchangeRate(1.75, 0.54) }
def dummyService1 = mockContext1.proxyInstance()
Reading XML
• XmlParser/ XmlSlurper

import groovy.util.*
def parser = new XmlParser()
def doc = parser.parse(‘library.xml’)
println “${doc.book[0].title[0].text()}”

doc.book.title.each { title ->
    println “${title.text()}”
}
Reading XML 2
person = new                       person    =  new XmlSlurper()
   XmlParser().parse(file)                             .parse(file)
println   person.attribute("id")   println    person.@id
                                   println    person["@id"]
println   person["@id"]
                                   println    person
println   person.text()
XML builders
•MarkupBuilder
import groovy.xml.MarkupBuilder
def mB = new MarkupBuilder()
mB.book(format:'pdf') {
  author('Ken Barcla')
  title('Groovy')
  publisher('Elsevier')
}


<book format='pdf'>
  <author>Ken Barcla</author>
  <title>Groovy</title>
  <publisher>Elsevier</publisher>
</book>
XML builders 2
def builder = new groovy.xml.StreamingMarkupBuilder()
def person = {
     person(id:99){
          firstname("John")
          lastname("Smith")
     }
}
println builder.bind(person)



<person id='99'><firstname>John</firstname><lastname>Smith</lastname></person>
SwingBuilder
import groovy.swing.SwingBuilder
def swing = new SwingBuilder()
def frame = swing.frame(title:'Printer') {
    panel {
        textField(id:'message', columns:10)
        button(text:'Print', actionPerformed: {
             println swing.message.text         })
    }
}
frame.pack()
frame.show()
AntBuilder
import groovy.util.*
def aB = new AntBuilder()
aB.echo(message : ‘Start’)
def demoDir = ‘demo’
aB.mkdir(dir : demoDir)
aB.copy(todir : demoDir) {
   aB.fileSet(dir : ‘.’) {
   aB.include(name : ‘*.groovy’)
  }
}
aB.echo(message : ‘End’)
Groovy sql
import groovy.sql.*
def DB = 'jdbc: derby: accountDB'
def DRIVER = 'org.apache.derby.jdbc.EmbeddedDriver'
sql = Sql.newInstance(DB, "user","passwd", DRIVER)
def displayAccounts(banner, sql) {
    sql.eachRow(' select * from accounts') {acc ->
        println "Account: $ {acc.number} $ {acc.balance}"
    }}
sql.query('SELECT firstname, lastname FROM Athlete') {resultSet ->
    if (resultSet.next()) {
        print resultSet.getString(1)
        print ' '
        println resultSet.getString('lastname')
    }}
sql.execute "DELETE FROM Athlete WHERE firstname = $firstname;"
def stmt = "UPDATE $tablename SET $field = ? $whereId"
sql.executeUpdate stmt, [newValue, id]

dataSet = sql.dataSet('weather')
citiesBelowFreezing = dataSet.findAll { it.temperature         <     32   }
println"Cities below freezing:"
citiesBelowFreezing.each {println it.city}
Integrating java and groovy

• Groovy Shell
• GroovyScriptEngine
• GroovyClassLoader
Groovy Shell
GroovyShell shell = new GroovyShell();
        Object result = shell.evaluate("12 + 23");
        System.out.println(result);


def binding = new Binding()
binding.mass = 22.3
binding.velocity = 10.6
def shell = new GroovyShell(binding)
def expression = "mass * velocity ** 2 / 2”
assert shell.evaluate(expression) == 1426.972


def shell = new GroovyShell()
def clazz = shell.evaluate('''
     class MyClass {
         def method() { "value" }
     }
     return MyClass
''')
GroovyScriptEngine


def engine = new GroovyScriptEngine(".")
def value = engine.run("test/MyScript.groovy", new Binding())
GroovyClassLoader

gcl = new GroovyClassLoader()
Class greetingClass = gcl.parseClass(new File("Hello.groovy"))
Spring Integration
...
<bean id="country1" class="spring.Australia">
    <property name="capital" value="Canberra"/>
    <property name="population" value="20264082"/>
</bean>
...


...
<lang:groovy id="country3"
    script-source="classpath:spring/NewZealand.groovy">
         <lang:property name="capital" value="Wellington" />
         <lang:property name="population" value="4076140" />
</lang:groovy>
...
Spring Integration 2

...
<lang:groovy id="sorter">
<lang:inline-script><![CDATA[
package spring
class CountrySorter implements Sorter {
  String order List sort(Country[] items) {
  List result = items.toList().sort{ p1, p2 ->
     p1.population <=> p2.population }
  if (order == "reverse") return result.reverse()
  else return result } } ]]>
</lang:inline-script>
<lang:property name="order" value="forward" />
</lang:groovy> ...
More Groovy Cool Stuff
•   Gant
•   Scriptom
•   GMaven
•   GraphicsBuilder
•   JideBuilder
•   GSQL
•   Griffon
•   Grails
http://groovy.codehaus.org/
Questions
The Groovy Way

Mais conteúdo relacionado

Mais procurados

GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorFedor Lavrentyev
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Template Haskell とか
Template Haskell とかTemplate Haskell とか
Template Haskell とかHiromi Ishii
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Leonardo Borges
 
The Macronomicon
The MacronomiconThe Macronomicon
The MacronomiconMike Fogus
 
Coffee Scriptでenchant.js
Coffee Scriptでenchant.jsCoffee Scriptでenchant.js
Coffee Scriptでenchant.jsNaoyuki Totani
 
Kotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin
Kotlin Programming Language. What it is all about. Roman Belov, PMM in KotlinKotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin
Kotlin Programming Language. What it is all about. Roman Belov, PMM in KotlinJetBrains Russia
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collectionsMyeongin Woo
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? DataWorks Summit
 
Query History of a Software Project
Query History of a Software ProjectQuery History of a Software Project
Query History of a Software Projectstevensreinout
 
Empathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeEmpathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeMario Gleichmann
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Paulo Morgado
 

Mais procurados (20)

GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Template Haskell とか
Template Haskell とかTemplate Haskell とか
Template Haskell とか
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
Coffee Scriptでenchant.js
Coffee Scriptでenchant.jsCoffee Scriptでenchant.js
Coffee Scriptでenchant.js
 
Kotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin
Kotlin Programming Language. What it is all about. Roman Belov, PMM in KotlinKotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin
Kotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Hands on lua
Hands on luaHands on lua
Hands on lua
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch?
 
Query History of a Software Project
Query History of a Software ProjectQuery History of a Software Project
Query History of a Software Project
 
Empathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeEmpathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible code
 
Kotlin standard
Kotlin standardKotlin standard
Kotlin standard
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 

Semelhante a The Groovy Way

Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークTsuyoshi Yamamoto
 
About java
About javaAbout java
About javaJay Xu
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Madrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyMadrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyIván López Martín
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
BEKK Teknologiradar - Kotlin
BEKK Teknologiradar - KotlinBEKK Teknologiradar - Kotlin
BEKK Teknologiradar - KotlinVegard Veiset
 
Derping With Kotlin
Derping With KotlinDerping With Kotlin
Derping With KotlinRoss Tuck
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfakshpatil4
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Chang W. Doh
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?Chang W. Doh
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 

Semelhante a The Groovy Way (20)

Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
 
About java
About javaAbout java
About java
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
EMFPath
EMFPathEMFPath
EMFPath
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Madrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyMadrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovy
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
BEKK Teknologiradar - Kotlin
BEKK Teknologiradar - KotlinBEKK Teknologiradar - Kotlin
BEKK Teknologiradar - Kotlin
 
Derping With Kotlin
Derping With KotlinDerping With Kotlin
Derping With Kotlin
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdf
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

The Groovy Way

  • 1. The Way by Dogaru Gabriel
  • 2.
  • 3.
  • 4. Agenda • What is Groovy ? • Candies • Closures • Dynamic Groovy • Groovy builders • Integrating java and groovy • More Groovy Cool Stuff
  • 5. #!/usr/bin/ruby class Person def initialize(lname, fname) @lname = lname @fname = fname end attr_reader :lname, :fname attr_writer :lname, :fname end steve = Person.new("Litt", "Stove") print "My name is ", steve.fname, " ", steve.lname, ".n" steve.fname = "Steve" print "My name is ", steve.fname, " ", steve.lname, ".n"
  • 7. What is Groovy ? • “Groovy is what Java would look like had it been written in the 21st century.” • an agile and dynamic language for the JVM • inspired by languages like Python, Ruby and Smalltalk • compiles straight to Java bytecode, integrates natively with java • compiled or interpreted • supports Domain-Specific Languages and other compact syntax
  • 8. Other Cool Features ● expressive java-like syntax ● same oo and libs and java properties ● suports strong/weak typing ● operator overloading ● Gstrings ● Closures ● Almost 0 learning curve for java developers
  • 9. J ava G roovy G roovy import java.util.List; import java.util.List; class Speaker { import java.util.ArrayList; import java.util.ArrayList; def age String name public class Speaker { public class Speaker { private Integer age; String toString() { private Integer age; private String name; private String name; return "${name} - $age" } public String toString() { public String toString() { } return name + " - " + age; return name + " - " + age; } } def speakers = [ public Integer getAge() { public Integer getAge() { new Speaker(name: "john", age: 15) , return age; return age; new Speaker (name: "ionel", age: 29) } } ] public void setAge(Integer age) { public void setAge(Integer age) { this.age = age; def upper = {it.toString().toUpperCase()} this.age = age; } } speakers.findAll{s -> s.age >20} public String getName() { public String getName() { .collect(upper).each{println it} return name; return name; } } public void setName(String name) { public void setName(String name) { this.name = name; this.name = name; } } public static void main(String[] args) { public static void main(String[] args) { List<Speaker> speakers = new List<Speaker> speakers = new ArrayList<Speaker>(); ArrayList<Speaker>(); Speaker ion = new Speaker(); Speaker ion = new Speaker(); ion.setName("Ion"); ion.setName("Ion"); ion.setAge(15); ion.setAge(15); Speaker john = new Speaker(); Speaker john = new Speaker(); john.setName("John"); john.setName("John"); john.setAge(25); john.setAge(25); speakers.add(ion); speakers.add(ion); speakers.add(john); speakers.add(john); for(Speaker s: speakers){ for(Speaker s: speakers){ if (s.getAge()>20) if (s.getAge()>20) System.out.println(s.toString().toUpperCase()); } System.out.println(s.toString().toUpperCase()); } } } } }
  • 10. Productivity graph AfterThought planning results
  • 11. “Good Programmers Are Lazy and Dumb” Philipp Lenssen http://blogoscoped.com/archive/2005-08-24-n14.html
  • 12. Candies 1 • Automatic Imports import java.lang.*; import java.util.*; import java.net.*; import java.io.*; import java.math.BigInteger; import java.math.BigDecimal; import groovy.lang.*; import groovy.util.*; • Everything is an object 3.times{print 'la'} --->lalala 3.minus(2) == 3-2 "lol".equals("lol")
  • 13. Candies 2 •Optional Semicolons msg ="Hello" msg +=" World" ; msg += "!"; println msg; ===> "Hello World!" def pizza = new Pizza() def deliver = pizza.&deliver() deliver • Optional Parentheses println("Hello World!") println"Hello World!" ===> "Hello World!"
  • 14. Candies 3 • Optional Datatype Declaration (Duck Typing) w ="Hello" String x ="Hello" println w.class ===> java.lang.String println w.class == x.class ===> true • Optional Exception Handling s?.doSomething()
  • 15. Candies 4 • Optional Return Statements String getFullName(){ return "${firstName} ${lastName}" } //equivalent code String getFullName(){ "${firstName} ${lastName}" } add(x,y){ x + y}
  • 16. Operator Overloading a+b a.plus(b) a-b a.minus(b) a*b a.multiply(b) a ** b a.power(b) a/b a.div(b) a %b a.mod(b) a|b a.or(b) a&b a.and(b) a^b a.xor(b) a++ or ++a a.next() a-- or --a a.previous() a[b] a.getAt(b) a[b] = c a.putAt(b, c) a << b a.leftS hift(b) a >> b a.rightS hift(b) switch(a) { case(b) : } b.isCase(a) ~a a.bitwiseNegate() -a a.negative() +a a.positive() a == b a.equals(b) or a.compareTo(b) == 0 ** a != b ! a.equals(b) a <=> b a.compareTo(b) a>b a.compareTo(b) > 0 a >= b a.compareTo(b) >= 0 a<b a.compareTo(b) < 0 a <= b a.compareTo(b) <= 0
  • 17. GStrings 'Hello World' “Hello $world” /Hello $world/ if (text =~ pattern)println "match" if (text ==~ pattern) println "match" matcher ='Groovy is groovy'=~ /(G|g)roovy/ print "Size of matcher is ${matcher.size()} " println "with elements ${matcher[0]} and ${matcher[1]}."
  • 18. Closures • A Groovy closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. def clos={param -> println "Hello ${param}"} clos.call(1) clos('1') 1.upto(10) {p -> println p} 1.upto 10,clos [1, 2, 3, 4].each {println it} def isEven={x -> return (x % 2==0)} def isOdd={x -> return ! isEven(x)} def filter(list, predicate) { return list.findAll(predicate) } def odds=filter(table, isOdd) println “odds: ${odds}”
  • 19. Lists def languages = ["Java","Groovy","JRuby"] languages <<"Jython" languages.each{lang ->println lang} languages.each{lang ->println lang} def others = ["Jython","JavaScript"] languages += others languages.findAll{ it.startsWith("G") } println languages*.toUpperCase() languages.pop() def scores = [80, 90, 70] println scores.max()
  • 20. Maps def family = [dad:"John", mom:"Jane"] family.get("dad") == family.dad family.put("kid","Timmy") == family.kid2 ="Susie" family.containsValue("John") def kids = [kid:"Timmy", kid2:"Susie"] family += kids
  • 21. Ranges (1..3).each{println "lla "} for(i in 1..3){ println "Attempt ${i}" } def twentiethCentury=1900..<2000 // Range literal def reversedTen=10..1 // Reversed Range twentiethCentury.size() // 100 twentiethCentury.get(0) // 1900 twentiethCentury.getFrom() // 1900 twentiethCentury.getTo() // 1999 twentiethCentury.contains(2000) // false twentiethCentury.subList(0, 5) // 1900..1904 reversedTen[2] // 8 reversedTen.isReverse() // true
  • 22. Files new File(".").eachFile{file ->println file} new File(".").eachFileMatch(~/.*.jsp/){file ->println file} new File("x.txt").eachLine{line->println line} file.splitEachLine(" "){words ->println words.size() ; wordCount += words.size() } File file = new File("hello.txt") file.write("Hello Worldn") File src = new File("src.jpg") new File("dest.jpg").withOutputStream{ out -> out.write src.readBytes() } "cp ${src.name}${dest.name}".execute() new File("src.txt").delete()
  • 23. Dynamic Groovy • “A domain-specific language, unlike a general-purpose language, is designed to be useful for a specific task in a fixed problem domain .”(MSDN)
  • 24. Why Groovy • The compiler doesn’t know much about behavior • Behaviour completely dynamic at runtime • Everything’s routed through the Meta Object Protocol – Method calls, property access, operators… – That’s why Groovy is a “dynamic language”
  • 25. What Groovy offers • invokeMethod and getProperty def invokeMethod(String name, args) def getProperty(String name) void setProperty(String name, value) • methodMissing & propertyMissing class GORM { def methodMissing(String name, args) { ….} } • ExpandoMetaClass def gstr = "hello $test" def emc = new ExpandoMetaClass( gstr.class, false ) emc.test = { println "test" } emc.initialize() gstr.metaClass = emc gstr.test()
  • 26. What Groovy offers 2 class Pouncer { static pounces(Integer self) { (0..<self).inject("") {s, n -> s += "boing! " } } } use(Pouncer) { assert 3.pounces() == "boing! boing! boing! " }
  • 27. 1+1= 2!!!! Really ??? String.metaClass.plus={d-> if (delegate=="maria" && d == "ion") return "ghita" delegate.concat d } println "maria"+"ion" println "Tom"+"&"+"Jerry"
  • 28. 1+1= ? 4.meters + 4.kilo.meters class Distance { static METER = 'meter' def dist, type Distance(a, b) {dist = a; type = b} String toString() {"$dist $type"} def plus(b) { if (b.type == type) { return new Distance(dist + b.dist, type) }}} Integer.metaClass.getMeters = {-> new Distance(delegate, Distance.METER) } Integer.metaClass.getKilo = {-> delegate * 1000 } println 4.kilo println 4.meters println 4.meters + 4.kilo.meters
  • 29. Testing and Mocks def service = [retrieveRate:{ new ExchangeRate(1.45, 0.57) }] as ExchangeRateService def sterlingConverter = new SterlingCurrencyConverter(service) service = { new ExchangeRate(1.55, 0.56) } as ExchangeRateService sterlingConverter = new SterlingCurrencyConverter(service) mockContext1 = new MockFor(ExchangeRateService) mockContext1.demand.retrieveRate { new ExchangeRate(1.75, 0.54) } def dummyService1 = mockContext1.proxyInstance()
  • 30. Reading XML • XmlParser/ XmlSlurper import groovy.util.* def parser = new XmlParser() def doc = parser.parse(‘library.xml’) println “${doc.book[0].title[0].text()}” doc.book.title.each { title -> println “${title.text()}” }
  • 31. Reading XML 2 person = new person = new XmlSlurper() XmlParser().parse(file) .parse(file) println person.attribute("id") println person.@id println person["@id"] println person["@id"] println person println person.text()
  • 32. XML builders •MarkupBuilder import groovy.xml.MarkupBuilder def mB = new MarkupBuilder() mB.book(format:'pdf') { author('Ken Barcla') title('Groovy') publisher('Elsevier') } <book format='pdf'> <author>Ken Barcla</author> <title>Groovy</title> <publisher>Elsevier</publisher> </book>
  • 33. XML builders 2 def builder = new groovy.xml.StreamingMarkupBuilder() def person = { person(id:99){ firstname("John") lastname("Smith") } } println builder.bind(person) <person id='99'><firstname>John</firstname><lastname>Smith</lastname></person>
  • 34. SwingBuilder import groovy.swing.SwingBuilder def swing = new SwingBuilder() def frame = swing.frame(title:'Printer') { panel { textField(id:'message', columns:10) button(text:'Print', actionPerformed: { println swing.message.text }) } } frame.pack() frame.show()
  • 35. AntBuilder import groovy.util.* def aB = new AntBuilder() aB.echo(message : ‘Start’) def demoDir = ‘demo’ aB.mkdir(dir : demoDir) aB.copy(todir : demoDir) { aB.fileSet(dir : ‘.’) { aB.include(name : ‘*.groovy’) } } aB.echo(message : ‘End’)
  • 36. Groovy sql import groovy.sql.* def DB = 'jdbc: derby: accountDB' def DRIVER = 'org.apache.derby.jdbc.EmbeddedDriver' sql = Sql.newInstance(DB, "user","passwd", DRIVER) def displayAccounts(banner, sql) { sql.eachRow(' select * from accounts') {acc -> println "Account: $ {acc.number} $ {acc.balance}" }} sql.query('SELECT firstname, lastname FROM Athlete') {resultSet -> if (resultSet.next()) { print resultSet.getString(1) print ' ' println resultSet.getString('lastname') }} sql.execute "DELETE FROM Athlete WHERE firstname = $firstname;" def stmt = "UPDATE $tablename SET $field = ? $whereId" sql.executeUpdate stmt, [newValue, id] dataSet = sql.dataSet('weather') citiesBelowFreezing = dataSet.findAll { it.temperature < 32 } println"Cities below freezing:" citiesBelowFreezing.each {println it.city}
  • 37. Integrating java and groovy • Groovy Shell • GroovyScriptEngine • GroovyClassLoader
  • 38. Groovy Shell GroovyShell shell = new GroovyShell(); Object result = shell.evaluate("12 + 23"); System.out.println(result); def binding = new Binding() binding.mass = 22.3 binding.velocity = 10.6 def shell = new GroovyShell(binding) def expression = "mass * velocity ** 2 / 2” assert shell.evaluate(expression) == 1426.972 def shell = new GroovyShell() def clazz = shell.evaluate(''' class MyClass { def method() { "value" } } return MyClass ''')
  • 39. GroovyScriptEngine def engine = new GroovyScriptEngine(".") def value = engine.run("test/MyScript.groovy", new Binding())
  • 40. GroovyClassLoader gcl = new GroovyClassLoader() Class greetingClass = gcl.parseClass(new File("Hello.groovy"))
  • 41. Spring Integration ... <bean id="country1" class="spring.Australia"> <property name="capital" value="Canberra"/> <property name="population" value="20264082"/> </bean> ... ... <lang:groovy id="country3" script-source="classpath:spring/NewZealand.groovy"> <lang:property name="capital" value="Wellington" /> <lang:property name="population" value="4076140" /> </lang:groovy> ...
  • 42. Spring Integration 2 ... <lang:groovy id="sorter"> <lang:inline-script><![CDATA[ package spring class CountrySorter implements Sorter { String order List sort(Country[] items) { List result = items.toList().sort{ p1, p2 -> p1.population <=> p2.population } if (order == "reverse") return result.reverse() else return result } } ]]> </lang:inline-script> <lang:property name="order" value="forward" /> </lang:groovy> ...
  • 43. More Groovy Cool Stuff • Gant • Scriptom • GMaven • GraphicsBuilder • JideBuilder • GSQL • Griffon • Grails