groovy intro for oudl
TRANSCRIPT
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/Spockin 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 Javasyntax
API (GDK)
enables less code, more clarity
compiles to Java classes
seamless integration with Java
backed by SpringSource/VMware
good IDE support inIntelliJ IDEA (the best, IMHO)
Eclipse Groovy/Grails (Spring) Tool Suite
Syntax
optional
;
( )
public
return
catch
types
literal
String'foo'
List['foo', 'bar']
Map[name: 'David', age: 43]
Range3..7
regex Pattern~/\d+/
multi-line String'''helloworld'''
keyword
in
as
def
featureexample
propertiesassert URL.'package'.name == 'java.net'
Closureolder = employees.findAll {it.age > 39}
GString$name was ${age - 1} years old last year
Groovy truthassert age
yet another for loopfor (e in employees) {totalAge += e.age}
named paramse = new Employee(name: 'David', age: 43)
multiple assignments(first, last) = 'John Doe'.tokenize()
Syntax
featureexample
default importsjava.io.*, java.lang.*, java.net.*, java.util.*
negative/range indexeslast = employees[-1]; allButLast = employees[0..-2]
dynamic propertiesobj[propertyName]
dynamic methodsobj.$methodName(params)
meta-programmingInteger.metaClass.cos 39}
findObjectfirstOlder = employees.find {it.age > 39}
anyBooleanhasOlder = employees.any {it.age > 39}
everyBooleannoYounger = employees.every {it.age > 39}
eachvoiddef totalAge = 0employees.each {totalAge += it.age}
eachWithIndexvoidemployees.eachWithIndex { e, i -> println ${e.name} is at index $i}
grep(classifier)Listdavids = employees*.name.grep ~/David.*/
collectListtripleAges = employees.collect {it.age * 3}
API (GDK)
method on Filereturnsexample
eachFile(closure)voidnew File('somedir').eachFile {println it}
getText()Stringpid = new File('app.pid').text.toLong()
readLines()Listlines = new File('grammar').readLines()
eachLine(closure)Objectfile.eachLine {parse(it)}
withWriter(closure)Objectnew File('report').withWriter {out -> employees.each {it.write(out)}}
on Stringreturnsexample
split()String[]assert 'a b c'.split() == ['a', 'b', 'c']
tokenize(token)Listassert '/tmp:/usr'.tokenize(':') == ['/tmp', '/usr']
normalize()Stringassert 'a\r\nb'.normalize() == 'a\nb'
find(regex)Stringassert 'New York, NY 10292-0098'.find(/\d{5}/) == '10292'
Why do I care?
My 1st 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...
Example: Exceptions
C
Java
Java's journey
versyearfeatureexample
1.01996initial release1.11997inner classesHibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);List products = (List) hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { return session.find(FROM example.Product WHERE price > ?, new Integer(1000), Hibernate.INTEGER); } });
reflectiontry { Class c = Class.forName("Foo"); c.getMethod("hello").invoke(c.newInstance());
} catch (ClassNotFoundException e) { e.printStackTrace();}catch (InvocationTargetException e) { e.printStackTrace();}catch (NoSuchMethodException e) { e.printStackTrace();}catch (InstantiationException e) { e.printStackTrace();}catch (IllegalAccessException e) { e.printStackTrace();}
other new APIJDBC, RMI
Java's journey
versyearfeatureexample
1.21998CollectionsList stooges = Arrays.asList(new String[] {Larry, Moe, Curly});
1.32000dynamic proxiesFoo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler);
other new APIJNDI, JPDA
1.42002assertassert 1 + 1 == 2
regexassert Pattern.compile("\\d{5}").matcher("12345").matches();
other new APINIO, logging, XML, XSLT, JAXP, JCE, JSSE, JAAS
1.52004genericsList stooges = Arrays.asList(new String[] {"Larry", "Moe", "Curly"});
annotations@Override public String toString() { return foo; }
enumsenum HolidayType {UH, STATE, BANK, FEDERAL}
varargsList stooges = Arrays.asList("Larry", "Moe", "Curly");
autoboxingList ages = Arrays.asList(43, 35, 28);
for each loopfor (String s : stooges) { System.out.println(s + " says \"Nyuk nyuk.\""); }
static importsimport static org.apache.commons.lang.StringUtils.*;
Java's journey
versyearfeatureexample
1.62006scripting languagesScriptEngineManager factory = new ScriptEngineManager();ScriptEngine engine = factory.getEngineByName("JavaScript");try { engine.eval("print('Hello, World')");} catch (ScriptException e) { e.printStackTrace();}
other new APIJAX-WS (SOAP), JAXB
1.72011Strings in switchswitch(artistName) { case Lily Allen: return FABULOUS; case Elisa: return GREAT; default: return MEH;}
generic type inferenceMap myMap = new HashMap();
catch multiple typescatch (IOException|SQLException ex) { logger.log(ex); 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!