SlideShare a Scribd company logo
1 of 34
Intro to Groovy




 J. David Beutel

  2013-03-18
Presenter's Background
●   1991 Comp. Sci. BS from RIT
●   1996- using Java
●   2000- developing web apps in Java
●   2005- staff at UH ITS/MIS
●   2009- using Groovy
●   2010- app with Groovy/Grails/Geb/Spock
    –   in production since 2012 June
    –   LOC: 14K production, 13K test
Presentation Objectives

●   recognize and understand Groovy code
●   get interested in Groovy coding
●   (not introducing Spock/Geb/Grails yet)
Outline

●   What is Groovy?
●   Why do I care?
●   How is it different?
●   How can I use it?
What is Groovy?
●   dynamic extension of Java
    –   syntax
    –   API (GDK)
●   enables less code, more clarity
●   compiles to Java classes
●   seamless integration with Java
●   backed by SpringSource/VMware
●   good IDE support in
    –   IntelliJ IDEA (the best, IMHO)
    –   Eclipse Groovy/Grails (Spring) Tool Suite
Syntax
optional                                    literal
   ;                   String             'foo'
  ( )                  List               ['foo', 'bar']
                                                                              keyword
 public                Map                [name: 'David', age: 43]
                                                                                in
 return                Range              3..7
                                                                                as
                       regex Pattern      ~/d+/
 catch                                                                          def
                       multi-line         '''hello
 types
                       String             world'''

                 feature                                   example
       properties                   assert URL.'package'.name == 'java.net'
       Closure                      older = employees.findAll {it.age > 39}
       GString                      “$name was ${age - 1} years old last year”
       Groovy truth                 assert age
       yet another for loop         for (e in employees) {totalAge += e.age}
       named params                 e = new Employee(name: 'David', age: 43)
       multiple assignments         (first, last) = 'John Doe'.tokenize()
Syntax
         feature                                    example
default imports          java.io.*, java.lang.*, java.net.*, java.util.*
negative/range indexes   last = employees[-1]; allButLast = employees[0..-2]
dynamic properties       obj[propertyName]
dynamic methods          obj.”$methodName”(params)
meta-programming         Integer.metaClass.cos << {Math.cos(delegate)}
                         @InheritConstructors
AST transformations
                         class MyException extends Exception {}
                         assert 1 + 1 == 3
power assert                      |   |
                                  2   false
                         switch (age) {
                           case [41, 18, 32]:    yakudoshi(); break
                           case 0..17:           child(); break
power switch
                           case {it % 2}:        odd(); break
                           default:              even()
                         }
customizable operators                a+b                            a.plus(b)
Syntax
operator                                  meaning                       name
a ?: b      a?a:b                                               Elvis
a?.b        a == null ? a : a.b                                 null safe
m(*list)    m(list[0], list[1], ...)                            spread
list*.m()   [list[0].m(), list[1].m(), ...]                     spread-dot
list*.a                                                         spread-dot
            [list[0].a, list[1].a, ...]
list.a                                                          (GPath)
a.&m        reference to method m in object a as closure        method closure
a.@f        direct access to field f                            dot-at
t =~ s      Pattern.compile(s).matcher(t).find()                regex find
t ==~ s     Pattern.compile(s).matcher(t).matches()             regex match
a <=> b     a.compareTo(b) handling null                        spaceship
a == b      a.equals(b) handling null, coercion, & Comparable   equals
a.is(b)     like Java's a == b
API (GDK)
      method on Object                                       example
is(other)                        a.is(b), like Java's a == b
isCase(candidate)                for power switch and in, e.g., assert 2 in [1, 2, 3]
println(value)                   println 'hello world'
sleep(millis)                    sleep 1500
with(closure)                    employee.with {name = 'Joe'; age--}



  on Collection       returns                                  example
join(separator)     String        assert [1, 2, 3].join('|') == '1|2|3'
sort(closure)       List          youngestFirst = employees.sort {it.age}
sum()               Object        def totalAge = employees*.age.sum()
max(closure)        Object        assert ['hi', 'hello', 'hey'].max {it.length()} == 'hello'
flatten()           Collection    assert [1,[2,3],[[4]],[ ],5].flatten() == [1,2,3,4,5]
groupBy(closure) Map              assert [1,2,3,4,5].groupBy {it % 2} == [0:[2,4], 1:[1,3,5]]
API (GDK)

iterative method   returns                           example
findAll            List      older = employees.findAll {it.age > 39}
find               Object    firstOlder = employees.find {it.age > 39}
any                Boolean hasOlder = employees.any {it.age > 39}
every              Boolean noYounger = employees.every {it.age > 39}
                             def totalAge = 0
each               void
                             employees.each {totalAge += it.age}
                             employees.eachWithIndex { e, i ->
eachWithIndex      void        println “${e.name} is at index $i”
                             }
grep(classifier)   List      davids = employees*.name.grep ~/David.*/
collect            List      tripleAges = employees.collect {it.age * 3}
API (GDK)
            method on File          returns                          example
          eachFile(closure)       void          new File('somedir').eachFile {println it}
          getText()               String        pid = new File('app.pid').text.toLong()
          readLines()             List          lines = new File('grammar').readLines()
          eachLine(closure)       Object        file.eachLine {parse(it)}
                                  Object        new File('report').withWriter {out ->
          withWriter(closure)                     employees.each {it.write(out)}
                                                }


    on String           returns                                  example
split()               String[]     assert 'a b c'.split() == ['a', 'b', 'c']
tokenize(token)       List         assert '/tmp:/usr'.tokenize(':') == ['/tmp', '/usr']
normalize()           String       assert 'arnb'.normalize() == 'anb'
find(regex)           String       assert 'New York, NY 10292-0098'.find(/d{5}/) == '10292'
Why do I care?
Example: Exceptions

       C




Java
Java's journey
vers   year       feature                                         example
1.0    1996 initial release
                              HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
                              List products = (List) hibernateTemplate.execute(
                                 new HibernateCallback() {
                                    public Object doInHibernate(Session session) throws HibernateException {
              inner classes           return session.find(“FROM example.Product WHERE price > ?”,
                                                           new Integer(1000), Hibernate.INTEGER);
                                    }
                                 }
                              );
                              try {
                                 Class c = Class.forName("Foo");
                                 c.getMethod("hello").invoke(c.newInstance());

                              } catch (ClassNotFoundException e) {
1.1    1997                   }
                                 e.printStackTrace();

                              catch (InvocationTargetException e) {
                                 e.printStackTrace();
              reflection      }
                              catch (NoSuchMethodException e) {
                                 e.printStackTrace();
                              }
                              catch (InstantiationException e) {
                                 e.printStackTrace();
                              }
                              catch (IllegalAccessException e) {
                                 e.printStackTrace();
                              }

              other new API   JDBC, RMI
Java's journey
vers   year            feature                                     example
1.2    1998 Collections          List stooges = Arrays.asList(new String[] {“Larry”, “Moe”, “Curly”});

                                 Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
              dynamic proxies                             new Class[] { Foo.class }, handler);
1.3    2000
              other new API      JNDI, JPDA
              assert             assert 1 + 1 == 2

1.4    2002 regex                assert Pattern.compile("d{5}").matcher("12345").matches();

              other new API      NIO, logging, XML, XSLT, JAXP, JCE, JSSE, JAAS
              generics           List<String> stooges = Arrays.asList(new String[] {"Larry", "Moe", "Curly"});

              annotations        @Override public String toString() { return “foo”; }

              enums              enum HolidayType {UH, STATE, BANK, FEDERAL}

1.5    2004 varargs              List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

              autoboxing         List<Integer> ages = Arrays.asList(43, 35, 28);

              for each loop      for (String s : stooges) { System.out.println(s + " says "Nyuk nyuk.""); }

              static imports     import static org.apache.commons.lang.StringUtils.*;
Java's journey

vers    year           feature                                       example
                                        ScriptEngineManager factory = new ScriptEngineManager();
                                        ScriptEngine engine = factory.getEngineByName("JavaScript");
                                        try {
               scripting languages         engine.eval("print('Hello, World')");
1.6    2006                             } catch (ScriptException e) {
                                           e.printStackTrace();
                                        }

               other new API            JAX-WS (SOAP), JAXB
                                        switch(artistName) {
                                          case “Lily Allen”: return FABULOUS;
               Strings in switch          case “Elisa”:      return GREAT;
                                          default:           return MEH;
                                        }
1.7    2011    generic type inference   Map<String, List<String>> myMap = new HashMap<>();

                                        catch (IOException|SQLException ex) {
                                          logger.log(ex);
               catch multiple types       throw ex;
                                        }
Why do I care?
Why do I care?
Why do I care?
How is it different?

●   code comparison, Java versus Groovy
●   hello worlds
●   examples from my Timesheets project
How is it different?
How is it different?
How is it different?
How is it different?
How can I use it?


●   same as Java
●   scripts, e.g.
    –   groovy -e "println System.properties['user.home']"
    –   groovy -e 'println java.sql.Timestamp.valueOf("2012-11-17 06:49:33").time'
    –   web app stats polling daemon via JMX
●   JUnit -> Spock
●   Selenium -> Geb
●   Spring/Hibernate -> Grails
Usage: JUnit -> Spock
Usage: Selenium -> Geb
Usage: Spring/Hibernate -> Grails
For more about Groovy
●   groovy.codehaus.org
●   google, e.g., “groovy collection”
●   books
Let's make beautiful code!




   Thanks for coming!

More Related Content

What's hot

Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureDmytro Zaitsev
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers輝 子安
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceAlexander Gladysh
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Davide Rossi
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceSeung-Bum Lee
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso Torres
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++Haris Lye
 

What's hot (20)

ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasure
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing Experience
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
EMFPath
EMFPathEMFPath
EMFPath
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 

Similar to Groovy intro for OUDL

The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 

Similar to Groovy intro for OUDL (20)

The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Groovy
GroovyGroovy
Groovy
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 

Recently uploaded

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Recently uploaded (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

Groovy intro for OUDL

  • 1. Intro to Groovy J. David Beutel 2013-03-18
  • 2. Presenter's Background ● 1991 Comp. Sci. BS from RIT ● 1996- using Java ● 2000- developing web apps in Java ● 2005- staff at UH ITS/MIS ● 2009- using Groovy ● 2010- app with Groovy/Grails/Geb/Spock – in production since 2012 June – LOC: 14K production, 13K test
  • 3. Presentation Objectives ● recognize and understand Groovy code ● get interested in Groovy coding ● (not introducing Spock/Geb/Grails yet)
  • 4. Outline ● What is Groovy? ● Why do I care? ● How is it different? ● How can I use it?
  • 5. What is Groovy? ● dynamic extension of Java – syntax – API (GDK) ● enables less code, more clarity ● compiles to Java classes ● seamless integration with Java ● backed by SpringSource/VMware ● good IDE support in – IntelliJ IDEA (the best, IMHO) – Eclipse Groovy/Grails (Spring) Tool Suite
  • 6. Syntax optional literal ; String 'foo' ( ) List ['foo', 'bar'] keyword public Map [name: 'David', age: 43] in return Range 3..7 as regex Pattern ~/d+/ catch def multi-line '''hello types String world''' feature example properties assert URL.'package'.name == 'java.net' Closure older = employees.findAll {it.age > 39} GString “$name was ${age - 1} years old last year” Groovy truth assert age yet another for loop for (e in employees) {totalAge += e.age} named params e = new Employee(name: 'David', age: 43) multiple assignments (first, last) = 'John Doe'.tokenize()
  • 7. Syntax feature example default imports java.io.*, java.lang.*, java.net.*, java.util.* negative/range indexes last = employees[-1]; allButLast = employees[0..-2] dynamic properties obj[propertyName] dynamic methods obj.”$methodName”(params) meta-programming Integer.metaClass.cos << {Math.cos(delegate)} @InheritConstructors AST transformations class MyException extends Exception {} assert 1 + 1 == 3 power assert | | 2 false switch (age) { case [41, 18, 32]: yakudoshi(); break case 0..17: child(); break power switch case {it % 2}: odd(); break default: even() } customizable operators a+b a.plus(b)
  • 8. Syntax operator meaning name a ?: b a?a:b Elvis a?.b a == null ? a : a.b null safe m(*list) m(list[0], list[1], ...) spread list*.m() [list[0].m(), list[1].m(), ...] spread-dot list*.a spread-dot [list[0].a, list[1].a, ...] list.a (GPath) a.&m reference to method m in object a as closure method closure a.@f direct access to field f dot-at t =~ s Pattern.compile(s).matcher(t).find() regex find t ==~ s Pattern.compile(s).matcher(t).matches() regex match a <=> b a.compareTo(b) handling null spaceship a == b a.equals(b) handling null, coercion, & Comparable equals a.is(b) like Java's a == b
  • 9. API (GDK) method on Object example is(other) a.is(b), like Java's a == b isCase(candidate) for power switch and in, e.g., assert 2 in [1, 2, 3] println(value) println 'hello world' sleep(millis) sleep 1500 with(closure) employee.with {name = 'Joe'; age--} on Collection returns example join(separator) String assert [1, 2, 3].join('|') == '1|2|3' sort(closure) List youngestFirst = employees.sort {it.age} sum() Object def totalAge = employees*.age.sum() max(closure) Object assert ['hi', 'hello', 'hey'].max {it.length()} == 'hello' flatten() Collection assert [1,[2,3],[[4]],[ ],5].flatten() == [1,2,3,4,5] groupBy(closure) Map assert [1,2,3,4,5].groupBy {it % 2} == [0:[2,4], 1:[1,3,5]]
  • 10. API (GDK) iterative method returns example findAll List older = employees.findAll {it.age > 39} find Object firstOlder = employees.find {it.age > 39} any Boolean hasOlder = employees.any {it.age > 39} every Boolean noYounger = employees.every {it.age > 39} def totalAge = 0 each void employees.each {totalAge += it.age} employees.eachWithIndex { e, i -> eachWithIndex void println “${e.name} is at index $i” } grep(classifier) List davids = employees*.name.grep ~/David.*/ collect List tripleAges = employees.collect {it.age * 3}
  • 11. API (GDK) method on File returns example eachFile(closure) void new File('somedir').eachFile {println it} getText() String pid = new File('app.pid').text.toLong() readLines() List lines = new File('grammar').readLines() eachLine(closure) Object file.eachLine {parse(it)} Object new File('report').withWriter {out -> withWriter(closure) employees.each {it.write(out)} } on String returns example split() String[] assert 'a b c'.split() == ['a', 'b', 'c'] tokenize(token) List assert '/tmp:/usr'.tokenize(':') == ['/tmp', '/usr'] normalize() String assert 'arnb'.normalize() == 'anb' find(regex) String assert 'New York, NY 10292-0098'.find(/d{5}/) == '10292'
  • 12. Why do I care?
  • 14. Java's journey vers year feature example 1.0 1996 initial release HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); List products = (List) hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { inner classes return session.find(“FROM example.Product WHERE price > ?”, new Integer(1000), Hibernate.INTEGER); } } ); try { Class c = Class.forName("Foo"); c.getMethod("hello").invoke(c.newInstance()); } catch (ClassNotFoundException e) { 1.1 1997 } e.printStackTrace(); catch (InvocationTargetException e) { e.printStackTrace(); reflection } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } other new API JDBC, RMI
  • 15. Java's journey vers year feature example 1.2 1998 Collections List stooges = Arrays.asList(new String[] {“Larry”, “Moe”, “Curly”}); Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), dynamic proxies new Class[] { Foo.class }, handler); 1.3 2000 other new API JNDI, JPDA assert assert 1 + 1 == 2 1.4 2002 regex assert Pattern.compile("d{5}").matcher("12345").matches(); other new API NIO, logging, XML, XSLT, JAXP, JCE, JSSE, JAAS generics List<String> stooges = Arrays.asList(new String[] {"Larry", "Moe", "Curly"}); annotations @Override public String toString() { return “foo”; } enums enum HolidayType {UH, STATE, BANK, FEDERAL} 1.5 2004 varargs List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); autoboxing List<Integer> ages = Arrays.asList(43, 35, 28); for each loop for (String s : stooges) { System.out.println(s + " says "Nyuk nyuk.""); } static imports import static org.apache.commons.lang.StringUtils.*;
  • 16. Java's journey vers year feature example ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); try { scripting languages engine.eval("print('Hello, World')"); 1.6 2006 } catch (ScriptException e) { e.printStackTrace(); } other new API JAX-WS (SOAP), JAXB switch(artistName) { case “Lily Allen”: return FABULOUS; Strings in switch case “Elisa”: return GREAT; default: return MEH; } 1.7 2011 generic type inference Map<String, List<String>> myMap = new HashMap<>(); catch (IOException|SQLException ex) { logger.log(ex); catch multiple types throw ex; }
  • 17.
  • 18. Why do I care?
  • 19. Why do I care?
  • 20. Why do I care?
  • 21.
  • 22. How is it different? ● code comparison, Java versus Groovy ● hello worlds ● examples from my Timesheets project
  • 23. How is it different?
  • 24. How is it different?
  • 25. How is it different?
  • 26. How is it different?
  • 27.
  • 28.
  • 29. How can I use it? ● same as Java ● scripts, e.g. – groovy -e "println System.properties['user.home']" – groovy -e 'println java.sql.Timestamp.valueOf("2012-11-17 06:49:33").time' – web app stats polling daemon via JMX ● JUnit -> Spock ● Selenium -> Geb ● Spring/Hibernate -> Grails
  • 33. For more about Groovy ● groovy.codehaus.org ● google, e.g., “groovy collection” ● books
  • 34. Let's make beautiful code! Thanks for coming!

Editor's Notes

  1. My 1 st job after college was programming client/server apps in C and X Windows on Unix, for 6 years. Java was released towards the end, and I loved its exceptions, safe memory, garbage collection, and simpler API. Memory management and error handling in C took so much time programming around and debugging, while Java did it automatically or more cleanly, that I couldn&apos;t stand C anymore. For example, compare error handling in C with Exceptions in Java...