SlideShare a Scribd company logo
Practical Groovy
                         for Java Developers
Gabriel Dogaru
gabi@gabrieldogaru.com

March 10 2012
Agenda

 Groovy introduction

 Closures

 First Script

 Testing with Groovy

 Building with groovy
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

Compiled or interpreted
Supports Domain-Specific Languages and other
 compact syntax
A programming language is for thinking
about programs, not for expressing
programs you've already thought of. It
should be a pencil, not a pen.

                             Paul Graham
I think I know java!
//... Person.java                           //... Person.groovy
                                            //... Person.groovy
public class Person {                       public class Person {
    private String name;                    class Person { name;
                                                private String
    private int age;                            String name
                                                private int age;
                                                int age
    public Person() {                           public Person() {
                                            }
    }                                           }
    public Person(String name, int age) {       public Person(String name, int age) {
       this.name = name;                    //... Person.groovyname;
                                                   this.name =
       this.age = age;                      class Person { age;
                                                   this.age =
    }                                           }
                                                def name
    public String getName() {                   def ageString getName() {
                                                public
       return name;                         }      return name;
    }                                           }
    public void setName(String name) {      person = new Person(name: "Ion", age: 66)
                                                public void setName(String name) {
       this.name = name;                           this.name = name;
    }                                       //person.setAge(61)
                                                }
                                            person.age = 61
    public int getAge() {                       public int getAge() {
       return age;                                 return age;
                                            //System.out.println(person.getName())
    }                                           }
                                            println person.name
    public void setAge(int age) {               public void setAge(int age) {
       this.age = age;                      //> Ionthis.age = age;
    }                                           }
}                                           }
Gotchas
 Automatic Imports
 Everything is an object
 Optional data type declaration (Duck
 Typing)
 Optional exception handling
 Optional semicolons and parentheses
 Optional return statements
 Operator overloading
Groovy Closures

 Like a "code block" or a method pointer

 May be passed as arguments

 May accept arguments

 May return values

 Makes anonymous inner classes obsolete
Closures
//... ClosureExample.java
//... ClosureExample.java                               //... ClosureExample.groovy
import com.google.common.base.Predicate;
import java.util.ArrayList;                             import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.Arrays;                                import com.google.common.collect.Iterables;
import java.util.ArrayList;                             import java.util.ArrayList;
                                                        def numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
import java.util.List;
import java.util.Arrays;                                import java.util.Arrays;
                                                        def oddNumbers = numbers.findAll {it % 2!=0}
import java.util.List;                                  import java.util.List;
public class ClosureExample {                           oddNumbers.each {println it}
 public static void main(String[] args) {
public class ClosureExample {                           public class ClosureExample {
  List<Integer> numbers = Arrays.asList(
public static void main(String[] args) {                public static void main(String[] args) {
 List<Integer> numbers = 2, 3, 4, 5, 6, 7, 8, 9);
                       1, Arrays.asList(                 List<Integer> numbers = Arrays.asList(
                          1, 2, 3, 4, 5, 6, 7, 8, 9);                       1, 2, 3, 4, 5, 6, 7, 8, 9);
      List<> oddNumbers = new ArrayList<..>();
    Iterable<> number : numbers) {
      for (int oddNumbers=Iterables.filter(numbers,       Iterable<> oddNumbers=Iterables.filter(numbers,
       new Predicate<Integer>() {
        if (number % 2 != 0) {                                new Predicate<Integer>() {
                                                        def odd = {Integer n->
         public boolean apply(Integer number) {
          oddNumbers.add(number);                               public boolean apply(Integer number) {
                                                          return return number % 2 != 0;
                                                                  n%2 != 0
        } return number % 2 != 0;
      } }                                               }       }
        });                                                 });
         for (int number : oddNumbers) {                def numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
         for (int number : oddNumbers) {                   for (int number : oddNumbers) {
               System.out.println(number);
            System.out.println(number);                 def oddNumbers = numbers.findAll odd
                                                              System.out.println(number);
        }}                                              oddNumbers.each {println it}
                                                          }
    }
    }                                                       }
}
}                                                       }
Cooo...ol
How do I start ?
Write your first script
//… WriteSomeXML .java
@GrabResolver(name = 'maven-central', root = 'repo1.maven.org')
import java.io.File;
@Grapes(
import java.io.FileOutputStream;
import javax.xml.parsers.*;
    @Grab(group = 'xerces', module = 'xercesImpl', version = '2.10.0')
)//… write xml
import org.w3c.dom.*;
import org.apache.xml.serialize.*;
public class WriteSomeXML {
 new File("persons.xml").withWriter {writer ->
import javax.xml.parsers.* {
   public static void main(String[] args)
   def xml = new MarkupBuilder(writer)
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
import org.apache.xml.serialize.*
     xml.persons db = null;
     DocumentBuilder {
dbf Document doc = null;
      = DocumentBuilderFactory.newInstance()
db = {person(id: 99) {
     trydbf.newDocumentBuilder()
        db = dbf.newDocumentBuilder();
doc = firstname("John")
           db.newDocument()
        doc = db.newDocument();                                  <?xml version="1.0" encoding="UTF-8"?>
root = lastname("Smith")
           doc.createElement"persons“
        Element root = doc.createElement("persons");
                                                                 <persons>
doc.appendChild root
  }}} doc.appendChild(root);
        Element el = doc.createElement("person");                  <person id="99">
el = doc.createElement"person“
        root.appendChild(el);
root.appendChild "99");                                               <firstname>John</firstname>
        el.setAttribute("id", el
el.setAttribute "id", doc.createElement("firstname");
        Element firstname = "99“
                                                                      <lastname>Smith</lastname>
//… read xml
        el.appendChild(firstname);
firstname = doc.createElement("firstname")                         </person>
        firstname.appendChild(doc.createTextNode("John"));       </persons>
el.appendChild firstname
def parser lastname =XmlParser()
        Element = new doc.createElement("lastname");
firstname.appendChild doc.createTextNode("John")
        el.appendChild(lastname);
def persons = parser.parse("persons.xml")
        lastname.appendChild(doc.createTextNode("Smith"));
lastname = doc.createElement "lastname“
println "${persons.person[0].@id}"
        OutputFormat out = new OutputFormat(doc);
el.appendChild lastnamelastname.appendChild
        out.setIndenting(true);
persons.person.eachnew XMLSerializer(new FileOutputStream(new File("persons.xml")), out);
doc.createTextNode="Smith" ->
        XMLSerializer xmlSer     { person
out println person.firstname[0].text()
      =xmlSer.serialize(doc);
          new OutputFormat doc
     } catch (Exception e) {
out.indenting = true
}       e.printStackTrace();
xmlSer = new XMLSerializer(new FileOutputStream(new File("persons.xml")),
     }                                                                                      out)
xmlSer.serialize doc
   }
}
Write your tests with groovy
 <dependency>
     <groupId>org.codehaus.groovy</groupId>
     <artifactId>groovy</artifactId>
     <scope>test</scope>
 </dependency>
....
 <build>
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
               <compilerId>groovy-eclipse-compiler</compilerId>
            </configuration>
            <dependencies>
               <dependency>
                 <groupId>org.codehaus.groovy</groupId>
                 <artifactId>groovy-eclipse-compiler</artifactId>
               </dependency>
            </dependencies>
         </plugin>
....
Classes under test
  //… ExchangeRateDAO.java

  public interface ExchangeRateDAO {
    BigDecimal load(String currency);
    void save(String currency, BigDecimal value);
  }


  //… ExchangeRateService.java

  public class ExchangeRateService {
    private final ExchangeRateDAO rateDAO;
    public ExchangeRateService(ExchangeRateDAO rateDAO) {
       this.rateDAO = rateDAO;
    }
    public BigDecimal getRate(String currency) {
       return rateDAO.load(currency);
    }
    public void updateRate(String currency, BigDecimal value) {
       rateDAO.save(currency, value);
    }
  }
Mocking – map coercion
//… DynamicTest.groovy
class DynamicTest {

    @Test
    public void test1() {
      ExchangeRateDAO rateDAO = {1.0} as ExchangeRateDAO
      ExchangeRateService service = new ExchangeRateService(rateDAO)
      assertEquals 1.0, service.getRate("USD")
    }

    @Test(expected = IllegalAccessError.class)
    public void test_named_methods() {
      ExchangeRateDAO rateDAO = [
             load: {String v -> 1.0},
             save: {String k, BigDecimal v -> throw new IllegalAccessError()}
         ] as ExchangeRateDAO

        ExchangeRateService service = new ExchangeRateService(rateDAO)
        assertEquals 1.0, service.getRate("USD")
        service.updateRate("1", 2)
    }
}
Mocking - MockFor

 //… MockForTest.groovy
 class MockForTest {
    @Test
    public void test() {
      def mockContext1 = new MockFor(ExchangeRateDAO)
      mockContext1.demand.load("USD") { 1.0 }

         def dummyDAO = mockContext1.proxyDelegateInstance()

         def service = new ExchangeRateService(dummyDAO)
         assertEquals 1.0, service.getRate("USD")
         mockContext1.verify dummyDAO
     }
 }
Build with groovy
<?xml version="1.0" encoding="UTF-8"?>
<project name=“Ant Example" default="main" basedir=".">
   <property environment="env"/>
   <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy">
       <classpath>
          <fileset dir="${env.GROOVY_HOME}" includes="embeddable/groovy-all-
*.jar,lib/ivy*.jar"/>
       </classpath>
   </taskdef>

  <target name=“print-xml">
     <groovy>
       xmlfiles = new File('.').listFiles().findAll{ it =~ '.xml$' }
       xmlfiles.sort().each{ println it.toString() }
     </groovy>
  </target>

</project>
Build with Ant

def ant = new AntBuilder()
ant.echo(file:'Temp.java',
     ''' class Temp { public static void main(String[] args) {System.out.println("Hello"); }}
''')
ant.javac(srcdir:'.', includes:'Temp.java', fork:'true')
ant.java(classpath:'.', classname:'Temp', fork:'true')
ant.echo('Done')


// =>
// [javac] Compiling 1 source file
// [java] Hello
//[echo] Done
's

please fill out the evaluations

More Related Content

What's hot

About java
About javaAbout java
About javaJay Xu
 
Predictably
PredictablyPredictably
Predictablyztellman
 
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
Fedor Lavrentyev
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
Mike Fogus
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
Jano Suchal
 
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
Johannes Schildgen
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
thnetos
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
용 최
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
groovy databases
groovy databasesgroovy databases
groovy databases
Paul King
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
Norman Richards
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Scott Leberknight
 
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
Fabio Collini
 
Google guava
Google guavaGoogle guava
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
Saeid Zebardast
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
Jordi Gerona
 

What's hot (20)

About java
About javaAbout java
About java
 
Predictably
PredictablyPredictably
Predictably
 
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
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
java sockets
 java sockets java sockets
java sockets
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
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
 
Google guava
Google guavaGoogle guava
Google guava
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 

Viewers also liked

The case for continuous delivery
The case for continuous deliveryThe case for continuous delivery
The case for continuous deliveryCodecamp Romania
 
Business analysis techniques exercise your 6-pack
Business analysis techniques   exercise your 6-packBusiness analysis techniques   exercise your 6-pack
Business analysis techniques exercise your 6-packCodecamp Romania
 
Andrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseAndrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseCodecamp Romania
 
Code camp 12 oct 2013 Sponsors
Code camp 12 oct 2013 SponsorsCode camp 12 oct 2013 Sponsors
Code camp 12 oct 2013 Sponsors
Codecamp Romania
 
Iasi code camp 12 october 2013 marius ursache - sketching & prototyping
Iasi code camp 12 october 2013  marius ursache - sketching & prototypingIasi code camp 12 october 2013  marius ursache - sketching & prototyping
Iasi code camp 12 october 2013 marius ursache - sketching & prototypingCodecamp Romania
 
Code camp iasi silviu niculita - machine learning for mere mortals with azu...
Code camp iasi   silviu niculita - machine learning for mere mortals with azu...Code camp iasi   silviu niculita - machine learning for mere mortals with azu...
Code camp iasi silviu niculita - machine learning for mere mortals with azu...
Codecamp Romania
 
Kickstart your own freelancing career
Kickstart your own freelancing careerKickstart your own freelancing career
Kickstart your own freelancing careerCodecamp Romania
 
Iasi code camp 12 october 2013 looking outside the scrum - richard stinear
Iasi code camp 12 october 2013   looking outside the scrum - richard stinearIasi code camp 12 october 2013   looking outside the scrum - richard stinear
Iasi code camp 12 october 2013 looking outside the scrum - richard stinearCodecamp Romania
 
Codecamp iasi-26 nov 2011-the value of bpm in real world applications
Codecamp iasi-26 nov 2011-the value of bpm in real world applicationsCodecamp iasi-26 nov 2011-the value of bpm in real world applications
Codecamp iasi-26 nov 2011-the value of bpm in real world applicationsCodecamp Romania
 
lettera Commissione Ue
lettera Commissione Uelettera Commissione Ue
lettera Commissione Ue
ilfattoquotidiano.it
 

Viewers also liked (10)

The case for continuous delivery
The case for continuous deliveryThe case for continuous delivery
The case for continuous delivery
 
Business analysis techniques exercise your 6-pack
Business analysis techniques   exercise your 6-packBusiness analysis techniques   exercise your 6-pack
Business analysis techniques exercise your 6-pack
 
Andrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseAndrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabase
 
Code camp 12 oct 2013 Sponsors
Code camp 12 oct 2013 SponsorsCode camp 12 oct 2013 Sponsors
Code camp 12 oct 2013 Sponsors
 
Iasi code camp 12 october 2013 marius ursache - sketching & prototyping
Iasi code camp 12 october 2013  marius ursache - sketching & prototypingIasi code camp 12 october 2013  marius ursache - sketching & prototyping
Iasi code camp 12 october 2013 marius ursache - sketching & prototyping
 
Code camp iasi silviu niculita - machine learning for mere mortals with azu...
Code camp iasi   silviu niculita - machine learning for mere mortals with azu...Code camp iasi   silviu niculita - machine learning for mere mortals with azu...
Code camp iasi silviu niculita - machine learning for mere mortals with azu...
 
Kickstart your own freelancing career
Kickstart your own freelancing careerKickstart your own freelancing career
Kickstart your own freelancing career
 
Iasi code camp 12 october 2013 looking outside the scrum - richard stinear
Iasi code camp 12 october 2013   looking outside the scrum - richard stinearIasi code camp 12 october 2013   looking outside the scrum - richard stinear
Iasi code camp 12 october 2013 looking outside the scrum - richard stinear
 
Codecamp iasi-26 nov 2011-the value of bpm in real world applications
Codecamp iasi-26 nov 2011-the value of bpm in real world applicationsCodecamp iasi-26 nov 2011-the value of bpm in real world applications
Codecamp iasi-26 nov 2011-the value of bpm in real world applications
 
lettera Commissione Ue
lettera Commissione Uelettera Commissione Ue
lettera Commissione Ue
 

Similar to CodeCamp Iasi 10 march 2012 - Practical Groovy

AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
Getting value from IoT, Integration and Data Analytics
 
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
akshpatil4
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
HamletDRC
 
The Groovy Way
The Groovy WayThe Groovy Way
The Groovy Way
Gabriel Dogaru
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdf
arjuncp10
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6
Moaid Hathot
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Codemotion
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
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
Iván López Martín
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
Md Sazzad Islam
 
C# Is The Future
C# Is The FutureC# Is The Future
C# Is The Future
Filip Ekberg
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
Paul King
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
Cody Engel
 
Introduzione a C#
Introduzione a C#Introduzione a C#
Introduzione a C#
Lorenz Cuno Klopfenstein
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
jagriti srivastava
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 

Similar to CodeCamp Iasi 10 march 2012 - Practical Groovy (20)

AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
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
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
The Groovy Way
The Groovy WayThe Groovy Way
The Groovy Way
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
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
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
 
C# Is The Future
C# Is The FutureC# Is The Future
C# Is The Future
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Introduzione a C#
Introduzione a C#Introduzione a C#
Introduzione a C#
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 

More from Codecamp Romania

Cezar chitac the edge of experience
Cezar chitac   the edge of experienceCezar chitac   the edge of experience
Cezar chitac the edge of experience
Codecamp Romania
 
Cloud powered search
Cloud powered searchCloud powered search
Cloud powered search
Codecamp Romania
 
Business analysis techniques exercise your 6-pack
Business analysis techniques   exercise your 6-packBusiness analysis techniques   exercise your 6-pack
Business analysis techniques exercise your 6-pack
Codecamp Romania
 
Bpm company code camp - configuration or coding with pega
Bpm company   code camp - configuration or coding with pegaBpm company   code camp - configuration or coding with pega
Bpm company code camp - configuration or coding with pega
Codecamp Romania
 
Andrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseAndrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabase
Codecamp Romania
 
Agility and life
Agility and lifeAgility and life
Agility and life
Codecamp Romania
 
2015 dan ardelean develop for windows 10
2015 dan ardelean   develop for windows 10 2015 dan ardelean   develop for windows 10
2015 dan ardelean develop for windows 10
Codecamp Romania
 
The bigrewrite
The bigrewriteThe bigrewrite
The bigrewrite
Codecamp Romania
 
The case for continuous delivery
The case for continuous deliveryThe case for continuous delivery
The case for continuous delivery
Codecamp Romania
 
Stefan stolniceanu spritekit, 2 d or not 2d
Stefan stolniceanu   spritekit, 2 d or not 2dStefan stolniceanu   spritekit, 2 d or not 2d
Stefan stolniceanu spritekit, 2 d or not 2d
Codecamp Romania
 
Sizing epics tales from an agile kingdom
Sizing epics   tales from an agile kingdomSizing epics   tales from an agile kingdom
Sizing epics tales from an agile kingdom
Codecamp Romania
 
Scale net apps in aws
Scale net apps in awsScale net apps in aws
Scale net apps in aws
Codecamp Romania
 
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...
Codecamp Romania
 
Parallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflowParallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflow
Codecamp Romania
 
Material design screen transitions in android
Material design screen transitions in androidMaterial design screen transitions in android
Material design screen transitions in android
Codecamp Romania
 
Kickstart your own freelancing career
Kickstart your own freelancing careerKickstart your own freelancing career
Kickstart your own freelancing career
Codecamp Romania
 
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu   the soft stuff is the hard stuff. the agile soft skills toolkitIonut grecu   the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkit
Codecamp Romania
 
Ecma6 in the wild
Ecma6 in the wildEcma6 in the wild
Ecma6 in the wild
Codecamp Romania
 
Diana antohi me against myself or how to fail and move forward
Diana antohi   me against myself  or how to fail  and move forwardDiana antohi   me against myself  or how to fail  and move forward
Diana antohi me against myself or how to fail and move forward
Codecamp Romania
 

More from Codecamp Romania (20)

Cezar chitac the edge of experience
Cezar chitac   the edge of experienceCezar chitac   the edge of experience
Cezar chitac the edge of experience
 
Cloud powered search
Cloud powered searchCloud powered search
Cloud powered search
 
Ccp
CcpCcp
Ccp
 
Business analysis techniques exercise your 6-pack
Business analysis techniques   exercise your 6-packBusiness analysis techniques   exercise your 6-pack
Business analysis techniques exercise your 6-pack
 
Bpm company code camp - configuration or coding with pega
Bpm company   code camp - configuration or coding with pegaBpm company   code camp - configuration or coding with pega
Bpm company code camp - configuration or coding with pega
 
Andrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseAndrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabase
 
Agility and life
Agility and lifeAgility and life
Agility and life
 
2015 dan ardelean develop for windows 10
2015 dan ardelean   develop for windows 10 2015 dan ardelean   develop for windows 10
2015 dan ardelean develop for windows 10
 
The bigrewrite
The bigrewriteThe bigrewrite
The bigrewrite
 
The case for continuous delivery
The case for continuous deliveryThe case for continuous delivery
The case for continuous delivery
 
Stefan stolniceanu spritekit, 2 d or not 2d
Stefan stolniceanu   spritekit, 2 d or not 2dStefan stolniceanu   spritekit, 2 d or not 2d
Stefan stolniceanu spritekit, 2 d or not 2d
 
Sizing epics tales from an agile kingdom
Sizing epics   tales from an agile kingdomSizing epics   tales from an agile kingdom
Sizing epics tales from an agile kingdom
 
Scale net apps in aws
Scale net apps in awsScale net apps in aws
Scale net apps in aws
 
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...
 
Parallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflowParallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflow
 
Material design screen transitions in android
Material design screen transitions in androidMaterial design screen transitions in android
Material design screen transitions in android
 
Kickstart your own freelancing career
Kickstart your own freelancing careerKickstart your own freelancing career
Kickstart your own freelancing career
 
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu   the soft stuff is the hard stuff. the agile soft skills toolkitIonut grecu   the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkit
 
Ecma6 in the wild
Ecma6 in the wildEcma6 in the wild
Ecma6 in the wild
 
Diana antohi me against myself or how to fail and move forward
Diana antohi   me against myself  or how to fail  and move forwardDiana antohi   me against myself  or how to fail  and move forward
Diana antohi me against myself or how to fail and move forward
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 

CodeCamp Iasi 10 march 2012 - Practical Groovy

  • 1. Practical Groovy for Java Developers Gabriel Dogaru gabi@gabrieldogaru.com March 10 2012
  • 2. Agenda Groovy introduction Closures First Script Testing with Groovy Building with groovy
  • 3. 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 Compiled or interpreted Supports Domain-Specific Languages and other compact syntax
  • 4. A programming language is for thinking about programs, not for expressing programs you've already thought of. It should be a pencil, not a pen. Paul Graham
  • 5. I think I know java! //... Person.java //... Person.groovy //... Person.groovy public class Person { public class Person { private String name; class Person { name; private String private int age; String name private int age; int age public Person() { public Person() { } } } public Person(String name, int age) { public Person(String name, int age) { this.name = name; //... Person.groovyname; this.name = this.age = age; class Person { age; this.age = } } def name public String getName() { def ageString getName() { public return name; } return name; } } public void setName(String name) { person = new Person(name: "Ion", age: 66) public void setName(String name) { this.name = name; this.name = name; } //person.setAge(61) } person.age = 61 public int getAge() { public int getAge() { return age; return age; //System.out.println(person.getName()) } } println person.name public void setAge(int age) { public void setAge(int age) { this.age = age; //> Ionthis.age = age; } } } }
  • 6. Gotchas  Automatic Imports  Everything is an object  Optional data type declaration (Duck Typing)  Optional exception handling  Optional semicolons and parentheses  Optional return statements  Operator overloading
  • 7. Groovy Closures  Like a "code block" or a method pointer  May be passed as arguments  May accept arguments  May return values  Makes anonymous inner classes obsolete
  • 8. Closures //... ClosureExample.java //... ClosureExample.java //... ClosureExample.groovy import com.google.common.base.Predicate; import java.util.ArrayList; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import java.util.Arrays; import com.google.common.collect.Iterables; import java.util.ArrayList; import java.util.ArrayList; def numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] import java.util.List; import java.util.Arrays; import java.util.Arrays; def oddNumbers = numbers.findAll {it % 2!=0} import java.util.List; import java.util.List; public class ClosureExample { oddNumbers.each {println it} public static void main(String[] args) { public class ClosureExample { public class ClosureExample { List<Integer> numbers = Arrays.asList( public static void main(String[] args) { public static void main(String[] args) { List<Integer> numbers = 2, 3, 4, 5, 6, 7, 8, 9); 1, Arrays.asList( List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5, 6, 7, 8, 9); 1, 2, 3, 4, 5, 6, 7, 8, 9); List<> oddNumbers = new ArrayList<..>(); Iterable<> number : numbers) { for (int oddNumbers=Iterables.filter(numbers, Iterable<> oddNumbers=Iterables.filter(numbers, new Predicate<Integer>() { if (number % 2 != 0) { new Predicate<Integer>() { def odd = {Integer n-> public boolean apply(Integer number) { oddNumbers.add(number); public boolean apply(Integer number) { return return number % 2 != 0; n%2 != 0 } return number % 2 != 0; } } } } }); }); for (int number : oddNumbers) { def numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for (int number : oddNumbers) { for (int number : oddNumbers) { System.out.println(number); System.out.println(number); def oddNumbers = numbers.findAll odd System.out.println(number); }} oddNumbers.each {println it} } } } } } } }
  • 10. Write your first script //… WriteSomeXML .java @GrabResolver(name = 'maven-central', root = 'repo1.maven.org') import java.io.File; @Grapes( import java.io.FileOutputStream; import javax.xml.parsers.*; @Grab(group = 'xerces', module = 'xercesImpl', version = '2.10.0') )//… write xml import org.w3c.dom.*; import org.apache.xml.serialize.*; public class WriteSomeXML { new File("persons.xml").withWriter {writer -> import javax.xml.parsers.* { public static void main(String[] args) def xml = new MarkupBuilder(writer) DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); import org.apache.xml.serialize.* xml.persons db = null; DocumentBuilder { dbf Document doc = null; = DocumentBuilderFactory.newInstance() db = {person(id: 99) { trydbf.newDocumentBuilder() db = dbf.newDocumentBuilder(); doc = firstname("John") db.newDocument() doc = db.newDocument(); <?xml version="1.0" encoding="UTF-8"?> root = lastname("Smith") doc.createElement"persons“ Element root = doc.createElement("persons"); <persons> doc.appendChild root }}} doc.appendChild(root); Element el = doc.createElement("person"); <person id="99"> el = doc.createElement"person“ root.appendChild(el); root.appendChild "99"); <firstname>John</firstname> el.setAttribute("id", el el.setAttribute "id", doc.createElement("firstname"); Element firstname = "99“ <lastname>Smith</lastname> //… read xml el.appendChild(firstname); firstname = doc.createElement("firstname") </person> firstname.appendChild(doc.createTextNode("John")); </persons> el.appendChild firstname def parser lastname =XmlParser() Element = new doc.createElement("lastname"); firstname.appendChild doc.createTextNode("John") el.appendChild(lastname); def persons = parser.parse("persons.xml") lastname.appendChild(doc.createTextNode("Smith")); lastname = doc.createElement "lastname“ println "${persons.person[0].@id}" OutputFormat out = new OutputFormat(doc); el.appendChild lastnamelastname.appendChild out.setIndenting(true); persons.person.eachnew XMLSerializer(new FileOutputStream(new File("persons.xml")), out); doc.createTextNode="Smith" -> XMLSerializer xmlSer { person out println person.firstname[0].text() =xmlSer.serialize(doc); new OutputFormat doc } catch (Exception e) { out.indenting = true } e.printStackTrace(); xmlSer = new XMLSerializer(new FileOutputStream(new File("persons.xml")), } out) xmlSer.serialize doc } }
  • 11. Write your tests with groovy <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <scope>test</scope> </dependency> .... <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <compilerId>groovy-eclipse-compiler</compilerId> </configuration> <dependencies> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-eclipse-compiler</artifactId> </dependency> </dependencies> </plugin> ....
  • 12. Classes under test //… ExchangeRateDAO.java public interface ExchangeRateDAO { BigDecimal load(String currency); void save(String currency, BigDecimal value); } //… ExchangeRateService.java public class ExchangeRateService { private final ExchangeRateDAO rateDAO; public ExchangeRateService(ExchangeRateDAO rateDAO) { this.rateDAO = rateDAO; } public BigDecimal getRate(String currency) { return rateDAO.load(currency); } public void updateRate(String currency, BigDecimal value) { rateDAO.save(currency, value); } }
  • 13. Mocking – map coercion //… DynamicTest.groovy class DynamicTest { @Test public void test1() { ExchangeRateDAO rateDAO = {1.0} as ExchangeRateDAO ExchangeRateService service = new ExchangeRateService(rateDAO) assertEquals 1.0, service.getRate("USD") } @Test(expected = IllegalAccessError.class) public void test_named_methods() { ExchangeRateDAO rateDAO = [ load: {String v -> 1.0}, save: {String k, BigDecimal v -> throw new IllegalAccessError()} ] as ExchangeRateDAO ExchangeRateService service = new ExchangeRateService(rateDAO) assertEquals 1.0, service.getRate("USD") service.updateRate("1", 2) } }
  • 14. Mocking - MockFor //… MockForTest.groovy class MockForTest { @Test public void test() { def mockContext1 = new MockFor(ExchangeRateDAO) mockContext1.demand.load("USD") { 1.0 } def dummyDAO = mockContext1.proxyDelegateInstance() def service = new ExchangeRateService(dummyDAO) assertEquals 1.0, service.getRate("USD") mockContext1.verify dummyDAO } }
  • 15. Build with groovy <?xml version="1.0" encoding="UTF-8"?> <project name=“Ant Example" default="main" basedir="."> <property environment="env"/> <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"> <classpath> <fileset dir="${env.GROOVY_HOME}" includes="embeddable/groovy-all- *.jar,lib/ivy*.jar"/> </classpath> </taskdef> <target name=“print-xml"> <groovy> xmlfiles = new File('.').listFiles().findAll{ it =~ '.xml$' } xmlfiles.sort().each{ println it.toString() } </groovy> </target> </project>
  • 16. Build with Ant def ant = new AntBuilder() ant.echo(file:'Temp.java', ''' class Temp { public static void main(String[] args) {System.out.println("Hello"); }} ''') ant.javac(srcdir:'.', includes:'Temp.java', fork:'true') ant.java(classpath:'.', classname:'Temp', fork:'true') ant.echo('Done') // => // [javac] Compiling 1 source file // [java] Hello //[echo] Done
  • 17.
  • 18. 's please fill out the evaluations