0
Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) Patterns Graeme Rocher,...
<ul><ul><li>Learn how Groovy through its powerful meta-programming techniques is enabling frameworks like Grails to change...
Your Speakers <ul><li>Graeme Rocher </li></ul><ul><ul><li>Project Lead of Grails </li></ul></ul><ul><ul><li>CTO of G2One I...
Your Speakers <ul><li>Guillaume LaForge </li></ul><ul><ul><li>Project Lead of Groovy </li></ul></ul><ul><ul><li>VP of Tech...
Agenda <ul><li>Introduction and Why Groovy? </li></ul><ul><li>What makes a dynamic language? </li></ul><ul><li>Groovy’s Me...
What is Groovy? <ul><li>Groovy is a dynamic language for the Java Virtual Machine (JVM) </li></ul><ul><li>Takes inspiratio...
What is Grails? <ul><li>A Web  platform  that implements the full stack from build system down to ORM layer </li></ul><ul>...
Getting Started <ul><li>Download from  http://grails.org/Download </li></ul><ul><li>Extract zip to disk </li></ul><ul><li>...
Why is Groovy dynamic? <ul><li>A lot of confusion exists on what a factors make a language dynamic </li></ul><ul><ul><li>D...
Dynamic/Static/Weak/Strong
The Meta Object Protocol (MOP) <ul><li>There are many dynamic languages </li></ul><ul><ul><li>VB, Python, Ruby, Groovy, Ja...
Groovy’s MOP <ul><li>Every class has a MetaClass, which can be obtained with: </li></ul><ul><li>The MetaClass defines the ...
Using  respondsTo  and  hasProperty <ul><li>Need to find out whether an object implements a method? Use  respondsTo : </li...
Useful API References <ul><li>MetaObjectProtocol </li></ul><ul><ul><li>http://groovy. codehaus . org/api/groovy/lang/MetaO...
Adding Methods at Runtime <ul><li>Instance methods can be added using the MetaClass: </li></ul><ul><li>As can properties u...
Static Methods and Constructors <ul><li>Static methods can be added using the  static  qualifier: </li></ul><ul><li>Constr...
Meta-Programming Hooks <ul><li>invokeMethod ,  methodMissing ,  get/setProperty ,  propertyMissing : </li></ul>Dog.metaCla...
Meta-Programming Patterns <ul><li>Intercept ,  Cache ,  Invoke </li></ul><ul><ul><li>Enables code synthesis </li></ul></ul...
Re-inventing Patterns with the MOP The Data Access Object The Service Locator
The Data Access Object (DAO) <ul><li>Basic Steps </li></ul><ul><ul><li>Define an interface </li></ul></ul><ul><ul><li>Defi...
Implications of DAO <ul><li>Class explosion </li></ul><ul><li>Promotes anemic domain model </li></ul><ul><li>Configuration...
Creating Dynamic SQL Finders Meta Magic with Groovy
Dynamic SQL Finders Example Book.metaClass. static . methodMissing  = { String name, args -> if (name.startsWith(&quot;fin...
Real Life Example: GORM in Grails class Album { String title String artist Date releaseDate static hasMany = [songs:Song] ...
GORM in Action Querying and Persistence with GORM
Dynamic Finders & Criteria def albums = Album. list () def recentAlbums =  Album. findAllByReleaseDateGreaterThan (new Dat...
GORM Features <ul><li>Dynamic finder and persistence methods </li></ul><ul><li>Criteria with a Groovy builder </li></ul><u...
MOP == Goodbye to the DAO <ul><li>Repetitive, boilerplate DAO logic gone (DRY) </li></ul><ul><li>Logic exists where it bel...
The Service Locator / IoC <ul><li>Pattern of many names </li></ul><ul><ul><li>Dependency Injection </li></ul></ul><ul><ul>...
Implications of Service Locator <ul><li>Requires factory classes </li></ul><ul><li>Class explosion </li></ul><ul><li>Promo...
Automatic Dependency Injection Automatic Dependency Injection with Spring & Grails via Meta-programming
Real Life Example: Spring & Grails class Book { PurchasingService purchasingService Transaction buyBook(User u) { purchasi...
Real Life Example: Spring & Grails <ul><li>Advantages of Meta way </li></ul><ul><ul><li>Promotes Domain Driven Design (DDD...
Summary <ul><li>Meta-programming represents a new way to think about problems </li></ul><ul><li>Common patterns like the D...
For More Information <ul><li>Grails </li></ul><ul><ul><li>TS-6457 - Choosing Your Java Technology-Based Web Framework: A C...
Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) Patterns Graeme Rocher ...
Upcoming SlideShare
Loading in...5
×

JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE patterns

9,090

Published on

Published in: Technology, News & Politics
1 Comment
10 Likes
Statistics
Notes
No Downloads
Views
Total Views
9,090
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
453
Comments
1
Likes
10
Embeds 0
No embeds

No notes for slide

Transcript of "JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE patterns"

  1. 1. Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) Patterns Graeme Rocher, CTO – G2One Inc Guillaume LaForge, VP of Engineering – G2One Inc TS-5793
  2. 2. <ul><ul><li>Learn how Groovy through its powerful meta-programming techniques is enabling frameworks like Grails to change the way we think about patterns on the Java™ platform </li></ul></ul>
  3. 3. Your Speakers <ul><li>Graeme Rocher </li></ul><ul><ul><li>Project Lead of Grails </li></ul></ul><ul><ul><li>CTO of G2One Inc – The Groovy/Grails Company </li></ul></ul><ul><ul><li>Member of JSR-241 (Java Specification Request) Expert Group </li></ul></ul><ul><ul><li>Author of “The Definitive Guide to Grails” </li></ul></ul>
  4. 4. Your Speakers <ul><li>Guillaume LaForge </li></ul><ul><ul><li>Project Lead of Groovy </li></ul></ul><ul><ul><li>VP of Technology at G2One Inc – The Groovy/Grails Company </li></ul></ul><ul><ul><li>Lead of JSR-241 Expert Group </li></ul></ul><ul><ul><li>Co-Author of “Groovy in Action” </li></ul></ul>
  5. 5. Agenda <ul><li>Introduction and Why Groovy? </li></ul><ul><li>What makes a dynamic language? </li></ul><ul><li>Groovy’s Meta Object Protocol </li></ul><ul><li>Domain Specific Languages </li></ul><ul><li>Meta Programming Patterns </li></ul><ul><li>Applying Meta Programming techniques to Java EE platform patterns </li></ul><ul><ul><li>The DAO </li></ul></ul><ul><ul><li>The Service Locator </li></ul></ul>
  6. 6. What is Groovy? <ul><li>Groovy is a dynamic language for the Java Virtual Machine (JVM) </li></ul><ul><li>Takes inspiration from Smalltalk, Python and Ruby </li></ul><ul><li>Integrates with the Java platform language and platform at every level </li></ul>
  7. 7. What is Grails? <ul><li>A Web platform that implements the full stack from build system down to ORM layer </li></ul><ul><li>Leverages existing technologies like Spring, Hibernate, Quartz etc. avoiding re-inventing the wheel </li></ul><ul><li>Features and extensible plug-in system and an environment for runtime configuration built on Spring </li></ul>
  8. 8. Getting Started <ul><li>Download from http://grails.org/Download </li></ul><ul><li>Extract zip to disk </li></ul><ul><li>Set GRAILS_HOME variable to location on disk </li></ul><ul><li>Add $GRAILS_HOME/bin to your environment variables </li></ul><ul><li>Download from http://groovy. codehaus .org </li></ul><ul><li>Extract zip to disk </li></ul><ul><li>Set GROOVY_HOME variable to location on disk </li></ul><ul><li>Add $GROOVY_HOME/bin to your environment variables </li></ul>
  9. 9. Why is Groovy dynamic? <ul><li>A lot of confusion exists on what a factors make a language dynamic </li></ul><ul><ul><li>Dynamic vs Static Typing </li></ul></ul><ul><ul><li>Strong vs. Weak Typing </li></ul></ul><ul><ul><li>Meta programming </li></ul></ul><ul><li>Let’s clarify these! </li></ul>
  10. 10. Dynamic/Static/Weak/Strong
  11. 11. The Meta Object Protocol (MOP) <ul><li>There are many dynamic languages </li></ul><ul><ul><li>VB, Python, Ruby, Groovy, JavaScript™ technology </li></ul></ul><ul><li>But, only a few have a MOP </li></ul><ul><ul><li>Groovy </li></ul></ul><ul><ul><li>Ruby </li></ul></ul><ul><ul><li>LISP </li></ul></ul><ul><ul><li>Smalltalk </li></ul></ul><ul><li>A MOP makes the semantics of a program extensible </li></ul>
  12. 12. Groovy’s MOP <ul><li>Every class has a MetaClass, which can be obtained with: </li></ul><ul><li>The MetaClass defines the behaviour of the object and can be inspected: </li></ul>def obj = &quot;Hello World!&quot; def metaClass = obj.metaClass obj. metaClass.methods .each { println it.name } Access the metaClass property The methods collection returns a list of MetaMethod instances
  13. 13. Using respondsTo and hasProperty <ul><li>Need to find out whether an object implements a method? Use respondsTo : </li></ul><ul><li>Need to find out if an object has a property? Use hasProperty : </li></ul>def foo = &quot;Hello World!&quot; if(foo. respondsTo(foo, &quot;toUpperCase&quot;)) println foo.toUpperCase() if(foo.metaClass. hasProperty( &quot;bytes&quot;) ) println foo.bytes.encodeAsBase64()
  14. 14. Useful API References <ul><li>MetaObjectProtocol </li></ul><ul><ul><li>http://groovy. codehaus . org/api/groovy/lang/MetaObjectProtocol .html </li></ul></ul><ul><li>MetaMethod </li></ul><ul><ul><li>http://groovy. codehaus . org/api/groovy/lang/MetaMethod .html </li></ul></ul><ul><li>MetaProperty </li></ul><ul><ul><li>http://groovy. codehaus . org/api/groovy/lang/MetaProperty .html </li></ul></ul>
  15. 15. Adding Methods at Runtime <ul><li>Instance methods can be added using the MetaClass: </li></ul><ul><li>As can properties using JavaBeans™ architecture conventions: </li></ul>class Dog {} Dog. metaClass.bark = { &quot;woof!&quot; } println new Dog().bark() class Dog {} Dog. metaClass.getBreed = { &quot;Bulldog&quot; } println new Dog().breed Assigning a block of code to a property of the MetaClass creates a method! Properties need to follow JavaBeans naming coventions
  16. 16. Static Methods and Constructors <ul><li>Static methods can be added using the static qualifier: </li></ul><ul><li>Constructors can be added using a special constructor property: </li></ul>Dog.metaClass .static.bark = {new Dog() } println Dog.create().bark() Dog. metaClass .constructor = {String s -> new Dog(name:s) } println new Dog( &quot;Fred&quot; ).name Prefix the method name with the static qualifier to make a static method Careful of Stack overflows when overriding constructors!
  17. 17. Meta-Programming Hooks <ul><li>invokeMethod , methodMissing , get/setProperty , propertyMissing : </li></ul>Dog.metaClass . methodMissing = { String name, args-> println &quot;Dogs don’t $name!&quot; } def d = new Dog() d.quack() d.fly() &quot;Dogs don’t quack!&quot; &quot;Dogs don’t fly!&quot; No exception is thrown, the call is intercepted and the messages printed to system out Method missing allows you to intercept failed method dispatch
  18. 18. Meta-Programming Patterns <ul><li>Intercept , Cache , Invoke </li></ul><ul><ul><li>Enables code synthesis </li></ul></ul><ul><li>Basic Usage: </li></ul><ul><ul><li>Intercept method </li></ul></ul><ul><ul><li>Dynamically create new method </li></ul></ul><ul><ul><li>Cache new method </li></ul></ul><ul><ul><li>Invoke new method </li></ul></ul><ul><li>First call takes performance hit, next call faster </li></ul>Dog.metaClass . methodMissing = {String name, args-> def cached = {Object[] a -> println ”Dogs don’t $name!&quot; } Dog.metaClass . &quot;$name&quot; = cached cached. call(args) } Intercept – implement methodMissing Cache – Dynamically register new method Invoke – call new behaviour
  19. 19. Re-inventing Patterns with the MOP The Data Access Object The Service Locator
  20. 20. The Data Access Object (DAO) <ul><li>Basic Steps </li></ul><ul><ul><li>Define an interface </li></ul></ul><ul><ul><li>Define one or many implementations </li></ul></ul><ul><ul><li>Inject dependencies into implementations </li></ul></ul><ul><ul><ul><li>Dependency Injection (IoC) </li></ul></ul></ul><ul><ul><ul><li>Factories </li></ul></ul></ul>http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
  21. 21. Implications of DAO <ul><li>Class explosion </li></ul><ul><li>Promotes anemic domain model </li></ul><ul><li>Configuration, configuration, configuration </li></ul><ul><li>Violates DRY </li></ul>
  22. 22. Creating Dynamic SQL Finders Meta Magic with Groovy
  23. 23. Dynamic SQL Finders Example Book.metaClass. static . methodMissing = { String name, args -> if (name.startsWith(&quot;findBy&quot;) && args) { def prop = name[6..-1] prop= prop[0].toLowerCase() + prop[1..-1] def callable = { Object[] varArgs -> def results = [] def sql = Sql.newInstance( url, user, pass, driver) sql.eachRow( &quot;&quot;&quot;select * from ${Book.name} where $prop=?&quot;&quot;&quot; , [varArgs[0]]) { results << new Book(title:it.title, author:it.author) } return results } Book.metaClass. &quot;$name&quot; = callable return callable. call(args) } } Intercept Cache Invoke
  24. 24. Real Life Example: GORM in Grails class Album { String title String artist Date releaseDate static hasMany = [songs:Song] } class Song { String title Double duration } table - album table - song GORM classes, also known as domain classes, go in the domain directory id title artist release_date id title duration album_id
  25. 25. GORM in Action Querying and Persistence with GORM
  26. 26. Dynamic Finders & Criteria def albums = Album. list () def recentAlbums = Album. findAllByReleaseDateGreaterThan (new Date()-7) def albumsStartingWithA = Album. findAllByTitleLike ( &quot;A%&quot;) def albumsWithSongsAboutSummer = Album. withCriteria { songs { like(&quot;title&quot;, &quot;%Summmer%&quot;) } } List all records Form method expressions Use “like” queries Construct criteria on the fly to query associations
  27. 27. GORM Features <ul><li>Dynamic finder and persistence methods </li></ul><ul><li>Criteria with a Groovy builder </li></ul><ul><li>Object-relational Mapping DSL </li></ul><ul><ul><li>Caching </li></ul></ul><ul><ul><li>Legacy mapping </li></ul></ul><ul><ul><li>Locking strategy (optimistic/pessimistic) </li></ul></ul><ul><li>Built on Hibernate </li></ul>+
  28. 28. MOP == Goodbye to the DAO <ul><li>Repetitive, boilerplate DAO logic gone (DRY) </li></ul><ul><li>Logic exists where it belongs - in the domain (DDD) </li></ul><ul><li>No direct references to third part dependencies! </li></ul>
  29. 29. The Service Locator / IoC <ul><li>Pattern of many names </li></ul><ul><ul><li>Dependency Injection </li></ul></ul><ul><ul><li>Service Locator </li></ul></ul><ul><ul><li>Inversion of Control </li></ul></ul><ul><li>Abstracts dependency look-up code </li></ul>http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html
  30. 30. Implications of Service Locator <ul><li>Requires factory classes </li></ul><ul><li>Class explosion </li></ul><ul><li>Promotes anemic domain model </li></ul><ul><li>Configuration, configuration, configuration </li></ul>
  31. 31. Automatic Dependency Injection Automatic Dependency Injection with Spring & Grails via Meta-programming
  32. 32. Real Life Example: Spring & Grails class Book { PurchasingService purchasingService Transaction buyBook(User u) { purchasingService.buyBook(this, u) } } Book. metaClass.constructor = {-> def obj = BeanUtils.instantiateClass(Book) applicationContext .getAutowireCapableBeanFactory() . autowireBeanProperties( obj, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false) return obj } Book domain class requires reference to PurchasingService Overriding default constructor for class Autowire dependencies into object from Spring at construction time
  33. 33. Real Life Example: Spring & Grails <ul><li>Advantages of Meta way </li></ul><ul><ul><li>Promotes Domain Driven Design (DDD) </li></ul></ul><ul><ul><li>No configuration </li></ul></ul><ul><ul><li>DRY </li></ul></ul>def user = User.get(1) def book = new Book() book.buyBook(user) All dependencies in place even when the new operator is used!
  34. 34. Summary <ul><li>Meta-programming represents a new way to think about problems </li></ul><ul><li>Common patterns like the DAO and Service Locator are present because of limitations in Java platform </li></ul><ul><li>Groovy and Grails open doors to declarative programmings, DSLs and Domain Driven Design (DDD) </li></ul>
  35. 35. For More Information <ul><li>Grails </li></ul><ul><ul><li>TS-6457 - Choosing Your Java Technology-Based Web Framework: A Comparison </li></ul></ul><ul><ul><li>http://grails.org </li></ul></ul><ul><li>Groovy </li></ul><ul><ul><li>Sessions, Panel Discussions, BOFs: PAN-5435, TS-5815, TS-6050, TS-5274, BOF-5102, BOF-5110, TS-5693, BOF-5101 </li></ul></ul><ul><ul><li>http://groovy. codehaus .org </li></ul></ul>
  36. 36. Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) Patterns Graeme Rocher Guillaume LaForge TS-5793
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×