• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
CodeCamp Iasi 10 march 2012 - Practical Groovy
 

CodeCamp Iasi 10 march 2012 - Practical Groovy

on

  • 911 views

 

Statistics

Views

Total Views
911
Views on SlideShare
911
Embed Views
0

Actions

Likes
0
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    CodeCamp Iasi 10 march 2012 - Practical Groovy CodeCamp Iasi 10 march 2012 - Practical Groovy Presentation Transcript

    • Practical Groovy for Java DevelopersGabriel Dogarugabi@gabrieldogaru.comMarch 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 thinkingabout programs, not for expressingprograms youve already thought of. Itshould be a pencil, not a pen. Paul Graham
    • I think I know java!//... Person.java //... Person.groovy //... Person.groovypublic 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.groovyimport 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...olHow 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 xmlimport 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", elel.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 firstnamedef 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 { personout 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.groovyclass 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 Antdef 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
    • splease fill out the evaluations