Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Intro to Groovy J. David Beutel  2013-03-18
Presenters Background●   1991 Comp. Sci. BS from RIT●   1996- using Java●   2000- developing web apps in Java●   2005- sta...
Presentation Objectives●   recognize and understand Groovy code●   get interested in Groovy coding●   (not introducing Spo...
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...
Syntaxoptional                                    literal   ;                   String             foo  ( )               ...
Syntax         feature                                    exampledefault imports          java.io.*, java.lang.*, java.net...
Syntaxoperator                                  meaning                       namea ?: b      a?a:b                       ...
API (GDK)      method on Object                                       exampleis(other)                        a.is(b), lik...
API (GDK)iterative method   returns                           examplefindAll            List      older = employees.findAl...
API (GDK)            method on File          returns                          example          eachFile(closure)       voi...
Why do I care?
Example: Exceptions       CJava
Javas journeyvers   year       feature                                         example1.0    1996 initial release         ...
Javas journeyvers   year            feature                                     example1.2    1998 Collections          Li...
Javas journeyvers    year           feature                                       example                                 ...
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 -...
Usage: JUnit -> Spock
Usage: Selenium -> Geb
Usage: Spring/Hibernate -> Grails
For more about Groovy●   groovy.codehaus.org●   google, e.g., “groovy collection”●   books
Lets make beautiful code!   Thanks for coming!
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Upcoming SlideShare
Loading in …5
×

Groovy intro for OUDL

516 views

Published on

an intro to Groovy for Java programmers

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Groovy intro for OUDL

  1. 1. Intro to Groovy J. David Beutel 2013-03-18
  2. 2. Presenters 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. 3. Presentation Objectives● recognize and understand Groovy code● get interested in Groovy coding● (not introducing Spock/Geb/Grails yet)
  4. 4. Outline● What is Groovy?● Why do I care?● How is it different?● How can I use it?
  5. 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. 6. Syntaxoptional 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. 7. Syntax feature exampledefault 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)} @InheritConstructorsAST transformations class MyException extends Exception {} assert 1 + 1 == 3power assert | | 2 false switch (age) { case [41, 18, 32]: yakudoshi(); break case 0..17: child(); breakpower switch case {it % 2}: odd(); break default: even() }customizable operators a+b a.plus(b)
  8. 8. Syntaxoperator meaning namea ?: b a?a:b Elvisa?.b a == null ? a : a.b null safem(*list) m(list[0], list[1], ...) spreadlist*.m() [list[0].m(), list[1].m(), ...] spread-dotlist*.a spread-dot [list[0].a, list[1].a, ...]list.a (GPath)a.&m reference to method m in object a as closure method closurea.@f direct access to field f dot-att =~ s Pattern.compile(s).matcher(t).find() regex findt ==~ s Pattern.compile(s).matcher(t).matches() regex matcha <=> b a.compareTo(b) handling null spaceshipa == b a.equals(b) handling null, coercion, & Comparable equalsa.is(b) like Javas a == b
  9. 9. API (GDK) method on Object exampleis(other) a.is(b), like Javas a == bisCase(candidate) for power switch and in, e.g., assert 2 in [1, 2, 3]println(value) println hello worldsleep(millis) sleep 1500with(closure) employee.with {name = Joe; age--} on Collection returns examplejoin(separator) String assert [1, 2, 3].join(|) == 1|2|3sort(closure) List youngestFirst = employees.sort {it.age}sum() Object def totalAge = employees*.age.sum()max(closure) Object assert [hi, hello, hey].max {it.length()} == helloflatten() 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. 10. API (GDK)iterative method returns examplefindAll 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 = 0each 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. 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 examplesplit() String[] assert a b c.split() == [a, b, c]tokenize(token) List assert /tmp:/usr.tokenize(:) == [/tmp, /usr]normalize() String assert arnb.normalize() == anbfind(regex) String assert New York, NY 10292-0098.find(/d{5}/) == 10292
  12. 12. Why do I care?
  13. 13. Example: Exceptions CJava
  14. 14. Javas journeyvers year feature example1.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. 15. Javas journeyvers year feature example1.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 == 21.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. 16. Javas journeyvers 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. 17. Why do I care?
  18. 18. Why do I care?
  19. 19. Why do I care?
  20. 20. How is it different?● code comparison, Java versus Groovy● hello worlds● examples from my Timesheets project
  21. 21. How is it different?
  22. 22. How is it different?
  23. 23. How is it different?
  24. 24. How is it different?
  25. 25. 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
  26. 26. Usage: JUnit -> Spock
  27. 27. Usage: Selenium -> Geb
  28. 28. Usage: Spring/Hibernate -> Grails
  29. 29. For more about Groovy● groovy.codehaus.org● google, e.g., “groovy collection”● books
  30. 30. Lets make beautiful code! Thanks for coming!

×