36
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

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

Embed Size (px)

Citation preview

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

Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) PatternsGraeme Rocher, CTO – G2One IncGuillaume LaForge, VP of Engineering – G2One Inc

TS-5793

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

2008 JavaOneSM Conference | java.sun.com/javaone | 2

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

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

2008 JavaOneSM Conference | java.sun.com/javaone | 3

Your Speakers

Graeme Rocher•Project Lead of Grails

•CTO of G2One Inc – The Groovy/Grails Company

•Member of JSR-241 (Java Specification Request) Expert Group

•Author of “The Definitive Guide to Grails”

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

2008 JavaOneSM Conference | java.sun.com/javaone | 4

Your Speakers

Guillaume LaForge•Project Lead of Groovy

•VP of Technology at G2One Inc – The Groovy/Grails Company

•Lead of JSR-241 Expert Group

•Co-Author of “Groovy in Action”

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

2008 JavaOneSM Conference | java.sun.com/javaone | 5

Agenda

Introduction and Why Groovy?What makes a dynamic language?Groovy’s Meta Object ProtocolDomain Specific LanguagesMeta Programming PatternsApplying Meta Programming techniques to Java EE platform patterns•The DAO

•The Service Locator

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

2008 JavaOneSM Conference | java.sun.com/javaone | 6

What is Groovy?

Groovy is a dynamic language for the Java Virtual Machine (JVM)Takes inspiration from Smalltalk, Python and Ruby Integrates with the Java platform languageand platform at every level

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

2008 JavaOneSM Conference | java.sun.com/javaone | 7

What is Grails?

A Web platform that implements the full stack from build system down to ORM layerLeverages existing technologies like Spring, Hibernate, Quartz etc. avoiding re-inventing the wheelFeatures and extensible plug-in system and an environment for runtime configuration built on Spring

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

2008 JavaOneSM Conference | java.sun.com/javaone | 8

Getting Started

Download from http://grails.org/DownloadExtract zip to diskSet GRAILS_HOME variable to location on diskAdd $GRAILS_HOME/bin to your environment variables

Download from http://groovy.codehaus.orgExtract zip to diskSet GROOVY_HOME variable to location on diskAdd $GROOVY_HOME/bin to your environment variables

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

2008 JavaOneSM Conference | java.sun.com/javaone | 9

Why is Groovy dynamic?

A lot of confusion exists on what a factors make a language dynamic•Dynamic vs Static Typing

•Strong vs. Weak Typing

•Meta programming

Let’s clarify these!

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

2008 JavaOneSM Conference | java.sun.com/javaone | 10

Dynamic/Static/Weak/Strong

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

2008 JavaOneSM Conference | java.sun.com/javaone | 11

The Meta Object Protocol (MOP)

There are many dynamic languages•VB, Python, Ruby, Groovy, JavaScript™

technology

But, only a few have a MOP•Groovy

•Ruby

•LISP

•Smalltalk

A MOP makes the semantics of a program extensible

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

2008 JavaOneSM Conference | java.sun.com/javaone | 12

Groovy’s MOP

Every class has a MetaClass, which can be obtained with:

The MetaClass defines the behaviour of the object and can be inspected:

def obj = "Hello World!"def metaClass = obj.metaClass

obj.metaClass.methods.each { println it.name }

Access the metaClass property

The methods collection returns a list of MetaMethod instances

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

2008 JavaOneSM Conference | java.sun.com/javaone | 13

Using respondsTo and hasProperty

Need to find out whether an object implements a method? Use respondsTo:

Need to find out if an object has a property? Use hasProperty:

def foo = "Hello World!"if(foo.respondsTo(foo, "toUpperCase")) println foo.toUpperCase()

if(foo.metaClass.hasProperty("bytes")) println foo.bytes.encodeAsBase64()

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

2008 JavaOneSM Conference | java.sun.com/javaone | 14

Useful API References

MetaObjectProtocol•http://groovy.codehaus.org/api/groovy/lang/

MetaObjectProtocol.html

MetaMethod•http://groovy.codehaus.org/api/groovy/lang/

MetaMethod.html

MetaProperty•http://groovy.codehaus.org/api/groovy/lang/

MetaProperty.html

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

2008 JavaOneSM Conference | java.sun.com/javaone | 15

Adding Methods at Runtime

Instance methods can be added using the MetaClass:

As can properties using JavaBeans™ architecture conventions:

class Dog {}Dog.metaClass.bark = {"woof!" }println new Dog().bark()

class Dog {}Dog.metaClass.getBreed = {"Bulldog" }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

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

2008 JavaOneSM Conference | java.sun.com/javaone | 16

Static Methods and Constructors

Static methods can be added using the static qualifier:

Constructors can be added using a special constructor property:

Dog.metaClass .static.bark = {new Dog() }println Dog.create().bark()

Dog.metaClass .constructor = {String s -> new Dog(name:s) }println new Dog("Fred").name

Prefix the method name with the static qualifier to make a static method

Careful of Stack overflows when overriding constructors!

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

2008 JavaOneSM Conference | java.sun.com/javaone | 17

Meta-Programming Hooks

invokeMethod, methodMissing, get/setProperty, propertyMissing:

Dog.metaClass .methodMissing = { String name, args-> println "Dogs don’t $name!" }

def d = new Dog()d.quack()d.fly()"Dogs don’t quack!" "Dogs don’t fly!"

No exception is thrown, the call is intercepted and the messages printed to system out

Method missing allows you to intercept failed method dispatch

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

2008 JavaOneSM Conference | java.sun.com/javaone | 18

Meta-Programming Patterns

Intercept, Cache, Invoke•Enables code synthesis

Basic Usage:• Intercept method

•Dynamically create new method

•Cache new method

• Invoke new method

First call takes performance hit, next call faster

Dog.metaClass .methodMissing = {String name, args-> def cached = {Object[] a -> println ”Dogs don’t $name!" } Dog.metaClass ."$name" = cached cached.call(args)}

Intercept – implement methodMissing

Cache – Dynamically register new method

Invoke – call new behaviour

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

2008 JavaOneSM Conference | java.sun.com/javaone | 19

Re-inventing Patterns with the MOP

The Data Access Object

The Service Locator

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

2008 JavaOneSM Conference | java.sun.com/javaone | 20

The Data Access Object (DAO)

Basic Steps•Define an interface

•Define one or many implementations

•Inject dependencies into implementations•Dependency Injection

(IoC)

• Factories

http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

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

2008 JavaOneSM Conference | java.sun.com/javaone | 21

Implications of DAO

Class explosionPromotes anemic domain modelConfiguration, configuration, configurationViolates DRY

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

2008 JavaOneSM Conference | java.sun.com/javaone | 22

Creating Dynamic SQL FindersMeta Magic with Groovy

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

2008 JavaOneSM Conference | java.sun.com/javaone | 23

Dynamic SQL Finders ExampleBook.metaClass.static.methodMissing = { String name, args ->

if(name.startsWith("findBy") && 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("""select * from ${Book.name} where $prop=?""", [varArgs[0]]) {

results << new Book(title:it.title, author:it.author)

} return results

} Book.metaClass."$name" = callable

return callable.call(args)}

}

Intercept

Cache

Invoke

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

2008 JavaOneSM Conference | java.sun.com/javaone | 24

Real Life Example: GORM in Grailsclass Album { String title String artist Date releaseDate static hasMany = [songs:Song]}class Song { String title Double duration}

id title artist release_date

table - album

id title

duration album_id

table - song

GORM classes, also known as domain classes, go in the domain directory

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

2008 JavaOneSM Conference | java.sun.com/javaone | 25

GORM in ActionQuerying and Persistence with GORM

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

2008 JavaOneSM Conference | java.sun.com/javaone | 26

Dynamic Finders & Criteria

def albums = Album.list()

def recentAlbums = Album.findAllByReleaseDateGreaterThan(new Date()-7)

def albumsStartingWithA = Album.findAllByTitleLike("A%")

def albumsWithSongsAboutSummer = Album.withCriteria { songs { like("title", "%Summmer%") } }

List all records

Form method expressions

Use “like” queries

Construct criteria on the fly to query associations

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

2008 JavaOneSM Conference | java.sun.com/javaone | 27

GORM Features

Dynamic finder and persistence methodsCriteria with a Groovy builderObject-relational Mapping DSL•Caching

•Legacy mapping

•Locking strategy (optimistic/pessimistic)

Built on Hibernate

+

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

2008 JavaOneSM Conference | java.sun.com/javaone | 28

MOP == Goodbye to the DAO

Repetitive, boilerplate DAO logic gone (DRY)Logic exists where it belongs - in the domain (DDD)No direct references to third part dependencies!

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

2008 JavaOneSM Conference | java.sun.com/javaone | 29

The Service Locator / IoC

Pattern of many names•Dependency

Injection

•Service Locator

•Inversion of Control

Abstracts dependency look-up code

http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html

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

2008 JavaOneSM Conference | java.sun.com/javaone | 30

Implications of Service Locator

Requires factory classesClass explosionPromotes anemic domain modelConfiguration, configuration, configuration

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

2008 JavaOneSM Conference | java.sun.com/javaone | 31

Automatic Dependency InjectionAutomatic Dependency Injection with Spring & Grails via Meta-programming

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

2008 JavaOneSM Conference | java.sun.com/javaone | 32

Real Life Example: Spring & Grailsclass 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

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

2008 JavaOneSM Conference | java.sun.com/javaone | 33

Real Life Example: Spring & Grails

Advantages of Meta way•Promotes Domain

Driven Design (DDD)

•No configuration

•DRY

def user = User.get(1)

def book = new Book()

book.buyBook(user)

All dependencies in place even when the new operator is used!

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

2008 JavaOneSM Conference | java.sun.com/javaone | 34

Summary

Meta-programming represents a new way to think about problemsCommon patterns like the DAO and Service Locator are present because of limitations in Java platformGroovy and Grails open doors to declarative programmings, DSLs and Domain Driven Design (DDD)

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

2008 JavaOneSM Conference | java.sun.com/javaone | 35

For More Information

Grails•TS-6457 - Choosing Your Java Technology-Based Web

Framework: A Comparison

•http://grails.org

Groovy•Sessions, Panel Discussions, BOFs: PAN-5435, TS-5815,

TS-6050, TS-5274, BOF-5102, BOF-5110, TS-5693, BOF-5101

•http://groovy.codehaus.org

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

Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) Patterns

Graeme RocherGuillaume LaForgeTS-5793