Your SlideShare is downloading. ×
0
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Groovy intro for OUDL
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Groovy intro for OUDL

236

Published on

an intro to Groovy for Java programmers

an intro to Groovy for Java programmers

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
236
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • 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't stand C anymore. For example, compare error handling in C with Exceptions in Java...
  • Transcript

    • 1. Intro to Groovy J. David Beutel 2013-03-18
    • 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. 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. 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. 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. 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. 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. 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. 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. Why do I care?
    • 13. Example: Exceptions CJava
    • 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. 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. 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. Why do I care?
    • 18. Why do I care?
    • 19. Why do I care?
    • 20. How is it different?● code comparison, Java versus Groovy● hello worlds● examples from my Timesheets project
    • 21. How is it different?
    • 22. How is it different?
    • 23. How is it different?
    • 24. How is it different?
    • 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. Usage: JUnit -> Spock
    • 27. Usage: Selenium -> Geb
    • 28. Usage: Spring/Hibernate -> Grails
    • 29. For more about Groovy● groovy.codehaus.org● google, e.g., “groovy collection”● books
    • 30. Lets make beautiful code! Thanks for coming!

    ×