2. Groovy Goals
• Learn what Groovy can do for you
• Start using it today!
2
6/22/2005
3. Rod Cope
• Founder and CTO of OpenLogic
– rod.cope@openlogic.com
• 9+ years Java experience
– Sun Certified Java Architect
– J2SE, J2EE, J2ME, Swing, Security, Open Source, etc.
– GE, IBM, Ericsson, Manugistics, Digital Thoughts, etc.
• Groovy Lover
– Started November 2003
– 7,000+ lines of Groovy in production (small apps)
– Groovy Presentations
• No Fluff Just Stuff Series
• JavaOne
• O'Reilly Open Source Convention
3
6/22/2005
4. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
4
6/22/2005
5. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
5
6/22/2005
6. Sample: Java and Groovy!
public class Filter {
public static void main( String[] args ) {
List list = new ArrayList();
list.add( quot;Rodquot; ); list.add( quot;Neetaquot; );
list.add( quot;Ericquot; ); list.add( quot;Missyquot; );
Filter filter = new Filter();
List shorts = filter.filterLongerThan( list, 4 );
System.out.println( shorts.size() );
Iterator iter = shorts.iterator();
while ( iter.hasNext() ) {
System.out.println( iter.next() );
}
}
public List filterLongerThan( List list, int length ) {
List result = new ArrayList();
Iterator iter = list.iterator();
while ( iter.hasNext() ) {
String item = (String) iter.next();
if ( item.length() <= length ) { result.add( item ); }
}
return result;
}
}
6
6/22/2005
7. Sample: Groovy!
def list = [quot;Rodquot;, quot;Neetaquot;, quot;Ericquot;, quot;Missyquot;]
def shorts = list.findAll { it.size() <= 4 }
println shorts.size()
shorts.each { println it }
groovy> 2
groovy> Rod
Eric
7
6/22/2005
8. Sample in Java (27 lines)
public class Filter {
public static void main( String[] args ) {
List list = new ArrayList();
list.add( quot;Rodquot; ); list.add( quot;Neetaquot; );
list.add( quot;Ericquot; ); list.add( quot;Missyquot; );
Filter filter = new Filter();
List shorts = filter.filterLongerThan( list, 4 );
System.out.println( shorts.size() );
Iterator iter = shorts.iterator();
while ( iter.hasNext() ) {
System.out.println( iter.next() );
}
}
public List filterLongerThan( List list, int length ) {
List result = new ArrayList();
Iterator iter = list.iterator();
while ( iter.hasNext() ) {
String item = (String) iter.next();
if ( item.length() <= length ) { result.add( item ); }
}
return result;
}
}
8
6/22/2005
10. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
10
6/22/2005
11. Java Platform Strengths
• Lots of reusable software, components, tools
• VM and Binary Compatibility
– Build deployment units (class, jar, jnlp, war, ear, sar, etc.)
and run them anywhere
– Easily reuse libraries and tools
• Allows for innovation at the source code level
11
6/22/2005
12. Components vs. Scripting
• We reuse far more code than we write
• We spend more time gluing components than writing them
• We write more tests than real code
• The web tier is a perfect example
– Render business objects as markup (templating / scripting)
– Glue actions with requests and domain models (MVC)
– Most of web tier is duct tape with pockets of business logic
• Scripting is a great way to glue components
together
12
6/22/2005
13. Why Another Agile Language?
• Want complete binary compatibility with Java
– No difference from Java at JVM / bytecode level
– No wrappers or separate islands of APIs
• Java-friendly syntax
– Don't want something totally foreign to Java developers
• Want a scripting language designed:
– for the Java Platform
– by Java developers
– for Java developers
13
6/22/2005
14. Groovy
• Who/When
– James Strachan, Bob McWhirter – August 2003
• What
– Dynamic, object-oriented scripting language for JVM
– Features of Ruby, Python, and Smalltalk
• Why
– J/Python, J/Ruby, BeanShell, etc. all lacking
• How
– Initially, hand-written compiler and bytecode generator
– Now uses ANTLR and ASM
14
6/22/2005
15. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
15
6/22/2005
16. Groovy Features
• Dynamic and Static Typing
def str = quot;Helloquot;
int a = 2
• Native syntax for lists, maps, arrays, beans, etc.
def list = [quot;Rodquot;, 3, new Date()]
def myMap = [quot;Neetaquot;:31, quot;Ericquot;:34]
• Closures
myMap.each(
{ name, age -> println quot;$name is $age years oldquot; } )
groovy> Eric is 34 years old
groovy> Neeta is 31 years old
16
6/22/2005
17. Groovy Features (cont.)
• Regex built-in
if ( quot;namequot; ==~ quot;na.*quot; ) { println quot;match!quot; }
groovy> match!
• Operator overloading
def list = [1, 2, 3] + [4, 5, 6]
list.flatten().each { print it }
groovy> 123456
• Autoboxing and polymorphism across collection,
array, map, bean, String, iterators, etc.
String[] array = ['cat', 'dog', 'mouse']
def str = 'hello'
println quot;${array.size()},${str.size()},${list.size()}quot;
groovy> 3,5,6
17
6/22/2005
18. Groovy JDK
• Groovy-er JDK: adds convenient methods to JDK
• String
– contains(), count(), execute(), padLeft(), center(),
padRight(), reverse(), tokenize(), each(), etc.
• Collection
– count(), collect(), join(), each(), reverseEach(),
find/All(), min(), max(), inject(), sort(), etc.
• File
– eachFile(), eachLine(), withPrintWriter(), write(),
getText(), etc.
• Lots there and growing all the time
• You can add methods programmatically
18
6/22/2005
19. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
19
6/22/2005
20. Working with Java
• Create Adder.java
package com.openlogic.test;
public interface Adder
{
public int add( int a, int b );
}
• Create GAdder.groovy
package com.openlogic.test
class GAdder implements Adder
{
public int add( int a, int b )
{
return a + b
}
}
20
6/22/2005
21. Working with Java (cont.)
• Compile the Java code
javac -d target Adder.java
• Compile the Groovy code
groovyc --classpath target GAdder.groovy
• Use the Groovy code inside Java with the
interface
Adder adder = new com.openlogic.test.GAdder();
int answer = adder.add( 1, 2 );
System.out.println( quot;Answer = quot; + answer );
groovy> Answer = 3
21
6/22/2005
22. Working with Ant
• BSF-compliant
<script language=quot;groovyquot;>println 'hi' * 2</script>
• Groovy task
<taskdef name=quot;groovyquot;
classname=quot;org.codehaus.groovy.ant.Groovyquot;
classpath=quot;groovy-all-1.0-jsr-2.jarquot;/>
<groovy>
def x = 2
for ( count in 1..x ) {
ant.echo( quot;hello world ($count)quot; )
}
ant.jar( destfile: quot;c:/stuff.jarquot;, basedir: quot;.quot; )
</groovy>
22
6/22/2005
23. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
23
6/22/2005
24. Groovy Markup
• Native support for hierarchical structures in
code
– XML
– XHTML
– Ant
– Swing
– SWT
• Relatively easy to add your own
24
6/22/2005
26. Groovy Markup: XML (cont.)
data = ['Rod': ['Misha':9, 'Bowie':3],
'Eric': ['Poe':5, 'Doc':4] ]
xml = new groovy.xml.MarkupBuilder()
doc = xml.people() {
for ( entry in data ) {
person( name: entry.key ) {
for ( dog in entry.value ) {
pet( name:dog.key, age:dog.value )
}
}
}
}
26
6/22/2005
27. Groovy Markup: XML Parsing
xml = quot;quot;quot;<people>
<person name=quot;Rodquot;>
<pet name=quot;Mishaquot; age=quot;9quot;/>
<pet name=quot;Bowiequot; age=quot;3quot;/>
</person>
<person name=quot;Ericquot;>
<pet name=quot;Poequot; age=quot;5quot;/>
<pet name=quot;Docquot; age=quot;4quot;/>
</person></people>quot;quot;quot;
people = new groovy.util.XmlParser().parseText( xml )
println people.person.pet['@name']
groovy> ['Misha','Bowie','Poe','Doc']
27
6/22/2005
28. XML: Transformation
• Advanced XML Generation
– StreamingMarkupBuilder in sandbox generates HTML
and complex XML - used to generate GDK javadoc
• Groovy as Human-Readable XSLT
– Use XML parsing and navigation (findAll, every, any, etc.) to
locate data
– Use MarkupBuilder, StreamingMarkupBuilder, etc. to
render new format
– Example in groovy.util.NavToWiki.groovy -
transforms XDoc to Wiki
28
6/22/2005
32. Groovy SQL
sql = new groovy.sql.Sql( dataSource )
sql.execute( quot;create table person
( name varchar, age integer)quot; )
people = sql.dataSet( quot;personquot; )
people.add( name: quot;Rodquot;, age: 34 )
people.add( name: quot;Neetaquot;, age: 31 )
sql.eachRow( quot;select * from personquot; ) { p ->
println quot;$p.name is $p.age years oldquot;
}
groovy> Rod is 34 years old
groovy> Neeta is 31 years old
32
6/22/2005
33. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
33
6/22/2005
34. Extras
• Processes: quot;cmd /c dirquot;.execute().text
• Threading: Thread.start { any code }
• Testing: GroovyTestCase, GroovyMock
• SWT: Full support for SWT building, like SwingBuilder
• Groovy Pages/Template Engine: GSP, Groovlets, etc.
• Thicky: Groovy-based fat client delivery via GSP
• Unix Scripting: Groovy API for pipe, cat, grep, etc.
• Eclipse, IntelliJ, JEdit: Groovy plug-ins available
• Native Compiler for Linux/Intel: Very early – maybe
dead
• JMX: Small sample available
• ActiveX Proxy: Control over MS Windows (IE, Excel,
etc.)
34
6/22/2005
35. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
35
6/22/2005
36. Demo: XML-RPC
• XML-based Communication (like SOAP)
• Server and Client side support
• Separate Module in Groovy (not in core)
36
6/22/2005
37. XML-RPC
– import groovy.net.xmlrpc.*
– Server
server = new XMLRPCServer()
server.testme = { | name | name + quot; is cool!quot; }
server.multiply = { | number | number * 10 }
serverSocket = new java.net.ServerSocket( 9047 )
server.startServer( serverSocket )
– Client
serverProxy=new XMLRPCServerProxy(quot;http://127.0.0.1:9047quot;)
println serverProxy.testme( quot;Groovyquot; )
-> quot;Groovy is cool!quot;
println serverProxy.multiply( 7 )
-> 70
server.stopServer()
37
6/22/2005
38. Demo: Groovy Automation
• ActiveXProxy
• Easy native Windows access through Groovy
• Uses Jacob Library (danadler.com/jacob)
38
6/22/2005
39. ActiveXProxy: Internet Explorer
import org.codehaus.groovy.scriptom.ActiveXProxy
explorer = new
ActiveXProxy(quot;InternetExplorer.Applicationquot;)
explorer.Visible = true
explorer.AddressBar = true
explorer.Navigate(quot;http://www.openlogic.comquot;)
explorer.StatusText = quot;OpenLogic home pagequot;
explorer.events.OnQuit = { println quot;Quitquot; }
explorer.events.listen()
Thread.sleep(3000)
explorer.Quit()
39
6/22/2005
41. Agenda
• Groovy Sample
• Genesis of Groovy
• Groovy Features
• Working with Java
• Groovy Markup
• Extras
• Demo
• Conclusion
41
6/22/2005
42. Trouble in Paradise
• Weak and Missing Features
– No support for inner classes
– Tool support (Eclipse, IntelliJ, etc.) not great, getting better
• Debugging/Scripting Hell
– Immature parser: hard to find quot;realquot; bugs
– Lots of rope: easy to hang yourself with dynamic code
• Language Instability
– Lots of syntactic sugar: nice to have, but may change
– Java camp vs. non-Java camp: competing directions
– quot;JSR Groovyquot; versus quot;Old Groovyquot;
42
6/22/2005
43. Conclusion
• Status
• 1.0 release expected later this summer
• Development Time
– Less than half that of Java
• Performance
– 20-90% of Java, depending on usage
– Very little tuning so far, waiting for 1.0 release
• Recommendations
– Ready for small, non-mission-critical projects
– Try it! Very easy to learn and lots of fun!
43
6/22/2005
44. For More Information
• Groovy Home Page
– http://groovy.codehaus.org
• GDK Javadoc
– http://groovy.codehaus.org/groovy-jdk.html
• JSR-241: The Groovy Programming Language
– http://www.jcp.org/en/jsr/detail?id=241
• James Strachan's Blog
– http://radio.weblogs.com/0112098/
44
6/22/2005