Groovy Update - JavaPolis 2007

  • 1,572 views
Uploaded on

Groovy Update at JavaPolis 2007 with Dierk Koenig

Groovy Update at JavaPolis 2007 with Dierk Koenig

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,572
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
0
Comments
0
Likes
1

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

Transcript

  • 1.  
  • 2. Groovy Update Guillaume Laforge G2One Dierk K önig Canoo Engineering AG
  • 3. Overall Presentation Goal
      • Learn more about the Groovy dynamic language for the JVM, what’s new in the latest version, and how you can use it in your projects!
  • 4. Guillaume Laforge
    • Groovy Project Manager
    • JSR-241 Spec Lead
    • Initiator of the Grails framework
    • Co-author of Groovy in Action
      • By Dierk König, et al.
    • Vice-President Technology
  • 5. Dierk König
    • Canoo Engineering AG, Basel
    • Rich Internet Applications Projects, Consulting, Training www.canoo.com
    • Trainer, Coach, Developer, Architect
    • Groovy- and Grails-Committer
    • Lead author: Groovy in Action
  • 6. Agenda
    • What’s Groovy?
    • Syntax basics
    • Groovy APIs
    • What’s new in Groovy 1.5?
    • Domain-Specific Languages
    • Integrating Groovy in your applications
    • Summary
    • Q&A
  • 7. What’s Groovy?
    • An award-winning alternative dynamic language for the JVM
    • State of the Groovy Nation
  • 8. Groovy – feature rich and Java friendly
  • 9. Being Java friendly
    • Groovy is Java-like
      • Easy to learn for a Java developer
        •  flat learning curve
      • Simpler than Java for beginners and subject matter experts
    • Seamless integration with Java
      • You can mix Groovy and Java objects together
        • Groovy class extending Java class implementing Groovy interface, and vice versa…
      • Same strings, regex, APIs, OO, threads, security
        • Same paradigm and platform!
        • No impedance mismatch!
  • 10. Being feature rich
    • Fully object-oriented
    • Properties declared easily
    • Closures for versatile code blocks
    • Operator overloading
    • Native syntax for enhanced Strings, regexes, lists, ranges, enums and maps
    • Multimethods: call the right method!
    • GPath: XPath-like navigation in object graphs
    • BigDecimal arithmetic by default
    • Optional semi-colons and parenthesis
    • GDK: a library that builds upon the JDK
    • Perfect for Domain-Specific Languages
  • 11. Lots of integrations
    • AntHill Grails eXo Platform JBoss Seam NanoContainer Eclipse XWiki ServiceMix Tapestry Wicket TestNG SoapUI Turbine Oracle OC4J Blojsom NetBeans OpenEJB Drools 1060NetKernel RIFE GroovyRules Mule FreeMind LuxorXUL Spring Ant Maven IntelliJ IDEA Simple JSPWiki eXist Canoo WebTest Biscuit ThinG Oracle Data Integrator Struts2 Eclipse JMeter JFreeChart, IBM Project Zero, SAP Composition, …
  • 12. Used in Mission-Critical applications
    • Mutual of Omaha – Fortune 500 US Comp.
      • 45,000 lines of Groovy (half business code / half test code)
      • Integrated in an EJB as a risk calculation engine for insurance policies
      • Involved Java beginners, developers, and subject matter experts
      • Exact arithmetic support, perfect Java integration, closures  ideal for business rules expression
  • 13. Books already out… more coming…
  • 14. JAX 2007 Innovation Award
    • 40 proposals / 10 nominees
    • Groovy won the first prize
      • Most innovative and creative project
      • 10,000 euros donation
    • Past winner was Spring
  • 15. Syntax Basics
    • Groovy as a Java-superset
    • Properties, lists, maps, ranges, regex, strings, closures
  • 16. Properties Support
    • Don’t wait for Java 7/8/9 
    • Getters / setters are boring boiler-plate code
    • Groovy adds support for properties
      • Declared fields get automagic accessors
    • Example
      • class Person { String name String firstName }
  • 17. Literals for lists, maps, ranges, regex, strings
    • List: def list = ["Groovy", "Grails"]
    • Map: def map = [CA: "Calif.", TX: "Texas"]
    • Ranges: def oneToTen = 1..10
    • Regex: assert fooooo ==~ /fo*/
    • Multiline strings:
      • def s = """ multi line string"""  
    • Gstring
      • println "My name is ${name}"
  • 18. Closures
    • Don’t wait for Java 7/8/9, get closures now!
    • Reusable / assignable code blocks
      • Combine, store, share data and logic
    • Examples
      • new File('x.txt').eachLine{ println it }
      • [0, 1, 2].each { println it }
      • def numbers = 1..100 def odd = { it % 2 == 1 } numbers.findAll { it > 90 } numbers.findAll( odd )
  • 19. Groovy APIs
    • Groovy Development Kit
    • Examples: XML, SQL, Swing and Office automation
  • 20. Groovy Development Kit
    • Simplified APIs for common tasks
      • Mocking / stubbing support
      • XML parsing and GPath navigation
      • SQL support with exception & resource handling
      • Scripting Ant with the AntBuilder
      • Create Swing UIs easily with SwingBuilder
      • Templating support à la Velocity
      • Script COM / ActiveX components on Windows
      • Consume / expose XML-RPC / SOAP services
      • Handle JXM beans as local objects
  • 21. XML Parsing and GPath Navigation
    • Given this XML snippet
      • def xml = &quot;&quot;&quot; <languages> <language name=&quot;Groovy&quot;> <feature coolness=&quot;low&quot;>SQL</feature> <feature coolness=&quot;high&quot;>Template</feature> </language> <language name=&quot;Perl&quot;/> </languages>&quot;&quot;“
    • Navigate the object graph
      • def root = new XmlParser().parseText(xml) println root.language.feature[1].text() root.language.feature .findAll{ it['@coolness'] == &quot;low&quot; } .each{ println it.text() }
  • 22. SQL support
    • Easy to use JDBC thanks to closures
      • def sql = Sql.newInstance(url, usr, pwd, driver) sql.execute(&quot;insert into table values ($foo, $bar)&quot;) sql.execute(&quot;insert into table values(?,?)&quot;, [a, b]) sql.eachRow(&quot;select * from USER&quot;) { print it.name } def list = sql.rows(&quot;select * from USER&quot;)
    • DataSet notion: « poor-man » ORM
      • def set = sql.dataSet(&quot;USER&quot;) set.add(name: &quot;Johnny&quot;, age: 33) set.each { user -> println user.name } set.findAll { it.age > 22 && it.age < 42 }
  • 23. SwingBuilder
    • def theMap = [color: &quot;green&quot;, object: &quot;pencil&quot;] def swing = new SwingBuilder() def frame = swing. frame ( title: 'A Groovy Swing', location: [240,240], defaultCloseOperation:WC.EXIT_ON_CLOSE) { panel { for (entry in theMap) { label (text: entry.key) textField (text: entry.value) } button (text: 'About', actionPerformed: { def pane = swing.optionPane(message: 'SwingBuilder') def dialog = pane.createDialog(null, 'About') dialog.show() }) button (text:'Quit', actionPerformed:{ System.exit(0) }) } } frame.pack() frame.show()
  • 24. Automating Office Applications
    • An additional module provide VB-like scripting capabilities with a VB-like syntax
    • Example
      • def outlook = new ActiveXProxy(&quot;Outlook.Application&quot;) def message = outlook.CreateItem(0) def emails = glaforge @ gmail.com   def rec= message.Recipients.add(emails) rec.Type = 1 message.Display(true)
  • 25. Domain-Specific Languages
    • Why create DSLs?
    • How to create such DSLs?
  • 26. Why Create a Domain-Specific Language?
    • Use a more expressive language than a general programming language
    • Share a common metaphore between developers and subject matter experts
    • Have domain experts help design the business logic of an application
    • Avoid cluttering business code with too much boilerplate technical code
    • Cleanly seperate business logic from application code
  • 27. Putting it all together
    • Optional parens, map syntax, props on ints
      • move left
      • compare indicator: ‘NIKEI’, withFund: ‘XYZ’
      • account.debit amount: 30.euros, in: 3.days
    • Custom control structures with closures
      • unless ( account.balance < 0 ) { account.debit 10.dollars }
      • execute( withTimeoutOf: 50.seconds ) { … }
    • Operator overloading
      • a + b  a.plus(b)
      • taskA | taskB  taskA.or(taskB)
  • 28. Builder pattern at the syntax level
    • Tree structures are everywhere
      • XML, GUI components, Ant tasks, conf files…
    • Through closure & chained method calls
      • new MarkupBuider().invoices { invoice(id: &quot;4&quot;) { line &quot;product 1&quot; line &quot;product 2&quot; } }
    • Create your own « builder »
      • Extend BuilderSupport, or FactoryBuilderSupport
  • 29. What’s new in 1.5?
    • Java 5 features
    • New dynamic capabilities
    • Performance improvements
    • IDE support
  • 30. What’s New?
    • Java 5 features
      • Annotations, generics, enums, static imports
    • New powerful dynamic capabilities
      • ExpandoMetaClass contributed by Grails
    • Performance improvements
      • Regular gains of perf. between the last releases
    • IDE support
      • IntelliJ IDEA, NetBeans & Eclipse
  • 31. Java 5 Features
    • Why adding Java 5 features to Groovy?
      • To leverage Enterprise frameworks making use of annotations and generics
        • Spring, JPA, Hibernate , Guice, TestNG, JUnit 4
      • Groovy is the sole alternative dynamic language for the JVM supporting annotations
      • Groovy is Java-like, but is closer to being a Java-superset
    • If you need annotations / generics and want to benefit from a dynamic language
      • Look no further, Groovy is the sole option
  • 32. Annotations Example
    • Taken from JBoss Seam ’s documentation
    • @Entity @Name(&quot;hotel&quot;) class Hotel implements Serializable { @Id @GeneratedValue Long id @Length(max=50) @NotNull String name @Override String toString() { &quot;Hotel ${name}&quot;  } }
  • 33. Enums example with a Groovy switch
    • enum Day { SUNDAY, MONDAY, TUESDAY, 
    • WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
    • def today =  Day.SATURDAY
    • switch (today) {
    •      case  [Day.SATURDAY, Day.SUNDAY] : 
    •          println &quot;Weekends are cool&quot;
    •          break
    •      case  Day.MONDAY..Day.FRIDAY : 
    •          println &quot;Boring work day&quot;
    •          break
    •      default: 
    •          println &quot;Is this a valid day?&quot;
    • }
  • 34. New dynamic features
    • Grails contributed the ExpandoMetaClass
      • Easily add new behavior to existing classes
      • Symbiotic relationship between both projects
    • Ex: Adding a meters property to numbers
      • Integer.metaClass.getMeters = { -> new Distance(delegate, Distance.METER) } println 3.meters
  • 35. Have a look at the IntelliJ IDEA plugin!
  • 36. Integrating Groovy in your Applications
    • Why integrating Groovy in your applications?
    • The different integration mechanisms
  • 37. Why Integrating Groovy in your Apps?
    • Groovy’s great support for testing
      • Mocks & stubs, GroovyTestCase
      • More concise & readable tests
    • Handy tool in the developer toolbox
    • Externalize business rules
      • Business rules be written by domain experts
      • Rules follow their own lifecycle
    • Providing extension points in your apps
      • For third-party plugins
      • Customizing the app to clients’ needs
  • 38. Several Integration Mechanisms
    • The « old » Bean Scripting Framework
    • Java 6’s scripting APIs (JSR-223)
    • Spring dynamic language support
    • Groovy’s own mechanisms
    • Let’s see some of them
  • 39. JSR-223 – javax.script.* from JDK 6
    • One API to rule them all!
    • Dedicated Groovy engine on scripting.dev.java.net
      • Drop it in your classpath!
    • Example
      • ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine gEngine = manager.getEngineByName(&quot;groovy&quot;); String result = (String)gEngine.eval(&quot;’Foo’ * 2&quot;);
  • 40. GroovyShell
    • Easily evaluate expressions in your Java app
      • Pass variables in and out
      • Can provide global reusable functions
    • Example
      • def binding = new Binding() binding.mass = 22.3 binding.velocity = 10.6 def shell = new GroovyShell( binding ) def expression = &quot;mass * velocity ** 2 / 2&quot; assert shell.evaluate(expression) == 1252.814
  • 41. GroovyClassLoader
    • Most powerful integration mechanism
    • With GCL, you can
      • Parse and compile classes
      • Provide a resource loader defining the location of sources
        • Database, flat files, XML files, distant URLs…
      • Define Java security rules
        • To avoid System.exit(0) in an Embedded DSL!
      • Even transform the Abstract Syntax Tree !
  • 42. Spring 2.x Groovy integration
    • Spring 2.0 provides support for alternative language bean definitions and configuration
      • A POGO can be wired the like a POJO and be proxied
      • You can mix languages in your Spring application
      • POGO and POJO can be injected within each other
    • Configuration of a POGO bean with the specific lang namespace , and a custom MetaClass
      • <lang:groovy id=&quot;events&quot; script-source=&quot;classpath:dsl/eventsChart.groovy&quot; customizer-ref=&quot;eventsMetaClass&quot; />
  • 43. Let’s Wrap Up
    • Summary
    • Resources
    • Q&A
  • 44. Summary
    • The Groovy dynamic language for the JVM simplifies the life of developers through powerful APIs
    • Groovy opens some interesting perspectives towards extending your application
    • Groovy provides seamless Java integration
    • Groovy lets you create DSL s
    • Groovy protects your investment in Java skills, tools, libraries, frameworks, and application platforms
  • 45. Resources
    • Groovy: http: //groovy . codehaus . org
    • Grails: http: //grails . org
    • Groovy blogs: http: //groovyblogs . org
    • AboutGroovy: http: //aboutgroovy . com
    • G2One: http://www.g2one.com
    • Canoo: http://www.canoo.com
  • 46. Q&A View JavaPolis talks @ www.parleys.com
  • 47. Thank you for your attention