Groovy for Java Devs

Information about Groovy for Java Devs

Published on March 8, 2019

Author: zak89s

Source: slideshare.net

Content

1. objectcomputing.com© 2019, Object Computing, Inc. (OCI). All rights reserved. No part of these notes may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior, written permission of Object Computing, Inc. (OCI) Gettin’ Groovy for Java Devs Zachary Klein, Senior Software Engineer

2. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com Zachary Klein is a Senior Software Engineer at OCI. He has been practicing web development since 2010 and frontend development since 2015. He’s a contributor to both the Grails and Micronaut frameworks, a conference speaker and an instructor in OCI’s training practice. Zachary’s home base is in St Louis, MO, along with his wife, Beth, and their three children. 2 Speaker

3. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 1. What is Groovy? 2. Why use Groovy? 3. From Java to Groovy 4. Overview/Demos of Groovy Features 3 Agenda 5. Groovy Ecosystem 6. What’s Next for Groovy? 7. Resources

4. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 4 What is Groovy?

5. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Dynamic Language for the JVM • Style-Agnostic: OOP, Functional, Scripts, DSLs • Static and Dynamic Type-checking • Compiles to Java Bytecode • Development sponsored by Object Computing, Inc • Top-level Project of the Apache Software Foundation 5 What is Groovy?

6. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 6

7. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 7 Why Use Groovy?

8. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Power • Advanced programming & productivity-enhancing features • Versatility • Can be used for full programs to scripts; OOP or functional style; testing; build scripts; “glue code” • Simplicity • Flat learning curve, expressive & readable code 8 Why Use Groovy?

9. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 9 How to get Groovy? • SDKMAN • http://sdkman.io • Manual Setup • Download Latest Release • http://groovy-lang.org/ • Extract Archive • Set $GROOVY_HOME • Add $GROOVY_HOME/bin to PATH

10. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 10 Demo: SDKMan

11. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • groovysh - Groovy Shell 11 Playing with Groovy

12. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • groovyConsole - Groovy Console 12 Playing with Groovy

13. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Groovy Web Console - groovyconsole.appspot.com 13 Playing with Groovy

14. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 14 From Java to Groovy

15. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 15 From Java to Groovy // PrintIndependenceDay.java 
 import java.util.Calendar;
 import java.util.Date;
 
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 Calendar calendar = Calendar.getInstance();
 calendar.clear();
 calendar.set(Calendar.MONTH, Calendar.JULY);
 calendar.set(Calendar.DATE, 4);
 calendar.set(Calendar.YEAR, 1776);
 
 Date time = calendar.getTime();
 
 System.out.println(time);
 }
 }


16. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 16 Rename file to .groovy // PrintIndependenceDay.groovy
 
 import java.util.Calendar;
 import java.util.Date;
 
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 Calendar calendar = Calendar.getInstance();
 calendar.clear();
 calendar.set(Calendar.MONTH, Calendar.JULY);
 calendar.set(Calendar.DATE, 4);
 calendar.set(Calendar.YEAR, 1776);
 
 Date time = calendar.getTime();
 
 System.out.println(time);
 }
 }


17. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 17 Remove unnecessary imports // PrintIndependenceDay.groovy
 
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 Calendar calendar = Calendar.getInstance();
 calendar.clear();
 calendar.set(Calendar.MONTH, Calendar.JULY);
 calendar.set(Calendar.DATE, 4);
 calendar.set(Calendar.YEAR, 1776);
 
 Date time = calendar.getTime();
 
 System.out.println(time);
 }
 }


18. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 18 Remove optional semicolons // PrintIndependenceDay.groovy
 
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 Calendar calendar = Calendar.getInstance()
 calendar.clear()
 calendar.set(Calendar.MONTH, Calendar.JULY)
 calendar.set(Calendar.DATE, 4)
 calendar.set(Calendar.YEAR, 1776)
 
 Date time = calendar.getTime()
 
 System.out.println(time)
 }
 }


19. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 19 Remove getter method calls // PrintIndependenceDay.groovy
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 Calendar calendar = Calendar.instance
 calendar.clear()
 calendar.set(Calendar.MONTH, Calendar.JULY)
 calendar.set(Calendar.DATE, 4)
 calendar.set(Calendar.YEAR, 1776)
 
 Date time = calendar.time
 
 System.out.println(time)
 }
 }


20. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 20 Use dynamic typing // PrintIndependenceDay.groovy
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 def calendar = Calendar.instance
 calendar.clear()
 calendar.set(Calendar.MONTH, Calendar.JULY)
 calendar.set(Calendar.DATE, 4)
 calendar.set(Calendar.YEAR, 1776)
 
 def time = calendar.time
 
 System.out.println(time)
 }
 }


21. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 21 Use Groovy println // PrintIndependenceDay.groovy
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 def calendar = Calendar.instance
 calendar.clear()
 calendar.set(Calendar.MONTH, Calendar.JULY)
 calendar.set(Calendar.DATE, 4)
 calendar.set(Calendar.YEAR, 1776)
 
 def time = calendar.time
 
 println(time)
 }
 }


22. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 22 Remove class // PrintIndependenceDay.groovy
 def calendar = Calendar.instance
 calendar.clear()
 calendar.set(Calendar.MONTH, Calendar.JULY)
 calendar.set(Calendar.DATE, 4)
 calendar.set(Calendar.YEAR, 1776) 
 def time = calendar.time 
 println(time)


23. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 23 Remove optional parantheses // PrintIndependenceDay.groovy
 def calendar = Calendar.instance
 calendar.clear()
 calendar.set Calendar.MONTH, Calendar.JULY
 calendar.set Calendar.DATE, 4
 calendar.set Calendar.YEAR, 1776
 
 def time = calendar.time
 
 println time


24. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 24 Use with method with a closure // PrintIndependenceDay.groovy
 
 def calendar = Calendar.instance
 calendar.with {
 clear()
 set MONTH, JULY
 set DATE, 4
 set YEAR, 1776
 println time
 }
 


25. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 25 Comparing Java vs Groovy // PrintIndependenceDay.groovy
 
 def calendar = Calendar.instance
 calendar.with {
 clear()
 set MONTH, JULY
 set DATE, 4
 set YEAR, 1776
 println time
 } // PrintIndependenceDay.java 
 import java.util.Calendar;
 import java.util.Date;
 
 public class PrintIndependenceDay {
 
 public static void main(String[] args) {
 Calendar calendar = Calendar.getInstance();
 calendar.clear();
 calendar.set(Calendar.MONTH, Calendar.JULY);
 calendar.set(Calendar.DATE, 4);
 calendar.set(Calendar.YEAR, 1776);
 
 Date time = calendar.getTime();
 
 System.out.println(time);
 }
 }


26. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 26 Groovy Features

27. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Semicolons are optional • Implicit return • Common packages are auto-imported • java.lang.* • java.net.* • java.util.* • java.io.* • etc... • Parentheses are optional (in some situations) • No checked exceptions 27 Syntactic Sugar

28. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Signified by double quotes • Support string interpolation • Automatically converted to java.lang.String when required • Additional methods added - e.g: take(), toURL() etc • Accessible with array-style syntax: message[0..4] • Multi-line strings denoted by triple double quotes: """ 28 Groovy Strings

29. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Classes with simple properties • All properties & methods public by default • Compiler generates getters & setters • Rarely need constructors (map constructor provided by default) • Dot access to properties (a la accessing fields) 29 Plain Old Groovy Objects (POGO)

30. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 30 Everything is an Object

31. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 31 Demo: Syntax, Strings & POGOs

32. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Groovy overloads operators symbols to call methods 32 Operators a + b a.add(b) a - b a.minus(b) a * b a.multiply(b) a / b a.div(b) a++ next() a-- a.previous() a % b a.mod(b) a ** b a.power(b) a[b] a.getAt(b) a[b] = c a.putAt(b, c) a << b a.leftShift(b) a >> b a.rightShift(b) a?.b Null-safe reference a ?: b “Elvis” operator http://groovy-lang.org/operators.html

33. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Groovy adds many useful methods to “normal” Java classes • .times() - can be called on any number, executes a closure that number of times • .with() - can be called on any object, accepts a closure, calls each unresolved method in the closure on the referenced object • .getProperties() - can be called on any object, returns a Map of all properties in the object • http://groovy-lang.org/gdk.html 33 Groovy Development Kit (GDK)

34. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 34 Demo: Operators

35. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Anonymous block of code • Can (optionally) accept arguments & (optionally) return a value • Can be passed as an argument or returned as a value • Similar to Java’s lambdas, but even more powerful • Can be assigned a delegate • Lazily evaluated • Can be used with the Java Streams API 35 Closures

36. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 36 Closures { item++ } { println it } { name -> println name } { String x, int y -> println “X: ${x} / Y: ${y}” } Defining a closure http://groovy-lang.org/closures.html def isOdd = { int i -> i%2 != 0 } assert isOdd(3) == true assert isOdd.call(2) == false Calling a closure class Person { String name } class Thing { String name } def p = new Person(name: 'Norman') def t = new Thing(name: ‘Teapot') //A closure that calls a delegate method def upperCasedName = { delegate.name.toUpperCase() } //Call closure with different delegates upperCasedName.delegate = p assert upperCasedName() == 'NORMAN' upperCasedName.delegate = t assert upperCasedName() == 'TEAPOT' Closure delegates

37. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Can be defined as literals • e.g., a List: [1, 2, 3] - a Map: [a:1, b:2, b:3] • GDK adds many useful methods to Java collections • each() - accepts a closure, executes the closure for each item in the collection • collect() - accepts a closure, maps over each item in the collection and returns the result as a new collection • find() - filters collection for matching item • findAll() - filters collection for all matching items 37 Collections

38. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 38 Collections http://docs.groovy-lang.org/latest/html/documentation/working-with-collections.html def list = [5, 6, 7, 8] assert list.get(2) == 7 assert list[2] == 7 assert list instanceof java.util.List List Literal Syntax [1, 2, 3].each { println "Item: $it” } ['a', 'b', 'c'].eachWithIndex { it, i -> println "$i: $it" } Iterating with .each def map = [name: 'DevNexus', id: 1234] assert map.get('name') == 'DevNexus' assert map.get('id') == 1234 assert map['id'] == 1234 assert map.id == 1234 assert map instanceof java.util.Map Map Literal Syntax def map = [Bob : 42, Alice: 54, Max : 33] map.each { it -> println "Name: $it.key Age: $it.value" } map.each { key, value -> println "Name: $key Age: $value" } Iterating with .each

39. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 39 Demo: Closures & Collections

40. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Compile-time meta-programming technique • Adds behavior to classes during compilation • Applied using annotations • Groovy includes many useful AST Transformations, eg: • @EqualsAndHashcode - implements default equals() and hashcode() methods for the annotated class • @Immutable - marks class as final, generates equals()/hashcode()/ toString() methods, but no getters, • You can write your own AST Transformations 40 AST Transformations

41. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 41 AST Transformations import groovy.transform.ToString @ToString class Book { String title String author } @ToString Transformation def book = new Book(title: ‘Grails: A Quick Start Guide', author: ‘Dave Klein') assert book.toString() == ‘Book(Grails: A Quick Start Guide, Dave Klein) Calling toString() import groovy.transform.EqualsAndHashCode @EqualsAndHashCode class Book { String title String author } @EqualsAndHashCode Transformation def b1 = new Book(title: ‘Groovy Recipes', author: ‘Scott Davis') def b2 = new Book(title: ‘Groovy Recipes', author: ‘Scott Davis') assert b1==b2 assert b1.hashCode() == b2.hashCode() Checking equality/hashcode http://groovy-lang.org/metaprogramming.html#_code_generation_transformations

42. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Language artifact, similar to interfaces with default methods • Allow composition of behaviors - multiple inheritance • Can have state, using public or private properties • Can declare abstract methods • Can declare private methods • Statically compiled & type-checked • Can be added to an object at runtime 42 Traits

43. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 43 Traits http://docs.groovy-lang.org/next/html/documentation/core-traits.html trait Flyer { String fly() { "I'm flying!" } } trait Speaker { String speak() { "I'm speaking!" } } Define traits class Duck implements Flyer, Speaker {} def d = new Duck() assert d.fly() == "I'm flying!" assert d.speak() == "I'm speaking!" Class that implements traits trait Named { String name } trait Polite extends Named { String introduce() { "Hello, I am $name" } } Trait inheritance trait Extra { String extra() { "I'm an extra!” } } class Something {} def s = new Something() as Extra s.extra() Assigning Traits at Runtime

44. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 44 MarkupBuilder & XmlSlurper import groovy.xml.MarkupBuilder def writer = new StringWriter() def xml = new MarkupBuilder(writer) //Create XML xml.records() { book() { title('Making Java Groovy') author('Ken Kousen') } book() { title('Programming Groovy 2') author('Venkat Subramaniam') } } //Parse XML def records = new XmlSlurper().parseText(writer.toString()) assert records.book.first().author.text() == 'Ken Kousen' assert records.book.last().title.text() == 'Programming Groovy 2' http://groovy-lang.org/processing-xml.html

45. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 45 JsonOutput & JsonSlurper class Person { String name } //Create JSON string from object def json = JsonOutput.toJson(new Person(name: 'John')) assert json == '{"name":"John"}' //Parse JSON string into Map def jsonSlurper = new JsonSlurper() def object = jsonSlurper.parseText(json) assert object instanceof Map assert object.name == 'John' http://groovy-lang.org/json.html

46. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 46 Writing & Reading Files //Writing to a file new File('names.txt').withWriter('utf-8') { writer -> writer.writeLine 'Ken Kousen' writer.writeLine 'Venkat Subramaniam' writer.writeLine 'Paul King' } //Reading file new File('names.txt').eachLine { line -> println line } http://docs.groovy-lang.org/latest/html/documentation/working-with-io.html //Print out the names of all the files in the current directory new File(‘.').eachFile { file -> println file.name }

47. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 47 Groovy Ecosystem

48. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Full-stack web framework built on top of Spring Boot • Designed to enhance developer-productivity • Provides powerful Groovy-based persistence with GORM • Leverages Groovy’s meta-programming capabilities and Traits • https://grails.org 48 Grails

49. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Full-stack web framework for building Spring- based web applications • Offers Groovy as a language option from the Spring Initializer • https://start.spring.io 49 Spring Boot

50. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Light-weight Groovy-based HTTP framework • Build for scalability & performance • Uses static compilation and type- checking features of Groovy • https://ratpack.io 50 Ratpack

51. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Java Desktop Application framework • Supports Swing, JavaFX, and more • Leverages Groovy’s SwingBuilder for creating Swing UIs with concise code • http://griffon-framework.org 51 Griffon

52. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Testing framework for JVM applications • Built on top of JUnit • Promotes expressive, behavior-focused testing • Uses a Groovy-based DSL to provide expressive testing conventions • http://spockframework.org 52 Spock

53. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Concurrency & Parallelism library for Groovy • Provides many concurrency abstractions, including Promises, Actors, Parallel Collections, and more • Leverages the flexibility of Groovy • http://www.gpars.org 53 Gpars

54. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Full-featured build tool and task runner • First-class support for Groovy projects, including a dedicated plugin • Uses a Groovy DSL for build scripting (a Kotlin DSL is also available) • https://gradle.org/ 54 Gradle

55. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Full-stack web framework designed for microservices & serverless • Uses AST transformations (in Groovy) to compute Dependency Injection & other metadatpa at compilation time • Blazing fast startup and low memory footprint • Natively cloud-native • Supports Groovy functions for AWS Lambda • https://micronaut.io 55 Micronaut String myFunction() { "hello world!" } Valid AWS Lambda function!

56. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 56 What’s Next for Groovy?

57. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Runs on JDK 9+ (but with warnings) • New AST Transformations • New GDK methods: tap() 57 What Is New In Groovy 2.5 & 2.6

58. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com • Minimum JDK 8 requirement • Improved Java 9+ support • New “Parrot” parser • Better support for modern Java code • Support for Lambdas • New operators: elvis assignment, identity, etc • Safe array-indexing - null instead of “out of bounds” • http://groovy-lang.org/releasenotes/groovy-3.0.html 58 What Is Coming in Groovy 3

59. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 59 Resources

60. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 60 Books https://mrhaki.blogspot.com/search/label/Groovy

61. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 61

62. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 62 Groovy Community Links • Open Collective: https://opencollective.com/friends-of-groovy • Groovy Slack: https://groovycommunity.com/ • Groovy Events/Conferences: http://groovy-lang.org/events.html • Groovy User Groups: http://groovy-lang.org/usergroups.html • Hubert Klein Ikkink (Mr Haki) blog: https://mrhaki.blogspot.com/ • Baeldung blog https://www.baeldung.com/tag/groovy/ • Groovy Twitter: https://twitter.com/ApacheGroovy

63. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 63 Events: ● objectcomputing.com/events Training: ● objectcomputing.com/training ● grailstraining.com ● micronauttraining.com Or email [email protected] to schedule a custom training program for your team online, on site, or in our state-of-the-art, Midwest training lab. LEARN MORE ABOUT OCI EVENTS AND TRAINING

64. © 2019, Object Computing, Inc. (OCI). All rights reserved. objectcomputing.com 64 Thank you!

Related presentations


Other presentations created by zak89s

Shields Up! Securing React Apps
10. 12. 2017
0 views

Shields Up! Securing React Apps

Grails 4: Upgrade your Game!
01. 10. 2020
0 views

Grails 4: Upgrade your Game!