SlideShare a Scribd company logo
for                      Developers
                          by  Leonard  Axelsson  (@xlson)




                                                                1

Thursday, June 17, 2010
SweGUG

                          Leonard Axelsson
        • Groovy user since 2006
        • Co-Founder of SweGUG
              –Swedish Groovy User Group
        • Speaker at GTUG, Agical Geeknight, JFokus,
          SweGUG
        • Developer/Consultant at Qbranch Stockholm




                                                       2

Thursday, June 17, 2010
SweGUG

                           Agenda
        • Overview and obligatory Hello World
        • Syntax Overview
        • Tips and Trix




                                                3

Thursday, June 17, 2010
SweGUG

                          Groovy Overview
        • Originated in 2003
        • Under the Apache License
        • Grammar derived from Java 1.5




                                            4

Thursday, June 17, 2010
SweGUG

                          Groovy Overview
        • Dynamic language
              –Inspired by Python, Ruby and Smalltalk
        • Object Oriented
        • Easy to learn for Java devs
              –Supports Java style code out of the box
        • Scriptable
        • Embeddable


                                                         5

Thursday, June 17, 2010
SweGUG

                                   Dynamic Language
        • No compile-time checking
              – int i = “Hello”                  throws exception at runtime
        • Ducktyping
              – def keyword allows you to care about what the object
                 does, not what it is
        • Supports custom DSLs
        new  DateDSL().last.day.in.december(  2009  )




                                                                               6

Thursday, June 17, 2010
SweGUG

                                  Gotchas
        • == uses equals()
              –not object identity
              –is() used for identity comparission
        • return keyword is optional
        • Methods and classes are public by default
        • All exceptions are unchecked exceptions
        • There are no primitives


                                                      7

Thursday, June 17, 2010
SweGUG




                          The obligatory Hello World




                                                       8

Thursday, June 17, 2010
SweGUG




             How many in here know Groovy?




                                             9

Thursday, June 17, 2010
SweGUG




                  Groovy can be coded the “Java”
                    way. So basically all of you!




                                                    10

Thursday, June 17, 2010
SweGUG

                                 HelloWorld.java

        class HelloWorld {
            public static void main(String[] args) {
                System.out.println("Hello World!");
            }
        }




                                                       11

Thursday, June 17, 2010
SweGUG

                             HelloWorld.groovy

        class HelloWorld {
            public static void main(String[] args) {
                System.out.println("Hello World!");
            }
        }




                                                       12

Thursday, June 17, 2010
SweGUG

                                      Removing ...

        class HelloWorld {
            public static void main(String[] args) {
                System.out.println("Hello World!");
            }
        }




                                                       13

Thursday, June 17, 2010
SweGUG

                                      Removing ...

        class HelloWorld {
            public static void main(String[] args) {
                System.out.println("Hello World!")
            }
        }




                                                       14

Thursday, June 17, 2010
SweGUG

                                      Removing ...

        class HelloWorld {
            public static void main(String[] args) {
                println("Hello World!")
            }
        }




                                                       15

Thursday, June 17, 2010
SweGUG

                                  Removing ...

        println("Hello World!")




                                                 16

Thursday, June 17, 2010
SweGUG

                                 This is it

        println "Hello World!"




                                              17

Thursday, June 17, 2010
SweGUG

                          Feature Overview
        • Properties
              –dynamic getters and setters
        • Closures
              –reusable blocks of code
        • Meta Object Protocol
              –rewrite behaviour at runtime
        • Many additions to the JDK



                                              18

Thursday, June 17, 2010
SweGUG

                          Default imports
        • java.io.*
        • java.lang.*
        • java.math.BigDecimal
        • java.math.BigInteger
        • java.net.*
        • java.util.*
        • groovy.lang.*
        • groovy.util.*

                                            19

Thursday, June 17, 2010
SweGUG




                          Strings




                                    20

Thursday, June 17, 2010
SweGUG

                                 Remember this?

        println "Hello World!"




                                                  21

Thursday, June 17, 2010
SweGUG

                          Let’s add something ...
        • Macros supported in double-quoted strings
        String whome = "World!"

        println "Hello $whome"




        Output:
        Hello World!




                                                      22

Thursday, June 17, 2010
SweGUG




                          Plain Old Groovy Objects




                                                     23

Thursday, June 17, 2010
SweGUG

                                           POGO’s
        • Properties
              –getters and setters are created automatically
        • Named Parameters
              –clarifies intent
        class Person {
            String name
            String lastname
        }

        def anders = new Person(name: 'Anders', lastname: 'Andersson')
        assert anders.getName() == 'Anders'

        // Anders gets married and changes his lastname
        anders.setLastname("Sundstedt")
        assert anders.lastname == "Sundstedt"




                                                                         24

Thursday, June 17, 2010
SweGUG

                                             POGO’s
        • Getters and setters can be overridden
        class Person {
            def name
            def lastname

              String setLastname(String lastname) {
                  this.lastname = lastname.reverse()
              }
        }

        def anders = new Person(name: 'Anders', lastname: 'Andersson')

        // Anders does a strange change of his lastname
        anders.lastname = "Sundstedt"
        assert anders.lastname == "tdetsdnuS"




                                                                         25

Thursday, June 17, 2010
SweGUG




                 Built in syntax for lists and maps




                                                      26

Thursday, June 17, 2010
SweGUG

                                                Lists
        List  syntax:
        def names = ['Leonard', 'Anna', 'Anders']
        assert names instanceof List
        assert names.size() == 3
        assert names[0] == 'Leonard'




                                                        27

Thursday, June 17, 2010
SweGUG

                                                 Maps

        def map = [name: 'Leonard',
                   lastname: 'Axelsson']
        assert map.name == 'Leonard'
        assert map['lastname'] == 'Axelsson'

        map.each{ key, value ->
            println "Key: $key, Value: $value"
        }

        Output:
        Key: name, Value: Leonard
        Key: lastname, Value: Axelsson




                                                        28

Thursday, June 17, 2010
SweGUG

                              each, find and findAll

        class Person {
            String name
            String lastname
            boolean male
        }

        def ages = [new Person(name: 'Bo', lastname: 'Olsson', male: true),
                    new Person(name: 'Gunn', lastname: 'Bertilsson', male: false),
                    new Person(name: 'Britt', lastname: 'Olsson', male: false)]
        // Print all names
        ages.each { println "$it.name $it.lastname" }

        // Find one male
        assert ages.find{ person -> person.male }.name == 'Bo'

        // or find all females
        assert ages.findAll{ Person p -> !p.male }.size() == 2




                                                                                     29

Thursday, June 17, 2010
SweGUG

                                               Power Asserts
        • New in Groovy 1.7
        // Will throw an assertion error
        def getNum() { 5 }
        assert (1 + 100) == num + 77

        Output:
        Assertion failed:

        assert (1 + 100) == num + 77
                  |      |  |   |
                  101    |  5   82
                         false

        	     at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(InvokerHelper.java:378)
        	     at ...




                                                                                                  30

Thursday, June 17, 2010
SweGUG

                                      Method not found?
        • Better feedback in Groovy 1.7
        // Will throw a MissingMethodException (no beginsWith method)
        def carType = "BMW M3"
        if(carType.beginsWith('Volvo')) {
            println "It's a Volvo!"
        }

        Output:
        groovy.lang.MissingMethodException: No signature of method: java.lang.String.beginsWith() is applicable for argument types:
        (java.lang.String) values: [Volvo]
        Possible solutions: endsWith(java.lang.String), startsWith(java.lang.String)
        	    at ...




                                                                                                                                      31

Thursday, June 17, 2010
SweGUG

                          @Grab and grape
        • Dependency management using Apache Ivy
              –Uses Maven Central
        • grape commandline tool
              –Adds dependencies to Groovys global classpath
        • @Grab annotation
              –Great for scripting




                                                               32

Thursday, June 17, 2010
SweGUG

                                     @Grab and GPars
        @Grab(group='org.codehaus.gpars', module='gpars', version='0.10')
        import groovyx.gpars.GParsExecutorsPool

        def importProcessingData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ,18, 19, 20]

        time('Parallel execution') {
            GParsExecutorsPool.withPool {
                importProcessingData.eachParallel { data ->
                    // Insert arbitrary heavy operation here
                    sleep 200
                }

             }
        }

        time('Linear execution') {
            importProcessingData.each {
                // Insert arbitrary heavy operation here
                sleep 200
            }
        }
        Output  (executed  on  dual-­‐core  machine):
        Parallel execution desc, 1449 ms.{
        def time(String took: task)
        Linear execution took: 4006 Date().time
             def startTime = new ms.
             def result = task()
             def executionTime = new Date().time - startTime
             println "$desc took: $executionTime ms."
             result
        }

                                                                                                             33

Thursday, June 17, 2010
SweGUG

                                    Links
        • Groovy
              –http://groovy.codehaus.org/
        • Groovy Goodness (great tips and trix)
              –http://mrhaki.blogspot.com/
        • SweGUG
              –http://groups.google.com/group/swegug




                                                       34

Thursday, June 17, 2010

More Related Content

Viewers also liked

peoples' chjoice
peoples' chjoicepeoples' chjoice
peoples' chjoicechuckbowers
 
Supply Chain Partners
Supply Chain PartnersSupply Chain Partners
Supply Chain Partners
JonGrigg
 
Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...
Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...
Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...
Giuseppe Benevento
 
Peoples Choice Ultimate
Peoples Choice UltimatePeoples Choice Ultimate
Peoples Choice Ultimate
chuckbowers
 
Planning System
Planning SystemPlanning System
Planning SystemJonGrigg
 
Language Teaching and learning in the Web 2.0 Environment
Language Teaching and learning in the Web 2.0 EnvironmentLanguage Teaching and learning in the Web 2.0 Environment
Language Teaching and learning in the Web 2.0 EnvironmentYuka Matsuhashi
 

Viewers also liked (7)

peoples' chjoice
peoples' chjoicepeoples' chjoice
peoples' chjoice
 
Supply Chain Partners
Supply Chain PartnersSupply Chain Partners
Supply Chain Partners
 
Heart Attack13 6
Heart Attack13 6Heart Attack13 6
Heart Attack13 6
 
Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...
Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...
Presentazione ubiquitous computing - Scrittura e tecnologia - 10 dicembre 201...
 
Peoples Choice Ultimate
Peoples Choice UltimatePeoples Choice Ultimate
Peoples Choice Ultimate
 
Planning System
Planning SystemPlanning System
Planning System
 
Language Teaching and learning in the Web 2.0 Environment
Language Teaching and learning in the Web 2.0 EnvironmentLanguage Teaching and learning in the Web 2.0 Environment
Language Teaching and learning in the Web 2.0 Environment
 

Similar to Groovy Introduction at Javaforum 2010

Základy GWT
Základy GWTZáklady GWT
Základy GWT
Tomáš Holas
 
Groovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume Laforge
Groovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume LaforgeGroovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume Laforge
Groovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume LaforgeGuillaume Laforge
 
Migrating existing Projects to Wonder
Migrating existing Projects to WonderMigrating existing Projects to Wonder
Migrating existing Projects to WonderWO Community
 
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Guillaume Laforge
 
Node.js - JavaScript Chicago Meetup
Node.js - JavaScript Chicago MeetupNode.js - JavaScript Chicago Meetup
Node.js - JavaScript Chicago Meetup
hugs
 
Unobtrusive CSS
Unobtrusive CSSUnobtrusive CSS
Unobtrusive CSS
John Hwang
 
Groovyの紹介20110820
Groovyの紹介20110820Groovyの紹介20110820
Groovyの紹介20110820
Yasuharu Hayami
 
Jython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank WierzbickiJython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank Wierzbicki
fwierzbicki
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
Andres Almiray
 
Adopt OpenJDK presentation (slide deck)
Adopt OpenJDK presentation (slide deck)Adopt OpenJDK presentation (slide deck)
Adopt OpenJDK presentation (slide deck)
Mani Sarkar
 
Groovy MOPping
Groovy MOPpingGroovy MOPping
Groovy MOPping
Izzet Mustafaiev
 
Getting your Grails on
Getting your Grails onGetting your Grails on
Getting your Grails on
Tom Henricksen
 
Groovy Metaprogramming for Dummies
Groovy Metaprogramming for DummiesGroovy Metaprogramming for Dummies
Groovy Metaprogramming for Dummies
Darren Cruse
 

Similar to Groovy Introduction at Javaforum 2010 (16)

Základy GWT
Základy GWTZáklady GWT
Základy GWT
 
Groovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume Laforge
Groovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume LaforgeGroovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume Laforge
Groovy to infinity and beyond - SpringOne2GX - 2010 - Guillaume Laforge
 
Migrating existing Projects to Wonder
Migrating existing Projects to WonderMigrating existing Projects to Wonder
Migrating existing Projects to Wonder
 
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010
 
Node.js - JavaScript Chicago Meetup
Node.js - JavaScript Chicago MeetupNode.js - JavaScript Chicago Meetup
Node.js - JavaScript Chicago Meetup
 
Rejectkaigi 2010
Rejectkaigi 2010Rejectkaigi 2010
Rejectkaigi 2010
 
Tomas Grails
Tomas GrailsTomas Grails
Tomas Grails
 
Unobtrusive CSS
Unobtrusive CSSUnobtrusive CSS
Unobtrusive CSS
 
Is these a bug
Is these a bugIs these a bug
Is these a bug
 
Groovyの紹介20110820
Groovyの紹介20110820Groovyの紹介20110820
Groovyの紹介20110820
 
Jython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank WierzbickiJython 2.7 and techniques for integrating with Java - Frank Wierzbicki
Jython 2.7 and techniques for integrating with Java - Frank Wierzbicki
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Adopt OpenJDK presentation (slide deck)
Adopt OpenJDK presentation (slide deck)Adopt OpenJDK presentation (slide deck)
Adopt OpenJDK presentation (slide deck)
 
Groovy MOPping
Groovy MOPpingGroovy MOPping
Groovy MOPping
 
Getting your Grails on
Getting your Grails onGetting your Grails on
Getting your Grails on
 
Groovy Metaprogramming for Dummies
Groovy Metaprogramming for DummiesGroovy Metaprogramming for Dummies
Groovy Metaprogramming for Dummies
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 

Groovy Introduction at Javaforum 2010

  • 1. for Developers by  Leonard  Axelsson  (@xlson) 1 Thursday, June 17, 2010
  • 2. SweGUG Leonard Axelsson • Groovy user since 2006 • Co-Founder of SweGUG –Swedish Groovy User Group • Speaker at GTUG, Agical Geeknight, JFokus, SweGUG • Developer/Consultant at Qbranch Stockholm 2 Thursday, June 17, 2010
  • 3. SweGUG Agenda • Overview and obligatory Hello World • Syntax Overview • Tips and Trix 3 Thursday, June 17, 2010
  • 4. SweGUG Groovy Overview • Originated in 2003 • Under the Apache License • Grammar derived from Java 1.5 4 Thursday, June 17, 2010
  • 5. SweGUG Groovy Overview • Dynamic language –Inspired by Python, Ruby and Smalltalk • Object Oriented • Easy to learn for Java devs –Supports Java style code out of the box • Scriptable • Embeddable 5 Thursday, June 17, 2010
  • 6. SweGUG Dynamic Language • No compile-time checking – int i = “Hello” throws exception at runtime • Ducktyping – def keyword allows you to care about what the object does, not what it is • Supports custom DSLs new  DateDSL().last.day.in.december(  2009  ) 6 Thursday, June 17, 2010
  • 7. SweGUG Gotchas • == uses equals() –not object identity –is() used for identity comparission • return keyword is optional • Methods and classes are public by default • All exceptions are unchecked exceptions • There are no primitives 7 Thursday, June 17, 2010
  • 8. SweGUG The obligatory Hello World 8 Thursday, June 17, 2010
  • 9. SweGUG How many in here know Groovy? 9 Thursday, June 17, 2010
  • 10. SweGUG Groovy can be coded the “Java” way. So basically all of you! 10 Thursday, June 17, 2010
  • 11. SweGUG HelloWorld.java class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } 11 Thursday, June 17, 2010
  • 12. SweGUG HelloWorld.groovy class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } 12 Thursday, June 17, 2010
  • 13. SweGUG Removing ... class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } 13 Thursday, June 17, 2010
  • 14. SweGUG Removing ... class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!") } } 14 Thursday, June 17, 2010
  • 15. SweGUG Removing ... class HelloWorld { public static void main(String[] args) { println("Hello World!") } } 15 Thursday, June 17, 2010
  • 16. SweGUG Removing ... println("Hello World!") 16 Thursday, June 17, 2010
  • 17. SweGUG This is it println "Hello World!" 17 Thursday, June 17, 2010
  • 18. SweGUG Feature Overview • Properties –dynamic getters and setters • Closures –reusable blocks of code • Meta Object Protocol –rewrite behaviour at runtime • Many additions to the JDK 18 Thursday, June 17, 2010
  • 19. SweGUG Default imports • java.io.* • java.lang.* • java.math.BigDecimal • java.math.BigInteger • java.net.* • java.util.* • groovy.lang.* • groovy.util.* 19 Thursday, June 17, 2010
  • 20. SweGUG Strings 20 Thursday, June 17, 2010
  • 21. SweGUG Remember this? println "Hello World!" 21 Thursday, June 17, 2010
  • 22. SweGUG Let’s add something ... • Macros supported in double-quoted strings String whome = "World!" println "Hello $whome" Output: Hello World! 22 Thursday, June 17, 2010
  • 23. SweGUG Plain Old Groovy Objects 23 Thursday, June 17, 2010
  • 24. SweGUG POGO’s • Properties –getters and setters are created automatically • Named Parameters –clarifies intent class Person { String name String lastname } def anders = new Person(name: 'Anders', lastname: 'Andersson') assert anders.getName() == 'Anders' // Anders gets married and changes his lastname anders.setLastname("Sundstedt") assert anders.lastname == "Sundstedt" 24 Thursday, June 17, 2010
  • 25. SweGUG POGO’s • Getters and setters can be overridden class Person { def name def lastname String setLastname(String lastname) { this.lastname = lastname.reverse() } } def anders = new Person(name: 'Anders', lastname: 'Andersson') // Anders does a strange change of his lastname anders.lastname = "Sundstedt" assert anders.lastname == "tdetsdnuS" 25 Thursday, June 17, 2010
  • 26. SweGUG Built in syntax for lists and maps 26 Thursday, June 17, 2010
  • 27. SweGUG Lists List  syntax: def names = ['Leonard', 'Anna', 'Anders'] assert names instanceof List assert names.size() == 3 assert names[0] == 'Leonard' 27 Thursday, June 17, 2010
  • 28. SweGUG Maps def map = [name: 'Leonard', lastname: 'Axelsson'] assert map.name == 'Leonard' assert map['lastname'] == 'Axelsson' map.each{ key, value -> println "Key: $key, Value: $value" } Output: Key: name, Value: Leonard Key: lastname, Value: Axelsson 28 Thursday, June 17, 2010
  • 29. SweGUG each, find and findAll class Person { String name String lastname boolean male } def ages = [new Person(name: 'Bo', lastname: 'Olsson', male: true), new Person(name: 'Gunn', lastname: 'Bertilsson', male: false), new Person(name: 'Britt', lastname: 'Olsson', male: false)] // Print all names ages.each { println "$it.name $it.lastname" } // Find one male assert ages.find{ person -> person.male }.name == 'Bo' // or find all females assert ages.findAll{ Person p -> !p.male }.size() == 2 29 Thursday, June 17, 2010
  • 30. SweGUG Power Asserts • New in Groovy 1.7 // Will throw an assertion error def getNum() { 5 } assert (1 + 100) == num + 77 Output: Assertion failed: assert (1 + 100) == num + 77           |      |  |   |           101    |  5   82                  false at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(InvokerHelper.java:378) at ... 30 Thursday, June 17, 2010
  • 31. SweGUG Method not found? • Better feedback in Groovy 1.7 // Will throw a MissingMethodException (no beginsWith method) def carType = "BMW M3" if(carType.beginsWith('Volvo')) { println "It's a Volvo!" } Output: groovy.lang.MissingMethodException: No signature of method: java.lang.String.beginsWith() is applicable for argument types: (java.lang.String) values: [Volvo] Possible solutions: endsWith(java.lang.String), startsWith(java.lang.String) at ... 31 Thursday, June 17, 2010
  • 32. SweGUG @Grab and grape • Dependency management using Apache Ivy –Uses Maven Central • grape commandline tool –Adds dependencies to Groovys global classpath • @Grab annotation –Great for scripting 32 Thursday, June 17, 2010
  • 33. SweGUG @Grab and GPars @Grab(group='org.codehaus.gpars', module='gpars', version='0.10') import groovyx.gpars.GParsExecutorsPool def importProcessingData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ,18, 19, 20] time('Parallel execution') { GParsExecutorsPool.withPool { importProcessingData.eachParallel { data -> // Insert arbitrary heavy operation here sleep 200 } } } time('Linear execution') { importProcessingData.each { // Insert arbitrary heavy operation here sleep 200 } } Output  (executed  on  dual-­‐core  machine): Parallel execution desc, 1449 ms.{ def time(String took: task) Linear execution took: 4006 Date().time def startTime = new ms. def result = task() def executionTime = new Date().time - startTime println "$desc took: $executionTime ms." result } 33 Thursday, June 17, 2010
  • 34. SweGUG Links • Groovy –http://groovy.codehaus.org/ • Groovy Goodness (great tips and trix) –http://mrhaki.blogspot.com/ • SweGUG –http://groups.google.com/group/swegug 34 Thursday, June 17, 2010