Groovy = Java + Ruby + Python
         for the JVM
           Rod Cope
Groovy Goals



• Learn what Groovy can do for you
• Start using it today!




                                           ...
Rod Cope
• Founder and CTO of OpenLogic
  – rod.cope@openlogic.com
• 9+ years Java experience
  – Sun Certified Java Archi...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Sample: Java and Groovy!
public class Filter {
  public static void main( String[] args ) {
    List list = new ArrayList(...
Sample: Groovy!

def list = [quot;Rodquot;, quot;Neetaquot;, quot;Ericquot;, quot;Missyquot;]
def shorts = list.findAll { ...
Sample in Java (27 lines)
public class Filter {
  public static void main( String[] args ) {
    List list = new ArrayList...
Sample in Groovy (4 lines)

def list = [quot;Rodquot;, quot;Neetaquot;, quot;Ericquot;, quot;Missyquot;]
def shorts = list...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Java Platform Strengths
• Lots of reusable software, components, tools
• VM and Binary Compatibility
  – Build deployment ...
Components vs. Scripting
•   We reuse far more code than we write
•   We spend more time gluing components than writing th...
Why Another Agile Language?
• Want complete binary compatibility with Java
  – No difference from Java at JVM / bytecode l...
Groovy
• Who/When
  – James Strachan, Bob McWhirter – August 2003
• What
  – Dynamic, object-oriented scripting language f...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Groovy Features
• Dynamic and Static Typing
    def str = quot;Helloquot;
    int a = 2

• Native syntax for lists, maps, ...
Groovy Features (cont.)
• Regex built-in
   if ( quot;namequot; ==~ quot;na.*quot; ) { println quot;match!quot; }
     gro...
Groovy JDK
• Groovy-er JDK: adds convenient methods to JDK
• String
  – contains(), count(), execute(), padLeft(), center(...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Working with Java
• Create Adder.java
  package com.openlogic.test;
  public interface Adder
  {
     public int add( int ...
Working with Java (cont.)
• Compile the Java code
  javac -d target Adder.java

• Compile the Groovy code
  groovyc --clas...
Working with Ant

• BSF-compliant
  <script language=quot;groovyquot;>println 'hi' * 2</script>

• Groovy task
  <taskdef ...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Groovy Markup
• Native support for hierarchical structures in
  code
   –   XML
   –   XHTML
   –   Ant
   –   Swing
   – ...
Groovy Markup: XML
<people>
   <person name='Rod'>
      <pet name='Bowie' age='3' />
      <pet name='Misha' age='9' />
 ...
Groovy Markup: XML (cont.)
data = ['Rod': ['Misha':9, 'Bowie':3],
        'Eric': ['Poe':5, 'Doc':4] ]

xml = new groovy.x...
Groovy Markup: XML Parsing
xml = quot;quot;quot;<people>
<person name=quot;Rodquot;>
   <pet name=quot;Mishaquot; age=quot...
XML: Transformation
• Advanced XML Generation
  – StreamingMarkupBuilder in sandbox generates HTML
    and complex XML - u...
XML: Transformation Example
• In navigation.xml:
   <body><links>
  <item name=quot;Downloadquot; href=quot;download.htmlq...
Groovy Markup: Ant
ant = new groovy.util.AntBuilder()

ant.echo( 'starting...' )
ant.sequential {
   def mydir = 'c:/backu...
Groovy Markup: Swing
def swing = new groovy.swing.SwingBuilder()
frame = swing.frame(title: 'My Frame', size: [800,400]) {...
Groovy SQL
sql = new groovy.sql.Sql( dataSource )
sql.execute( quot;create table person
             ( name varchar, age i...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Extras
• Processes: quot;cmd /c dirquot;.execute().text
• Threading: Thread.start { any code }
• Testing: GroovyTestCase, ...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Demo: XML-RPC
• XML-based Communication (like SOAP)
• Server and Client side support
• Separate Module in Groovy (not in c...
XML-RPC
– import groovy.net.xmlrpc.*
– Server
   server = new XMLRPCServer()
   server.testme = { | name | name + quot; is...
Demo: Groovy Automation
• ActiveXProxy
• Easy native Windows access through Groovy
• Uses Jacob Library (danadler.com/jaco...
ActiveXProxy: Internet Explorer
 import org.codehaus.groovy.scriptom.ActiveXProxy
 explorer = new
   ActiveXProxy(quot;Int...
ActiveXProxy: Excel
import org.codehaus.groovy.scriptom.ActiveXProxy
excel = new ActiveXProxy(quot;Excel.Applicationquot;)...
Agenda
•   Groovy Sample
•   Genesis of Groovy
•   Groovy Features
•   Working with Java
•   Groovy Markup
•   Extras
•   ...
Trouble in Paradise
• Weak and Missing Features
  – No support for inner classes
  – Tool support (Eclipse, IntelliJ, etc....
Conclusion
• Status
  • 1.0 release expected later this summer
• Development Time
  – Less than half that of Java
• Perfor...
For More Information
• Groovy Home Page
  – http://groovy.codehaus.org
• GDK Javadoc
  – http://groovy.codehaus.org/groovy...
Q&A Period




       Any questions?




                                    45
                        6/22/2005
Upcoming SlideShare
Loading in …5
×

OpenLogic

794 views

Published on

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

  • Be the first to like this

No Downloads
Views
Total views
794
On SlideShare
0
From Embeds
0
Number of Embeds
29
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

OpenLogic

  1. 1. Groovy = Java + Ruby + Python for the JVM Rod Cope
  2. 2. Groovy Goals • Learn what Groovy can do for you • Start using it today! 2 6/22/2005
  3. 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. 4. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 4 6/22/2005
  5. 5. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 5 6/22/2005
  6. 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. 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. 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
  9. 9. Sample in Groovy (4 lines) def list = [quot;Rodquot;, quot;Neetaquot;, quot;Ericquot;, quot;Missyquot;] def shorts = list.findAll { it.size() <= 4 } println shorts.size() shorts.each { println it } 9 6/22/2005
  10. 10. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 10 6/22/2005
  11. 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. 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. 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. 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. 15. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 15 6/22/2005
  16. 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. 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. 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. 19. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 19 6/22/2005
  20. 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. 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. 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. 23. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 23 6/22/2005
  24. 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
  25. 25. Groovy Markup: XML <people> <person name='Rod'> <pet name='Bowie' age='3' /> <pet name='Misha' age='9' /> </person> <person name='Eric'> <pet name='Poe' age='5' /> <pet name='Doc' age='4' /> </person> </people> 25 6/22/2005
  26. 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. 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. 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
  29. 29. XML: Transformation Example • In navigation.xml: <body><links> <item name=quot;Downloadquot; href=quot;download.htmlquot;/> <item name=quot;JavaDocquot; href=quot;apidocs/index.htmlquot;/> ... • Excerpt from groovy.util.NavToWiki.groovy doc = new XmlParser().parse(quot;navigation.xmlquot;) items = doc.body.links.item println items.collect { item -> quot;{link:${item['@name']}|${item['@href']}}quot; }.join(quot; | quot;) -> {link:Download|download.html} | {link:JavaDoc|apidocs/index.html} 29 6/22/2005
  30. 30. Groovy Markup: Ant ant = new groovy.util.AntBuilder() ant.echo( 'starting...' ) ant.sequential { def mydir = 'c:/backups' mkdir( dir: mydir ) copy( todir: mydir ) { fileset( dir: 'src/test' ) { includes( name:'**/*.groovy' ) } } echo( quot;done!quot; ) } 30 6/22/2005
  31. 31. Groovy Markup: Swing def swing = new groovy.swing.SwingBuilder() frame = swing.frame(title: 'My Frame', size: [800,400]) { menuBar { menu(text: 'File') { menuItem() { action(name:'New', closure:{ println(quot;Newquot;) }) } } } panel(layout:new BorderLayout()) { label(text: 'Name', constraints: BorderLayout.WEST, toolTipText: 'This is the name field') button(text: 'Click me!', constraints: BorderLayout.SOUTH, actionPerformed: { println(quot;Click!quot;) } ) } } frame.show() 31 6/22/2005
  32. 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. 33. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 33 6/22/2005
  34. 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. 35. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 35 6/22/2005
  36. 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. 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. 38. Demo: Groovy Automation • ActiveXProxy • Easy native Windows access through Groovy • Uses Jacob Library (danadler.com/jacob) 38 6/22/2005
  39. 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
  40. 40. ActiveXProxy: Excel import org.codehaus.groovy.scriptom.ActiveXProxy excel = new ActiveXProxy(quot;Excel.Applicationquot;) excel.Visible = true Thread.sleep(1000) workbooks = excel.Workbooks workbook = workbooks.Add() sheet = workbook.ActiveSheet a1 = sheet.Range('A1') a2 = sheet.Range('A2') a1.Value = 125.3 a2.Formula = '=A1 * 2' println quot;a2: ${a2.Value.value}quot; groovy> 250.6 Workbook.close( false, null, false ) excel.Quit() 40 6/22/2005
  41. 41. Agenda • Groovy Sample • Genesis of Groovy • Groovy Features • Working with Java • Groovy Markup • Extras • Demo • Conclusion 41 6/22/2005
  42. 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. 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. 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
  45. 45. Q&A Period Any questions? 45 6/22/2005

×