88
An Introduction to Groovy for Java Developers Kostas Saidis www.niovity.com Java Hellenic User Group Meetup May 17, 2014

An Introduction to Groovy for Java Developers

Embed Size (px)

DESCRIPTION

An introduction to Groovy for Java developers with real-life examples that present how Groovy helped us win the 2nd prize in the Open Public Data Hackathon 2014 (http://www.ydmed.gov.gr/hackathon/)

Citation preview

Page 1: An Introduction to Groovy for Java Developers

An Introduction to Groovy for JavaDevelopers

Kostas Saidis

www.niovity.com

Java Hellenic User Group MeetupMay 17, 2014

Page 2: An Introduction to Groovy for Java Developers

Outline

Introductionto Groovy

1. MeetGroovy

What is Groovy?

Groovy History

Why Groovy

2. GroovyBasics

Using Groovy

LanguageOverview

Closures

Lists andRanges

Maps

3. Real-lifeGroovy

Open PublicData Hackathon

Our Web App

JSON and REST

Groovlets

Page 3: An Introduction to Groovy for Java Developers

About Me

Kostas [email protected]

Software & DataArchitect

Twitter:@saikosLinkedin:http://gr.linkedin.com/in/saiko

Short bio:I Academia

I BSc @ cs.unipi.gr (2001)I MSc @ di.uoa.gr (2004)I PhD @ di.uoa.gr (2011)

I IndustryI Freelance consultant, developer &

instructor since 1999I Founder & Managing Director

I JavaI Early Java enthusiast (1997)I Diving into Groovy since 2011

Page 4: An Introduction to Groovy for Java Developers

Target audience

Java developerswith little or no experience inGroovy or dynamic languages.

Page 5: An Introduction to Groovy for Java Developers

So, what brings us here?

The Java Platform

1. The language2. The development kit3. The virtual machine

The JVM is the key component!

The language and the JDK are aging, striving to catch up with newdevelopments.

Yet, Java 8 (with Streams and Lambdas) is a huge step forward!

Page 6: An Introduction to Groovy for Java Developers

What really brings us here!

The fun of programming

And Groovy programming is a whole lotta fun!

Page 7: An Introduction to Groovy for Java Developers

1. Meet Groovy

What isGroovy?

GroovyHistory

Why Groovy

Page 8: An Introduction to Groovy for Java Developers

What is Groovy?

Groovy is

a feature-richJava-friendlydynamic language

for the Java platform

Page 9: An Introduction to Groovy for Java Developers

Dynamic language?

What is a dynamic language?

A language that allows the types of variables to bechanged at runtime......among other things!

In GroovyWe can also change the behavior of objects and classes at runtime (withMetaprogramming).

Page 10: An Introduction to Groovy for Java Developers

Example

Introduce a new method in Strings1 String.metaClass.isUpperCase = {−>2 delegate.toCharArray().every{ Character.isUpperCase(it) }3 }4 assert "GROOVY".isUpperCase() == true5 assert "java".isUpperCase() == false

Page 11: An Introduction to Groovy for Java Developers
Page 12: An Introduction to Groovy for Java Developers

Keep an open mind

A language that doesn't affect the wayyou think about programming, is not

worth knowing.

Alan Perlis (1922 - 1990)ACM Turing Award, 1966

Page 13: An Introduction to Groovy for Java Developers

Languages and Typing

Static vs. DynamicI Statically typed: resolves the types of variables during

compilation. (e.g. Java)I Dynamically typed: resolves the types of variables at runtime.

(Groovy)Weak vs. Strong

I Strongly typed: you can't coerce to a wrong type --thelanguage guarantees type conformance. (Java & Groovy)

I Weakly typed: you can screw everything up in all possible ways.(e.g. C)

Page 14: An Introduction to Groovy for Java Developers

Java-friendly?

Groovy is:I A super version of Java

I Augments Java with additional features→ the GDK extends JDK inso many helpful ways!

I Designed as a companion language for JavaI seamless integration with Java→ an additional jar at runtime!I syntactically aligned with Java→ syntactically correct Java will

work in Groovy (with some gotchas)!I compiles into JVM bytecode and preserves Java semantics→ call

Groovy from Java == call Java from Java!

I the 2nd language targeting the Java platform (JSR-241)→Java was the first!

Page 15: An Introduction to Groovy for Java Developers

Feature-rich?

Groovy featuresI Fully object-oriented -- e.g. Traits in new version (2.3).I Optional typing --static or dynamic.I Duck typing.I List, map, range, regular expression literals.I Operator overloading.I Closures.I GroovyBeans.I GString and GPath.I Multimethods and metaprogramming.I Easily build custom DSLs (e.g. Gradle, Spock).

Page 16: An Introduction to Groovy for Java Developers

Example

Optional Typing1 def s1 = "saiko"2 assert s1.class == String.class3 s1 = 34 assert s1.class == Integer.class5 Integer s2 = 36 try {7 s2 = "saiko"8 }9 catch(ex) {

10 assert ex.message == "Cannot cast object 'saiko' with class 'java.lang.String' to class 'java.lang.Integer'"

11 }

Page 17: An Introduction to Groovy for Java Developers

Groovy History

I 2003: Started by James Strachan and Bob McWhirter.I 2004: Commissioned into JSR 241 but was almost abandoned.I 2005: Brought back to life by Guillaume Laforge and Jeremy

Rayner.I 2007: Groovy version 1.0.I 2012: Groovy version 2.0.I 2014: Groovy version 2.3 (official support for JDK 8).

Page 18: An Introduction to Groovy for Java Developers

Going Mainstream

Awesome Groovy-based tools & frameworksI Grails: Web development framework.I Gradle: Build automation tool. (my next one, if you like!)I Spock: Testing and specification framework.I CodeNarc: Static analysis tool.I easyb: Behavior-driven development framework.I Geb: Browser automation tool.I Griffon: Desktop app framework.I GPars: Multi-paradigm concurrency framework.

Groovy is supported by Pivotal.

Page 19: An Introduction to Groovy for Java Developers

Why Groovy?

I Open Source. → Apache v2.0 License.I Near-zero learning curve. → You' ll become a Groovyist before

you realize it!I Leverage Java investment. → Rock-solid Java foundations.I Focus on your problem/app. → No more boilerplate!I More expressive, powerful and concise code. →

Productivity boost!

Page 20: An Introduction to Groovy for Java Developers

A picture is worth some thousand words

Page 21: An Introduction to Groovy for Java Developers

2. Groovy Basics

UsingGroovy

LanguageOverview

Closures

Lists andRanges

Maps

Page 22: An Introduction to Groovy for Java Developers

Groovy Tools

1. groovyc: Compliles groovy sources to JVM class files.2. groovysh: Executes code interactively.3. groovyConsole: GUI for interactive code execution

the best place to start .4. groovy: Executes groovy scripts. Use it like bash, perl, python,

etc. (#!/usr/bin/groovy).5. groovydoc: Generates documentation (like javadoc).

Page 23: An Introduction to Groovy for Java Developers

Using the Groovy Console

Use Groovy console to experiment, test and evaluate code.

Page 24: An Introduction to Groovy for Java Developers

Using the Groovy Interpreter

What date/time is it?groovy −e "print new Date()"

List files recursively

groovy −e "new File('.').eachFileRecurse { println it }"

Page 25: An Introduction to Groovy for Java Developers

Groovy scripts

I No mandatory class definitions, no main methods, noboilerplate.

I Groovy creates them for you automagically!

Writing a Groovy script

Fibonacci.groovy1 def fib(n) { // a method: the return type is not mandatory2 n<2 ? 1 : fib(n−1)+fib(n−2)3 }4 if (args) { // command−line args5 println fib(args[0] as Integer)6 }

Page 26: An Introduction to Groovy for Java Developers

Groovy scripts continued

Running the script

> groovy Fibonacci 834

> groovyc Fibonacci.groovy> java −cp $GROOVY_HOME/embeddable/groovy−all.2.0.0.jar:. Fibonacci 834

Page 27: An Introduction to Groovy for Java Developers

The Groovy Syntax

The majority of Java syntax is part of the Groovy syntax:I packagesI importsI control structuresI exception handlingI classes and methodsI object instantiation and method calls

Gotchas: Arrays, additional Groovy keywords, equals checks, etc.

Page 28: An Introduction to Groovy for Java Developers

Default imports

The following imports are included by defaultI java.lang.*I java.util.*I java.net.*I groovy.lang.*I groovy.util.*I java.math.BigInteger and java.math.BigDecimal

Page 29: An Introduction to Groovy for Java Developers

Groovy truth and equals

I Null value is false.I Empty collection or map is false.I Empty string is false.I Zero value is false.

Gotcha

I The == operator performs value equality (like Javaequals() ).

I Use the method is for identity (available in every Groovyobject).

Page 30: An Introduction to Groovy for Java Developers

Groovy truth

Examples1 def f = null2 def t = "string"3 assert f == false4 assert t == true5 list = []6 map = [a:1]7 assert list == false8 assert map == false9 String s = ""

10 assert s == false11 i = 112 z = 0.013 assert i == true14 assert z == false

Page 31: An Introduction to Groovy for Java Developers

Optionals

The following are optional:I semicolons: required only when you write multiple statements

in one line.I variable types: you decide what should be static or dynamic.I return statements: the last evaluated expression is the

default return value Gotcha .I parentheses: in method/function invocations Gotcha .

Page 32: An Introduction to Groovy for Java Developers

Optionals

Examples1 //a method2 def fac(n) { n<=1? 1 : n*fac(n−1)}3 assert fac(3) == 64 //a method with default arg value5 Integer factorial(Integer n=3) { return (n<=1? 1 : n*factorial(n

−1)) }6 assert factorial(3) == 67 //invoke them without parentheses8 def x = fac 39 def y = factorial 3

10 assert x == y11 x = fac 3 + 1 //will calculate the factorial of 4.12 assert x == fac(4) //Not always what you want!13 x = fac(3 + 1) //use parentheses to disambiguate14 //where parentheses are required15 x = factorial() //Groovy will look for a property otherwise16 assert x == fac(3)

Page 33: An Introduction to Groovy for Java Developers

Everything is an object

In Groovy:I all objects are derived from groovy.lang.GroovyObject, which

extends java.lang.Object.I all integral numbers are java.lang.Integers (or java.lang.Longs

using the proper Java notation).I all real numbers are java.math.BigDecimals.I all booleans are java.lang.Booleans.

Page 34: An Introduction to Groovy for Java Developers

Example

Everything's an object1 def x = 12 int y = 13 assert x.class == Integer.class4 assert y.class == Integer.class5 def l = 1L6 assert l.class == Long.class7 def z = 0.38 assert z.class == BigDecimal.class9 def flag = false

10 assert flag.class == Boolean.class

Page 35: An Introduction to Groovy for Java Developers

Strings

Groovy strings support:I Single quotes: ordinary strings.I Double quotes: ordinary strings with variable expansion

(GStrings).I Triple quotes: multi-line strings with variable expansion

(GStrings).I Slashy strings: strings enclosed in slashes; no need to escape

backslashes (useful for regular expressions and file paths).I operator overloading.

Page 36: An Introduction to Groovy for Java Developers

Examples

Strings1 def mlStr = """ I am a multi−line2 string!"""3 def name = 'Angus';def surname = "Young"4 //GStrings5 def fullname = "$name $surname"6 assert fullname == "Angus Young"7 //operator overloading8 def s = name * 39 assert s == "AngusAngusAngus"

10 s = fullname − name11 assert s.trim() == surname12 //slashy strings: preserve backslashes; no escaping is required13 s = /\n\r/14 assert s.size() == 4

Page 37: An Introduction to Groovy for Java Developers

Numbers

In Groovy all numbers are objects and BigDecimal arithmetic is used bydefault.

Examples1 def x = 32 assert x.plus(4) == x + 43 assert x.multiply(4) = x * 44 assert x.mod(4) == x % 45 //BigDecimal arithmetic6 assert x/4 == x.div(4)7 assert x/4 != x.intdiv(4)8 assert 1/2 == 0.59 assert 1/3 == 0.3333333333

Page 38: An Introduction to Groovy for Java Developers

Java beans for human beings

In Groovy classes/beans:I Methods and classes are public by default.I Members are private by default.I The @PackageScope annotation is used for package scoped

class members.I Enhanced bean property support.I Dynamic constructor arguments.I Accessors (getters and setters) are generated automatically.I You can use the this keyword inside static methods (which

refers to this class).

Page 39: An Introduction to Groovy for Java Developers

Defining a Groovy class

A Person class1 class Person {2 String name3 String surname4 @Override5 String toString() { "$surname, $name" }6 }

Compile the Person.groovy

groovyc Person.groovyResult: A ready to use Person.class

Page 40: An Introduction to Groovy for Java Developers

Use the Person class

ExamplesFrom Groovy

1 p = new Person(name:"Theodoros", surname:"Kolokotronis")2 assert p.toString() == "Theodoros Kolokotronis"

From Java1 public class UsingPerson {2 public static void main(String[] args) {3 Person p = new Person();4 p.setSurname("Young");5 p.setName("Angus");6 HashMap map = new HashMap();7 map.put("name", "James");8 map.put("surname", "Bond");9 Person p1 = new Person(map);

10 }11 }

Page 41: An Introduction to Groovy for Java Developers

Additional Operators

I Safe navigation: x?.method()I Elvis: x = y ?: "no y"I Spread: ["java","groovy"]*.size() →[4,6]

I and more... <=> , =~ , ==~ , .@ , .&

Page 42: An Introduction to Groovy for Java Developers

Groovy powerful switch statement

1 switch(val) {2 case "String":3 //a string4 break5 case 10..100:6 //a range7 break8 case Date:9 //a date instance

10 break11 case ~/gw+/:12 //a reg−ex13 break14 case ['A', 'B']:15 //a list16 break17 case { it instanceOf Number && it > Integer.MAX_VALUE }18 //a closure19 break20 default:21 //the default, treated as an "else" in Groovy (if22 //all else fails, run the default). It should always23 //be at the end of the switch statement.24 }

Page 43: An Introduction to Groovy for Java Developers

Dynamic method dispatch

I Java dispatches methods according to the type of thearguments at compile time.

I Groovy dispatches methods according to the type of thearguments at runtime (multimethods).

Example1 public void foo(String arg) { System.out.println("String"); }2 public void foo(Object o) { System.out.println("Object"); }3 Object o = "The type of o at runtime is String";4 foo(o);

Java output: ObjectGroovy output: String

Page 44: An Introduction to Groovy for Java Developers

Other differences from Java

I There is no distinction between checked and unchecked(runtime) exceptions. All exceptions are runtime exceptions!

I Assertions are enabled by default.I Support for default values in method arguments.I use , is and as are keywords. Don't use them as variable

names.I You cannot declare more than one variables in for loops.I Arrays should be initialized with list-like syntax:int[] a = [1, 2, 3] . Avoid int a[]notation. Gotcha .

Page 45: An Introduction to Groovy for Java Developers

What is a closure?

DefinitionA closure is a function together with a referencing environment.

Closures are anonymous functions that:I may accept parameters or return a value,I can be assigned to variables,I can be passed as arguments,I capture the variables of their surrounding lexical scope.

Page 46: An Introduction to Groovy for Java Developers

Groovy closures

Example1 //a block of code assigned to a variable2 def num = { int n −> n <=> 0 }3 //what type is that?4 assert num instanceof Closure5 //it: the default closure argument6 def num2 = { it <=> 0 }7 assert num(−3) == num2(−3)8 def x = 39 def times = { it * x }

10 assert times(3) == 911 x = 412 assert times(3) == 12

Page 47: An Introduction to Groovy for Java Developers

Functional Programming with Groovy

Currying & Higher-order functions1 def func = { Closure c, int i, int j −>2 c.call(i, j)3 }4 def add = func.curry { int i, int j −> i + j }5 assert add(1,2) == 3

Composition1 def add1 = { it + 1}2 def sq = { it*it }3 assert sq(add1(2)) == 9 //composition4 def trans1 = add1 >> sq //left to right5 assert trans1(2) == sq(add1(2))6 def trans2 = add1 << sq //right to left7 assert trans2(2) == add1(sq(2))

Page 48: An Introduction to Groovy for Java Developers

Closure owner and delegate

Example1 //All closures have 3 implicit variables:2 //this: as in Java3 //owner: the enclosing object (either a closure or this)4 //delegate: defaults to owner but can be changed5 def test = {6 ((this == owner) && (owner == delegate))7 return { (this != owner) && (owner == delegate) }8 }9 assert test()()

10 //changing the delegate11 def collectWithIndex = { Closure c−>12 int i = 013 delegate.collect { c(it, i++) }14 }15 def map = ["name":"Angus", "surname":"Young"]16 collectWithIndex.delegate = map17 def list = collectWithIndex { entry, i −> [i, entry.key, entry.

value] }18 assert list.flatten() == [0, "name", "Angus", 1, "surname", "

Young"]

Page 49: An Introduction to Groovy for Java Developers

Java 8 Lambda Expressions

Groovy closures ̸= Java lambda expressions.Lambda expressions

I Language facility for implementing functional interfacesI Interfaces with a single abstract method.I Function, Predicate, Supplier, Consumer.

I Type inference at compile time.I Free variables must be final or effective final.I Do make your Java life easier.

Page 50: An Introduction to Groovy for Java Developers

Lists

Groovy offers:I Special syntax for list literals.I Additional common list methods.

Combine with closures for extremely expressive and powerful code!

Examples1 //a list2 def list = [1, "2", 3.0]3 //what type is that?4 assert list.class == ArrayList.class5 //list elements6 assert list.get(1) == "2"7 assert list[1] == "2"8 assert list.getAt(1) == "2"9 //list.getAt(i) equivalent to list[i]

10 //negative indexes − not for the standard list.get(i)11 assert list[−1] == 3.012 assert list.getAt(−2) == "2"

Page 51: An Introduction to Groovy for Java Developers

More list examples1 //another list2 def list3 = [5, 3, 1, ] //trailing comma OK3 list3[0] = 34 list3.putAt(0, 3) //list.putAt(i,val) equivalent to list[i]=val5 list3.set(0, 3)6 assert list3 == [3, 3, 1]7 //the in operator8 assert '2' in list9 assert list.contains('2')

10 //operator overloading11 assert list + [1] == [1, "2", 3.0, 1]12 assert list − [1] == ["2", 3.0]13 assert list * 2 == [1, "2", 3.0, 1, "2", 3.0]14 assert list + list == list * 215 //append to list16 assert list << 1 == [1, "2", 3.0, 1]17 def otherList = [4, 5.0, "6"]18 assert list << otherList == [1, "2", 3.0, 1, [4, 5.0, "6"]]19 //methods20 assert list.flatten() == [1, "2", 3.0, 1, 4, 5.0, "6"]21 assert list.flatten().unique() == [1, "2", 3.0, 4, 5.0, "6"]

Page 52: An Introduction to Groovy for Java Developers

Even more list examples1 //methods that accept closure arguments2 otherList = list.flatten().collect { it as Integer }3 assert otherList == [1, 2, 3, 1, 4, 5, 6]4 def toInt = { Object o −>5 try { return o as Integer }6 catch(e) { return 0 }7 }8 assert list.flatten().collect(toInt) == otherList9 assert [5, "6", "seven"].collect(toInt) == [5, 6, 0]

10 //convert a list to a set11 def set = otherList as Set12 assert otherList instanceof List13 assert set instanceof Set14 //collect is available to all groovy objects15 set.collect { it + 1 } == [2, 3, 4, 5, 6, 7]16 //list to string17 assert otherList.unique().join(', ') == '1, 2, 3, 4, 5, 6'

Page 53: An Introduction to Groovy for Java Developers

Enough with these list examples1 //some more list methods2 assert otherList.count(1) == 23 assert otherList.sum() == 224 assert otherList.intersect([1, 3, 4]) == [1, 3, 4]5 assert otherList.disjoint([0, 10, 20])6 assert otherList.min() == 17 assert otherList.max() == 68 assert otherList.reverse().unique().sort() == [1, 2, 3, 4, 5, 6]9 //some more closures

10 assert otherList.findAll { it%2 == 0} == [2, 4, 6]11 assert otherList.every { it > 0 } //checks whether the closure

holds for every list element12 assert !otherList.every { it < 1 }13 def listWithNulls = [1, null, 2]14 assert !listWithNulls.every() //checks whether groovy truth

holds for every element15 //the spread (*.) operator16 def strings = ['one', 'the other', 'and another']17 assert strings*.size() == strings.collect { it.size() }18 //list*.action() calls list.collect { it.action() }19 assert strings*.toUpperCase() == ['ONE', 'THE OTHER', 'AND

ANOTHER']

Page 54: An Introduction to Groovy for Java Developers

Ranges

Groovy:I treats ranges as first-class objects.I offers special syntax for ranges.

Examples1 def letters = 'a'..'z'2 def digits = 0..93 //what type is that?4 assert letters.class == ObjectRange5 assert digits.class == IntRange6 //okay, but wait...7 assert letters instanceof java.util.List8 assert digits instanceof java.util.List9 //ranges are lists of sequential values.

10 assert digits == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]11 assert letters[0] == 'a'12 assert letters.size() == 26

Page 55: An Introduction to Groovy for Java Developers

More ranges examples1 //methods2 def otherDigits = digits.collect { it*2 } //or, equivalently3 otherDigits = digits*.multiply(2)4 assert otherDigits == [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]5 //half−open ranges6 def digits2 = 0..<9 //0 up to 9 exclusive7 assert digits2.size() == 98 //get the from,to values of ranges9 assert digits.from == digits2.from

10 assert digits.to == digits2.to + 111 //another way to express a range12 assert 1..4 == (1..4)13 //looping14 (1..4).each { print it }15 //stepping16 (1..4).step(2) { print it }17 //slicing18 def list = ['one', 'two', 'three', 'four', 'five', 'six']19 assert list[1..3] == ['two', 'three', 'four']20 assert list[0..<2] == ['one', 'two']21 assert list[−1] == 'six'22 assert list[3..−1] == ['four', 'five', 'six']23 assert list[−1..−3] == ['six', 'five', 'four']

Page 56: An Introduction to Groovy for Java Developers

Maps

Groovy:I offers pecial syntax for map literals.I provides dditional common map methods.I uses maps + closures for duck typing: if it walks and swims like

a duck, it is a duck! → rapid implementation of interfaces

Examples1 //a map2 def map = ['id' : 12, 'name' : "John", 'surname' : "Doe"]3 assert map.size() == 34 //keys which are valid Java identifiers need no quotes5 def now = new Date()6 def map2 = [7 id : 1,8 value : 2.0,9 "peter's birthday": now

10 ]

Page 57: An Introduction to Groovy for Java Developers

More maps examples1 //we can use map.key when key is valid Java identifier2 assert map2.id == 13 //we can quote the key if needed4 assert map2."peter's birthday" == now5 //we can also use subscription notation map[key]6 assert map2["peter's birthday"] == now7 //and the standard get method8 assert map2.get('value') == 29 assert map.get('foo') == null

10 //default value when key not found11 assert map.get('foo', 'No such key') == 'No such key'12 //adds the default value in the map13 assert map.containsKey('foo')14 //what type is the map?15 try {16 assert map.class == LinkedHashMap.class17 }18 catch(Error e) {19 assert map.class == null //the map is looking for the 'class

' key20 map.getClass() == LinkedHashMap.class21 }

Page 58: An Introduction to Groovy for Java Developers

Even more maps examples1 //put/update values2 map.newKey = "new key's value"3 map2['newKey'] = map.newKey4 //use parentheses to add the value of a var in a map (and not

its name)5 def anotherKey = "address"6 map[(anotherKey)] = "Petraki 28"7 assert map.address == "Petraki 28"8 //iterate with each9 map.each { println "In each: ${it.class}" }

10 //the closure argument is a Map.Entry instance11 map.each { println "In each again: ${it.key} = ${it.value}" }12 //all Java Map methods are here13 assert !map.isEmpty()14 assert map.containsKey('id')15 assert map.containsValue(12)16 //use a HashMap instead of a LinkedHashMap17 def map3 = new HashMap()18 assert map3.getClass() == HashMap.class19 //empty map20 def map4 = [:]21 assert !map4//empty map is false

Page 59: An Introduction to Groovy for Java Developers

Some more maps examples1 //find in map2 assert ['id':12, 'foo':'No such key'] == map.findAll{ it.key.

size() <= 3}3 //group by4 def list = [1, '2', 3, '4', '5', 6]5 def map5 = list.groupBy { it.getClass().getSimpleName() }6 assert ['String': ['2', '4', '5'], 'Integer': [1, 3, 6]] == map57 //store closures in a map8 def actions = [9 login : { println "login" },

10 logout : { println "logout" }11 ]12 //execute the closures13 actions.login.call() //or14 actions['logout'].call() //or15 actions.logout()

Page 60: An Introduction to Groovy for Java Developers

Duck typing1 //Duck typing − a comparator2 def cmp = [3 compare : { a, b −> a.size() <=> b.size() }4 ] as Comparator5 assert cmp instanceof Comparator6 //a list7 def list2 = ['a' , 'quick', 'brown', 'fox', 'jumps', 'over', 'a'

, 'lazy', 'dog']8 assert list2.sort(cmp) == ['a', 'a', 'fox', 'dog', 'over', 'lazy

', 'quick', 'brown', 'jumps']9 //a runnable

10 def r = [11 run : {12 def t = Thread.currentThread()13 println "Thread ${t.getId()} starting"14 t.sleep(1000)15 println "Thread ${t.getId()} finished"16 }17 ] as Runnable18 assert r instanceof Runnable19 new Thread(r).start()

Page 61: An Introduction to Groovy for Java Developers

Duck typing continued

Another Example1 interface Doer {2 void doThis();3 void doThat();4 }5 class DoerImpl implements Doer {6 void doThis(){"Did this"}7 void doThat(){"Did that"}8 }9 def doer1 = new DoerImpl()

10 assert doer1 instanceof Doer11 def doer2 = [12 doThis:{"This done"},13 doThat:{"That done"}14 ] as Doer15 assert doer2 instanceof Doer

Page 62: An Introduction to Groovy for Java Developers

3. Real-lifeGroovy

OpenPublic DataHackathon

Our WebApp

JSONand REST

Groovlets

Page 63: An Introduction to Groovy for Java Developers

Open Public Data Hackathon

Held between 15 - 30 April 2014.Organized by the Ministry of Administration Reform and E-Governance(ydmed.gr), in association with:

1. aspete.gr2. hua.gr3. ellak.gr

Requirement: deliver an app that utilizes open public data (fromdata.gov.gr or elsewhere).

Page 64: An Introduction to Groovy for Java Developers

We won the 2nd prize!

And Groovy helped us do it!We shall discuss:

1. How to build a RESTful API with Groovy and Restlet.2. How to build dynamic web pages with Groovlets.

Page 65: An Introduction to Groovy for Java Developers

Our Web App

A prototype of a cloud service forI Accessing/retrieving dataI Searching/querying dataI Visualizing/embedding data

through a powerful RESTful API.

Page 66: An Introduction to Groovy for Java Developers

Quick demo here

opendatacloud.gr

Page 67: An Introduction to Groovy for Java Developers

Technologies used

BackendI Java 7.xI Apache Tomcat 7.0.xI Groovy 2.2.xI Restlet 2.2.0I Apache POI 3.10I Elastic Search 1.1.1

FrontendI Bootstrap 3I jQuery 1.10I D3.js

Page 68: An Introduction to Groovy for Java Developers

The data model

We haveI Kept thins as simple as possible.I Data source groups: Sets of

I Data sources: Tabular data in excel files arrangedI in columnsI and rows.

After all, it is a prototype!

Page 69: An Introduction to Groovy for Java Developers

The web.xml

Two servlets1 <servlet>2 <servlet−name>RestletServlet</servlet−name>3 <servlet−class>org.restlet.ext.servlet.ServerServlet</servlet−

class>4 <init−param>5 <param−name>org.restlet.application</param−name>6 <param−value>com.niovity.opd.restlet.App</param−value>7 </init−param>8 </servlet>9 <servlet−mapping>

10 <servlet−name>RestletServlet</servlet−name>11 <url−pattern>/api/v0/*</url−pattern>12 </servlet−mapping>13 <servlet>14 <servlet−name>groovy</servlet−name>15 <servlet−class>groovy.servlet.GroovyServlet</servlet−class>16 </servlet>17 <servlet−mapping>18 <servlet−name>groovy</servlet−name>19 <url−pattern>*.groovy</url−pattern>20 </servlet−mapping>

Page 70: An Introduction to Groovy for Java Developers

The web.xml continued

And a listener1 <listener>2 <listener−class>com.niovity.opd.Listener</listener−class>3 </listener>1 package com.niovity.opd2 class Listener implements ServletContextListener {3 @Override4 void contextInitialized(ServletContextEvent e) {5 try {6 //Initialize log4j & elastic7 ...8 //Initialize the config9 String basePath = ctx.getRealPath("/data")

10 Config.instance.init(basePath)11 } catch(Exception e) {12 System.err.println("Fatal error: ${e.getMessage()}")13 e.printStackTrace(System.err)14 throw new ServletException(e.getMessage(), e)15 }16 }17 }

Page 71: An Introduction to Groovy for Java Developers

Groovy @Singleton Annotation

Config1 package com.niovity.opd2 @Singleton class Config {3 String basePath4 Map<String, DataSourceGroup> sourceGroups = [:]5 void init(String basePath) throws Exception {6 this.basePath = basePath7 def groups = [:]8 DataSourceGroup nte = new DataSourceGroup(9 id: "nte",

10 title:"...", ...11 )12 nte.addDataSource(new DataSource(title: "...",...))13 groups.nte = nte14 ...15 sourceGroups = Collections.unmodifiableMap(groups)16 }17 }

Page 72: An Introduction to Groovy for Java Developers

The Restlet App

The REST router1 package com.niovity.opd.restlet2 import org.restlet.Application3 import org.restlet.Restlet4 import org.restlet.routing.Router5 class App extends Application {6 @Override7 synchronized Restlet createInboundRoot() {8 Router router = new Router(getContext())9 router.attach "/groups", SourceGroups

10 router.attach "/{grp}/{src}", Source11 router.attach "/search", Search12 return router13 }14 }

Page 73: An Introduction to Groovy for Java Developers

An example of a Restlet

GET the source groups1 package com.niovity.opd.restlet2 import ...3 class SourceGroups extends ServerResource{4 @Override5 protected Representation get() throws ResourceException {6 def groups = Config.instance.sourceGroups7 def result = [:]8 result.total = groups.size()9 result.groups = []

10 groups.each {11 def group = [id : it.key, title : it.value.title, ...]12 group.sources = []13 it.value.dataSources().eachWithIndex { source, index −>14 def src = [id:"/${it.key}/$index",...]15 group.sources.push(src)16 }17 result.groups.push(group)18 }19 return new JsonRespresentation(result)20 }21 }

Page 74: An Introduction to Groovy for Java Developers

JSON

JsonRepresentation1 package com.niovity.opd.restlet2 import groovy.json.JsonBuilder3 import org.restlet.data.MediaType4 import org.restlet.representation.WriterRepresentation5 class JsonRespresentation extends WriterRepresentation {6 private Map result7 JsonRespresentation(Map result) {8 super(MediaType.APPLICATION_JSON)9 this.result = result ?: [:]

10 }11 @Override12 void write(Writer writer) throws IOException {13 new JsonBuilder(result).writeTo(writer)14 }15 }

Page 75: An Introduction to Groovy for Java Developers

Groovlets

Groovy scripts on the server sideI Compiled on the flyI No boilerplateI With some handy implicit variables provided by default

I request,response : Http servler request andresponse

I params : request parametersI context, application : the ServletContext

objectI session : the HttpSession objectI out : the writer of the responseI sout : the output stream of the responseI html: a groovy.xml.MarkupBuilder which writes to out

Page 76: An Introduction to Groovy for Java Developers

Display a data source in HTML table

source.grovy1 String groupId = request.getParameter("grp")2 String srcId = request.getParameter("src")3 def group = Config.instance.sourceGroups.get(groupId)4 def sources = group.dataSources()5 int index = srcId as Integer6 def source = group.dataSources().get(index)7 println """8 ...9 <table class="table table−bordered table−striped" >

10 <thead>11 <tr>12 <th>#</th>13 ${source.columnNames.collect {"<th>$it</th>"}.join("")}14 </tr>15 </thead>16 <tbody >17 """

Page 77: An Introduction to Groovy for Java Developers

HTML table continued

source.grovy1 source.rows.eachWithIndex {Map row, int i −>2 println """3 <tr>4 <td>${i+1}</td>5 ${source.columnNames.collect{ "<td>${row.get(it)}</td>"}.join

("")}6 </tr>7 """8 }9 println """

10 </tbody>11 </table>12 ...13 """

Page 78: An Introduction to Groovy for Java Developers

4. Epilogue

Page 79: An Introduction to Groovy for Java Developers

Groovy is Java on steroids!

I Easy to use: Its integration with the Java platform is insanelybrilliant!

I Expressive: Do more with less code!I Effective: Focus on your app and stop wasting your time with

the irrelevant!I Agile: Groovy is agile and rapid prototyping is a few Groovy lines

away!I Leverage Java expertise. Build upon your Java skills.I Powerful: The swiss army knife of the Java hacker!

Page 80: An Introduction to Groovy for Java Developers

Swiss army knife, indeed

Ain't this groovy or what?

db.groovy1 @GrabConfig(systemClassLoader=true)2 @Grab(group='mysql', module='mysql−connector−java', version='

5.1.6')3 import groovy.sql.Sql4 def query="select count(*) as c, date(creationDate) as d from

dofields group by d order by c desc limit 10"5 def url="jdbc:mysql://localhost:3306/test_db?characterEncoding=

utf−8"6 def (u,p)=["test","test"]7 try {8 def sql = Sql.newInstance(url,u,p,"com.mysql.jdbc.Driver")9 sql.eachRow(query) { println("${it.c}:${it.d}") }

10 }11 catch(e) { e.printStackTrace() }

Page 81: An Introduction to Groovy for Java Developers

Output

Run itgroovy dbOutput

1 9427:2004−08−202 6615:2004−10−293 5498:2004−10−084 5103:2004−08−315 4864:2004−10−146 4675:2004−10−317 4583:2004−10−058 4570:2004−08−219 4339:2004−09−30

10 4235:2004−10−30

Page 82: An Introduction to Groovy for Java Developers

Groovy rocks!

Page 83: An Introduction to Groovy for Java Developers

We 've only scratched the surface

Groovy topics not coveredI MetaprogrammingI GrapeI BuildersI Working with XMLI Working with SQLI TestingI And much, much more...

Perhaps in a 2nd part?

Page 84: An Introduction to Groovy for Java Developers

What about performance?

Programmers have spent far too much timeworrying about efficiency in the wrong placesat the wrong times; premature optimization is

the root of all evil.

Donald E. KnuthACM Turing Award, 1974

Page 85: An Introduction to Groovy for Java Developers

Put in other terms

The reason to use Groovy should be because itimproves your performance not the computer's.

matthew@stackoverflow

Page 86: An Introduction to Groovy for Java Developers

About Groovy Performance

Sorry, it hasn't bothered me yet.I Groovy 2.x introduced the @CompileStatic annotation.

I Most of Groovy method calls are compiled into direct JVM bytecodemethod calls.

I People report that Groovy reaches to almost identical performancewith Java.

I Start with Groovy and (re)write your performance-criticalclasses in Java as you grow.

I You can find various benchmarks and performance comparisonson the web.

I Any volunteers for benchmarking, should we do a 2nd part?

Page 87: An Introduction to Groovy for Java Developers

Resources

1. Programming Groovy 2, V. Subramaniam, The PragmaticBookshelf, 978-1-937785-30-7, 2013

2. Groovy in Action, D. Koenig, A. Glover, P. King, G. Laforge and J.Skeet, Manning Publications, 1-932394-84-2, 2007

3. Groovy Web Sitehttp://groovy.codehaus.org

4. Groovy language documentation betahttp://beta.groovy-lang.org/docs/groovy-2.3.0/html/documentation/

Page 88: An Introduction to Groovy for Java Developers

Thank you

Questions?Proudly powered by:

LATEXUsing the Beamer class &

the Wronki theme (slightly modified).