SlideShare une entreprise Scribd logo
1  sur  18
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

Contenu connexe

Tendances

About java
About javaAbout java
About java
Jay Xu
 
Predictably
PredictablyPredictably
Predictably
ztellman
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
Jan Kronquist
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Tendances (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
 

En vedette (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
 

Similaire à CodeCamp Iasi 10 march 2012 - Practical Groovy

AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
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.pdf
akshpatil4
 
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
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 

Similaire à 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
 

Plus de Codecamp Romania

Plus de 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
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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?
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

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