Groovy & Grails Lightning Talk Raphael Volz Sep. 10, 2007 FZI, Karlsruhe <ul><ul><li>Builds on content from the following ...
Agenda <ul><li>Why should I care ? </li></ul><ul><li>Get Groovy </li></ul><ul><li>Find Grails </li></ul>
Why should I care ? 40-60% User Interface 40-60% Functionality Software Development Effort Variance Max. 20 % User Interfa...
Efficiency Problems in Web Development <ul><li>Many repetitive tasks </li></ul><ul><ul><li>Consider example data flow:  Da...
Java’s biggest strengths in Web development ? <ul><li>VM and Binary Compatibility </li></ul><ul><ul><li>We can build deplo...
Problems with Java in Web Dev’t <ul><li>Verbose </li></ul><ul><ul><li>Many import statements </li></ul></ul><ul><ul><li>Tr...
Agenda <ul><li>Why should I care ? </li></ul><ul><li>Get Groovy </li></ul><ul><li>Find Grails </li></ul>
Get Groovy – An agile dynamic language for Java <ul><li>Integrates with Java </li></ul><ul><ul><li>Can call Java </li></ul...
Groovy // Simplifying Java Syntax (1) <ul><li>Automatically imports </li></ul><ul><li>groovy.lang.* </li></ul><ul><li>groo...
Groovy // New features beyond Java <ul><li>Everything is an object </li></ul><ul><li>Groovy Beans </li></ul><ul><ul><li>Au...
Groovy // Hello World <ul><li>Java </li></ul><ul><li>public class HelloWorld { </li></ul><ul><li>public static void  main ...
Groovy // Closures : Blocks of code as objects <ul><li>def c = { println &quot;hello&quot; } c() </li></ul><ul><li>square ...
Groovy // Calling Java APIS <ul><li>10 liner to get &quot;Google Patent Search&quot; results via HTMLUnit </li></ul><ul><l...
Groovy // Everything is an object <ul><li>def i = 1 </li></ul><ul><li>assert i == new Integer (1) </li></ul><ul><li>def k ...
Groovy // Groovy Beans vs. Java Beans <ul><li>Java </li></ul><ul><li>public class Person { </li></ul><ul><li>private Strin...
Groovy // Simplified List Handling <ul><li>def list = [1,2,3] assert list[0] == 1 assert list[-1] == 3 assert list[1..2] =...
Groovy // List Handling Example <ul><li>public class Filter { </li></ul><ul><li>public static void main( String[] args ) {...
Groovy // Ranges and Maps <ul><li>def sum = 0 for (i in 1..10) sum += i assert sum ==55 </li></ul><ul><li>map = ['rod' : 3...
Basic Sorting <ul><li>list = [ 'dog', 'bird', 'chick' ] </li></ul><ul><li>println( list.sort() )  </li></ul><ul><li>-> [bi...
Sorting JavaBeans <ul><li>class Person { name; age } </li></ul><ul><li>list = [ new Person( name:'Rod', age:33 ), </li></u...
Groovy // Operator Overloading <ul><li>Maps Operators to Methods </li></ul><ul><li>Can be implemented by any class and sub...
Groovy // Advanced switch <ul><li>switch (v) {   case 1: println 'Number one'; break;   case 'test': println 'String test'...
Groovy // Additional Library <ul><li>Adds methods missing from the JDK </li></ul><ul><li>String </li></ul><ul><ul><li>cont...
Groovy // Strings and Regular Expressions <ul><li>def cal = new GregorianCalendar() println &quot;Date: $cal.time&quot; </...
Groovy // GPath path expressions <ul><li>class Person { name; age } </li></ul><ul><li>list = [ new Person( name:'Rod', age...
Groovy // Builders <ul><li>Implemenation of Builder Design Pattern </li></ul><ul><li>Used to construct other things </li><...
Groovy // XML Builder <ul><li>Groovy </li></ul><ul><li>data = ['Rod':  ['Misha':8, 'Bowie':2],   'Eric': ['Poe':4, 'Doc':3...
Groovy // XML Parser <ul><li>XML </li></ul><ul><li><people> </li></ul><ul><li><person name='Rod'> </li></ul><ul><li><pet n...
Groovy // Dynamic Features <ul><li>Meta Object protocol </li></ul><ul><ul><li>Intercept method calls </li></ul></ul><ul><u...
Groovy // Summary <ul><li>Groovy </li></ul><ul><li>Dynamic, flexible Components </li></ul><ul><li>Focus Adaptivity, Protot...
Agenda <ul><li>Why should I care ? </li></ul><ul><li>Get Groovy </li></ul><ul><li>Find Grails </li></ul>
What is GRAILS ? <ul><li>Grails is an MVC Web framework </li></ul><ul><ul><li>Initially inspired by  Ruby on Rails </li></...
GRAILS // Layering on Java Components Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006, p. 7
GRAILS // Step 1
Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006, p. 39
GRAILS // Basic application already there after Step 1
GRAILS // Step 2 - Define a Model <ul><li>•  Now that the skeleton is there, focus on the  model </li></ul><ul><li>•  Mode...
GRAILS // GRAILS Contribution <ul><li>•  Automatically, Grails add dynamic instance &  </li></ul><ul><li>static  </li></ul...
GRAILS // Step 3 Generation of views and controllers •  Once the Book class is created, let´s benefint  from static scaffo...
GRAILS // Scaffolding provides basic GUI for CRUD
GRAILS // Taking control of GRAILS V iew M odel C ontroller grails generate-controller /grails-app/controllers grails gene...
GRAILS // VIEW CONTROLLER INTERACTION Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006
GRAILS // Hibernate interaction •  Hibernate is the de facto ORM solution •  Domain classes are automatically and  transpa...
GRAILS // A more complex domain class  Author  { String  firstName String  lastName def  hasMany = [books:  Book ] String ...
GRAILS // Domain with constraints to keep valid Add an email to Author class  Author  { String email // … static  constrai...
GRAILS // ... and even more constraints •  Many constraints available: blank , creditcard, email,  inList , length, min,  ...
GRAILS // Querying your Model <ul><li>Grails provides various querying mechanisms: </li></ul><ul><li>Dynamic finder method...
GRAILS // Query Examples •  Book. find By Title  (“The Stand”) Book.findByTitle Like (“Harry Pot%”) Book.findByReleaseData...
GRAILS // Views •  Spring MVC  under the hood •  Support for flash scope between requests •  GSP : Groovy alternative to J...
GRAILS // GSP Groovy Server Pages <html> <head>   <meta name=“layout“ content=“main“ />   <title>Book List</title> </head>...
GRAILS // Rich Set of Dynamic Tag Libs •  Logical:  if, else, elseif •  Iterative:  while, each, collect, findAll… •  Link...
GRAILS // URL Convention •  URL mapping convention: controller/action/id http://localhost:8080/library/ book / show / 1 • ...
GRAILS // Controllers provide actions to execute (call) class  Book Controller  { def index = {  redirect(action:list,para...
GRAILS // Chaining and Flashing Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006
GRAILS // Services •  Services are Groovy classes that should contain your  business logic •  Automatic injection of servi...
Grails // Jobs •  You can create recuring events with Quartz  under the hood, configured by Spring •  Again a convention o...
Further Reading
Concluding Notes <ul><li>Slides (largely) inspired by the following two presentations </li></ul><ul><ul><li>Rod Cope and J...
Upcoming SlideShare
Loading in...5
×

2007 09 10 Fzi Training Groovy Grails V Ws

5,455

Published on

2-3 hour introduction to GROOVY and GRAILS given on Sep 10, 2007 for an internal tech talk at the FZI, Germany

Published in: Technology
1 Comment
6 Likes
Statistics
Notes
No Downloads
Views
Total Views
5,455
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
274
Comments
1
Likes
6
Embeds 0
No embeds

No notes for slide

2007 09 10 Fzi Training Groovy Grails V Ws

  1. 1. Groovy & Grails Lightning Talk Raphael Volz Sep. 10, 2007 FZI, Karlsruhe <ul><ul><li>Builds on content from the following presentations </li></ul></ul><ul><ul><li>Rod Cope and James Strachan The Groovy Programming Language Presentation held at JavaOne 2004 </li></ul></ul><ul><ul><li>Graeme Rocher Rapid Web Application Development with Grails Presentation held at JavaOne 2006 </li></ul></ul>
  2. 2. Agenda <ul><li>Why should I care ? </li></ul><ul><li>Get Groovy </li></ul><ul><li>Find Grails </li></ul>
  3. 3. Why should I care ? 40-60% User Interface 40-60% Functionality Software Development Effort Variance Max. 20 % User Interface Min. 80% Functionality Focus : Users  Great Interface  Developer  Gigantic Functionality Typically Research … try to be efficient in programming efforts … ... try to be efficient in UI efforts...
  4. 4. Efficiency Problems in Web Development <ul><li>Many repetitive tasks </li></ul><ul><ul><li>Consider example data flow: Database – Object Representation – Presentation HTML </li></ul></ul><ul><li>Different structure of individual applications </li></ul><ul><ul><li>Hard to understand </li></ul></ul><ul><ul><li>Hard to maintain </li></ul></ul><ul><li>Difficulty to get started </li></ul><ul><ul><li>Many concepts at once: HTML, XML, SQL, JavaScript, Programming Languages … </li></ul></ul><ul><li>Need: </li></ul><ul><li>Simplification </li></ul><ul><li>Standardization </li></ul><ul><li>Capture “Best Practices” </li></ul>
  5. 5. Java’s biggest strengths in Web development ? <ul><li>VM and Binary Compatibility </li></ul><ul><ul><li>We can build deployment units (class, jar, jnlp, war, ear, rar, car) and run them anywhere </li></ul></ul><ul><ul><li>We can easily reuse libraries, APIs and tools </li></ul></ul><ul><ul><ul><li>e.g. high quality BPM, SemWeb, Market APIs </li></ul></ul></ul><ul><li>Lots of reusable software & components & tools </li></ul><ul><li>We can innovate at the source code level if we play nice at the binary level </li></ul>
  6. 6. Problems with Java in Web Dev’t <ul><li>Verbose </li></ul><ul><ul><li>Many import statements </li></ul></ul><ul><ul><li>Try… Catch Nightmare </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><li>Static </li></ul><ul><ul><li>Compile Cycle prevents necessary agility </li></ul></ul><ul><li>Language Concepts </li></ul><ul><ul><li>(in my opinion) slow to embrace “modern” concepts … </li></ul></ul><ul><ul><li>… many of which are helpful for Web Development </li></ul></ul>
  7. 7. Agenda <ul><li>Why should I care ? </li></ul><ul><li>Get Groovy </li></ul><ul><li>Find Grails </li></ul>
  8. 8. Get Groovy – An agile dynamic language for Java <ul><li>Integrates with Java </li></ul><ul><ul><li>Can call Java </li></ul></ul><ul><ul><li>Can be called by Java </li></ul></ul><ul><ul><li>Compiles to Java byte code </li></ul></ul><ul><li>Simplifies syntax of java </li></ul><ul><li>Adds modern language features from Python, Ruby, Dylan and Smalltalk to Java </li></ul><ul><li>Supports DSL (domain specific languages) to compact syntax and increase readability </li></ul><ul><li>Reduces scaffolding code (Web, GUI, database) </li></ul><ul><li>Simplifies testing (mocks up out-of-the-box) </li></ul>
  9. 9. Groovy // Simplifying Java Syntax (1) <ul><li>Automatically imports </li></ul><ul><li>groovy.lang.* </li></ul><ul><li>groovy.util.* </li></ul><ul><li>java.lang.* </li></ul><ul><li>java.util.* </li></ul><ul><li>java.net.* </li></ul><ul><li>java.io.* </li></ul><ul><li>java.math.BigInteger </li></ul><ul><li>java.math.BigDecimal </li></ul>Declare all imports Imports PUBLIC PRIVATE Default scope OPTIONAL MUST Typing of variables OPTIONAL MUST Brackets with method calls OPTIONAL MUST Semicolon after statement Groovy Java Feature
  10. 10. Groovy // New features beyond Java <ul><li>Everything is an object </li></ul><ul><li>Groovy Beans </li></ul><ul><ul><li>Automatically generates get/set methods </li></ul></ul><ul><ul><li>Uses these methods when attributes are read </li></ul></ul><ul><li>Simple Notation of lists and (hash) maps </li></ul><ul><li>Closures - Objects with executable code </li></ul><ul><li>Operator overloading </li></ul><ul><li>Extended Switch </li></ul>
  11. 11. Groovy // Hello World <ul><li>Java </li></ul><ul><li>public class HelloWorld { </li></ul><ul><li>public static void main (String[] args) { </li></ul><ul><li> System.out.println( “Hello World”); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Groovy </li></ul><ul><li>println “Hello World” </li></ul><ul><li>Simplifications applied </li></ul><ul><ul><li>Public optional </li></ul></ul><ul><ul><li>Type information optional </li></ul></ul><ul><ul><li>Every Class knows “println” </li></ul></ul><ul><ul><li>Script needs no class and main method context </li></ul></ul><ul><ul><li>Semicolon optional </li></ul></ul><ul><ul><li>Brackets are optional when calling methods </li></ul></ul>Println “Hello World” class HelloWorld { static void main (String[] args) { System.out.println( “Hello World”); } } class HelloWorld { static main (args) { System.out.println( “Hello World”); } } class HelloWorld { static main (args) { println(“Hello World”); } } println(“Hello World”); Println “Hello World”
  12. 12. Groovy // Closures : Blocks of code as objects <ul><li>def c = { println &quot;hello&quot; } c() </li></ul><ul><li>square = { x -> x * x } assert square(2) == 4 </li></ul><ul><li>square = { it * it } </li></ul><ul><li>3.times { println &quot;hoch!&quot; } </li></ul><ul><li>def sum = 0 1.upto(5) { sum += it } assert sum == 15 </li></ul><ul><li>Use to substitute repeated code blocks </li></ul><ul><li>Closure with parameter </li></ul><ul><li>Closure with default parameter &quot;it&quot; does not require return </li></ul><ul><li>Times function </li></ul><ul><li>upto function </li></ul>Remember LISP ? ... pass around as references, store, execute at arbitratry time ... similar to anonymous inner classes, but nicer syntax and more flexible
  13. 13. Groovy // Calling Java APIS <ul><li>10 liner to get &quot;Google Patent Search&quot; results via HTMLUnit </li></ul><ul><li>1 import com.gargoylesoftware.htmlunit.WebClient </li></ul><ul><li>2 def searchTerm = 'Robot' </li></ul><ul><li>// Patent Search with Google </li></ul><ul><li>3 def client = new WebClient() </li></ul><ul><li>4 def page = client.getPage('http://www.google.com/patents') </li></ul><ul><li>5 def input = page.forms[0].getInputByName('q') </li></ul><ul><li>6 input.valueAttribute = searchTerm </li></ul><ul><li>7 page = page.forms[0].submit() </li></ul><ul><li>8 def results = page.anchors.grep { it.classAttribute == 'big' } </li></ul><ul><li>9 results.each { </li></ul><ul><li>10 println it.hrefAttribute.padRight(30) + ' : ' + it.asText() } </li></ul>Closure
  14. 14. Groovy // Everything is an object <ul><li>def i = 1 </li></ul><ul><li>assert i == new Integer (1) </li></ul><ul><li>def k = i assert i.is(k) assert !(i.is(new Integer(i))) </li></ul><ul><li>No primitive datatypes </li></ul><ul><li>Int, short byte, long real objects </li></ul><ul><li>== is equals() </li></ul><ul><li>Checks equality of objects </li></ul><ul><li>is() checks identity of objects </li></ul>Very, very useful when writing test code !!!
  15. 15. Groovy // Groovy Beans vs. Java Beans <ul><li>Java </li></ul><ul><li>public class Person { </li></ul><ul><li>private String firstName; </li></ul><ul><li>private String nickName; </li></ul><ul><li>public String getFirstName() { </li></ul><ul><li>return firstName; </li></ul><ul><li>} </li></ul><ul><li>public String setFirstName( String n) { </li></ul><ul><li>this.name = n; </li></ul><ul><li>} </li></ul><ul><li>... </li></ul><ul><li>} </li></ul><ul><li>Person p = new Person(); </li></ul><ul><li>p.setFirstName(&quot;Raphael&quot;); </li></ul><ul><li>System.out.println(p.getName()); </li></ul><ul><li>Groovy </li></ul><ul><li>class Person { </li></ul><ul><li>String firstName; </li></ul><ul><li>String nickName </li></ul><ul><li>String getNickName() { </li></ul><ul><li> if (!nickName) return firstName else return nickname </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>def p = new Person(firstName: 'Raphael' ) </li></ul><ul><li>assert p.nickName == 'Raphael' </li></ul>
  16. 16. Groovy // Simplified List Handling <ul><li>def list = [1,2,3] assert list[0] == 1 assert list[-1] == 3 assert list[1..2] == [2,3] </li></ul><ul><li>assert list + [4,5] == [1,2,3,4,5] assert list << 9 == [1,2,3,9] </li></ul><ul><li>assert [1,2,3] - [2] == [1,3] assert [1,2] * 2 == [1,2,1,2] </li></ul><ul><li>def sum = 0 for (i in list) sum+= i asset sum == 6 </li></ul><ul><li>Simplified addressing of list elements avoids calls to len() </li></ul><ul><li>Simplied modification of lists </li></ul><ul><li>Simplified iteration </li></ul>
  17. 17. Groovy // List Handling Example <ul><li>public class Filter { </li></ul><ul><li>public static void main( String[] args ) { </li></ul><ul><li>List list = new java.util.ArrayList(); </li></ul><ul><li>list.add( &quot;Rod&quot; ); list.add( &quot;James&quot; ); list.add( &quot;Chris&quot; ); </li></ul><ul><li>Filter filter = new Filter(); </li></ul><ul><li>List shorts = filter.filterLongerThan( list, 4 ) </li></ul><ul><li>for ( String item : shorts ) { System.out.println( item ); } </li></ul><ul><li>} </li></ul><ul><li>public List filterLongerThan( List list, int length ) { </li></ul><ul><li>List result = new ArrayList(); </li></ul><ul><li>for ( String item : list ) { </li></ul><ul><li>if ( item.length() <= length ) { result.add( item ); } </li></ul><ul><li>} </li></ul><ul><li>return result; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Select all names with at most 3 characters from a list Groovy Java list = [&quot;Rod&quot;, &quot;James&quot;, &quot;Chris&quot;] shorts = list.findAll { it.size() <= 4 } shorts.each { println it }
  18. 18. Groovy // Ranges and Maps <ul><li>def sum = 0 for (i in 1..10) sum += i assert sum ==55 </li></ul><ul><li>map = ['rod' : 33, 'james' : 35] assert map['rod'] == map.rod </li></ul><ul><li>map.joe = 28 assert map == ['rod':33, 'james':35, 'joe':28] </li></ul><ul><li>assert map.subMap(['rod', 'joe']) == ['rod':33, 'joe':28] </li></ul>
  19. 19. Basic Sorting <ul><li>list = [ 'dog', 'bird', 'chick' ] </li></ul><ul><li>println( list.sort() ) </li></ul><ul><li>-> [bird, chick, dog] </li></ul><ul><li>println( list.sort { it.size() }.reverse() ) </li></ul><ul><li>-> [chick, bird, dog] </li></ul>
  20. 20. Sorting JavaBeans <ul><li>class Person { name; age } </li></ul><ul><li>list = [ new Person( name:'Rod', age:33 ), </li></ul><ul><li> new Person( name:'James', age:35 ) ] </li></ul><ul><li>list.sort { | person | person.age } </li></ul><ul><li>list.sort { [ it.name, it.age ] } </li></ul><ul><li>list.sort { | a, b | a.name <=> b.name } </li></ul><ul><li>println( list.sort{it.name}.name ) </li></ul><ul><li>-> [James, Rod] </li></ul><ul><li>println(list.sort{it.name}.name.join(':')) </li></ul><ul><li>-> &quot;James:Rod&quot; </li></ul>
  21. 21. Groovy // Operator Overloading <ul><li>Maps Operators to Methods </li></ul><ul><li>Can be implemented by any class and subsequently used </li></ul><ul><li>Operator Name Method a+b plus a.plus(b) a-b minus a.minus(b) a*b star a.multiply(b) a/b divide a.div(b) a % b modulo a.mod(b) a++ increment a.next() a-- decrement a.previous() a**b power a.power(b) </li></ul>
  22. 22. Groovy // Advanced switch <ul><li>switch (v) { case 1: println 'Number one'; break; case 'test': println 'String test'; break; case 2..15 : println 'in range 2 to 15'; break; case [1, '1', 'One'] : println 'Number one'; break; case ~/A.*/: println 'Starts with A'; break; default: println 'Default Output'; break } </li></ul>
  23. 23. Groovy // Additional Library <ul><li>Adds methods missing from the JDK </li></ul><ul><li>String </li></ul><ul><ul><li>contains(), count(), execute(), padLeft(), center(), padRight(), reverse(), tokenize(), each(), etc. </li></ul></ul><ul><li>Collection </li></ul><ul><ul><li>count(), collect(), join(), each(), reverseEach(), find/All(), min(), max(), inject(), sort(), etc. </li></ul></ul><ul><li>File </li></ul><ul><ul><li>eachFile(), eachLine(), withPrintWriter(), write(), getText(), etc. </li></ul></ul>
  24. 24. Groovy // Strings and Regular Expressions <ul><li>def cal = new GregorianCalendar() println &quot;Date: $cal.time&quot; </li></ul><ul><li>assert 'only letters' ==~ /((w*) *)*/ </li></ul><ul><li>assert 'only letters' =~ /w*/ </li></ul><ul><li>def matcher = 'only letters' =~ /w*/ mather.each { println it } </li></ul><ul><li>Usage of variables in strings </li></ul><ul><li>Matches whole words </li></ul><ul><li>Matches all words </li></ul><ul><li>Print all words </li></ul>
  25. 25. Groovy // GPath path expressions <ul><li>class Person { name; age } </li></ul><ul><li>list = [ new Person( name:'Rod', age:33 ), </li></ul><ul><li> new Person( name:'James', age:35 ) ] </li></ul><ul><li>println( list.find {it.age > 25}.name ) </li></ul><ul><li>-> [Rod] </li></ul><ul><li>println( list.findAll {it.age > 25}.name ) </li></ul><ul><li> -> [Rod, James] </li></ul><ul><li>println( list.any{ it.name.size() > 4 } ) </li></ul><ul><li> -> true </li></ul>
  26. 26. Groovy // Builders <ul><li>Implemenation of Builder Design Pattern </li></ul><ul><li>Used to construct other things </li></ul><ul><li>Groovy provides builders for </li></ul><ul><ul><li>Groovy objects NodeBuilder </li></ul></ul><ul><ul><li>XML,HTML groovy.xml.MarkupBuilder </li></ul></ul><ul><ul><li>Swing SwingBuilder </li></ul></ul><ul><ul><li>Ant AntBuilder </li></ul></ul><ul><li>Can add own Builders (very powerful) </li></ul><ul><ul><li>Who writes one for RDF ? </li></ul></ul><ul><ul><li>Who writes one for OWL ? </li></ul></ul><ul><ul><li>Who writes one for BPEL ? </li></ul></ul>
  27. 27. Groovy // XML Builder <ul><li>Groovy </li></ul><ul><li>data = ['Rod': ['Misha':8, 'Bowie':2], 'Eric': ['Poe':4, 'Doc':3] ] </li></ul><ul><li>xml = new groovy.xml.MarkupBuilder() </li></ul><ul><li>people = xml.people() { </li></ul><ul><li>for ( entry in data ) { person( name: entry.key ) { for ( dog in entry.value) { pet( name:dog.key, age:dog.value ) } } </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>XML </li></ul><ul><li><people> </li></ul><ul><li><person name='Rod'> </li></ul><ul><li><pet name='Bowie' age='2' /> </li></ul><ul><li><pet name='Misha' age='8' /> </li></ul><ul><li></person> </li></ul><ul><li><person name='Eric'> </li></ul><ul><li><pet name='Poe' age='4' /> </li></ul><ul><li><pet name='Doc' age='3' /> </li></ul><ul><li></person> </li></ul><ul><li></people> </li></ul>
  28. 28. Groovy // XML Parser <ul><li>XML </li></ul><ul><li><people> </li></ul><ul><li><person name='Rod'> </li></ul><ul><li><pet name='Bowie' age='2' /> </li></ul><ul><li><pet name='Misha' age='8' /> </li></ul><ul><li></person> </li></ul><ul><li><person name='Eric'> </li></ul><ul><li><pet name='Poe' age='4' /> </li></ul><ul><li><pet name='Doc' age='3' /> </li></ul><ul><li></person> </li></ul><ul><li></people> </li></ul><ul><li>Groovy </li></ul><ul><li>def persons = new XmlParser(). parseText(text); </li></ul><ul><li>assert people.person.pet.name == ['Bowie', 'Misha', 'Poe', 'Doc'] </li></ul>
  29. 29. Groovy // Dynamic Features <ul><li>Meta Object protocol </li></ul><ul><ul><li>Intercept method calls </li></ul></ul><ul><ul><li>Control access to properties </li></ul></ul><ul><ul><li>Control access to classes </li></ul></ul><ul><li>Expando Object </li></ul><ul><ul><li>def e = new Expando () e.a = Math.PI e.m = { println 'I am an expando, this is new method m' } e.m() </li></ul></ul><ul><li>Duck Typing </li></ul><ul><ul><li>class Fish { def swim() { println 'I am a fish' } } class Dolphin {def swim() { println 'I am a dolphin' } } [new Fish(), new Dolphin()].each { it.swim() } </li></ul></ul>
  30. 30. Groovy // Summary <ul><li>Groovy </li></ul><ul><li>Dynamic, flexible Components </li></ul><ul><li>Focus Adaptivity, Prototyping </li></ul><ul><li>Java </li></ul><ul><li>Static, stable Components </li></ul><ul><li>Critical for runtime </li></ul><ul><li>More efficient compiler </li></ul>Typically 50% less development effort (*) Note: (*) Comes at higher debugging expense and 20-90% performance
  31. 31. Agenda <ul><li>Why should I care ? </li></ul><ul><li>Get Groovy </li></ul><ul><li>Find Grails </li></ul>
  32. 32. What is GRAILS ? <ul><li>Grails is an MVC Web framework </li></ul><ul><ul><li>Initially inspired by Ruby on Rails </li></ul></ul><ul><li>Built upon solid bricks & best of breed components </li></ul><ul><ul><li>Spring : IoC, DI, Spring MVC, transactional support, experimental Spring WebFlow… </li></ul></ul><ul><ul><li>Hibernate : ORM, querying mechanism… </li></ul></ul><ul><ul><li>Groovy : for focusing on everything that matters </li></ul></ul><ul><ul><li>And: SiteMesh, Quarz, AJAX frameworks… </li></ul></ul><ul><li>« Convention over configuration »: Focus not on wiring and configuration! </li></ul>
  33. 33. GRAILS // Layering on Java Components Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006, p. 7
  34. 34. GRAILS // Step 1
  35. 35. Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006, p. 39
  36. 36. GRAILS // Basic application already there after Step 1
  37. 37. GRAILS // Step 2 - Define a Model <ul><li>• Now that the skeleton is there, focus on the model </li></ul><ul><li>• Model backed by GORM </li></ul><ul><li>• The model is just a set POGO s </li></ul><ul><li>(Plain Old Groovy Objects) </li></ul><ul><li>• First class of our domain: the books </li></ul><ul><li>class Book { </li></ul><ul><ul><ul><ul><ul><li>String title </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>String author </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>String publisher </li></ul></ul></ul></ul></ul><ul><li>} </li></ul>
  38. 38. GRAILS // GRAILS Contribution <ul><li>• Automatically, Grails add dynamic instance & </li></ul><ul><li>static </li></ul><ul><li>methods to all your domain classes: </li></ul><ul><li>Static methods: Instance methods: </li></ul><ul><ul><li>• Book.get(1) • Book.save() </li></ul></ul><ul><ul><li>• Book.find() • book.validate() </li></ul></ul><ul><ul><li>• Book.findAll() • book.update() </li></ul></ul><ul><ul><li>• bok.delete() </li></ul></ul>
  39. 39. GRAILS // Step 3 Generation of views and controllers • Once the Book class is created, let´s benefint from static scaffolding -> grails generate-all -> grails run-app • A BookController is created, as well as four GSP: ▪ create.gsp ▪ edit.gsp ▪ list.gsp ▪ show.gsp
  40. 40. GRAILS // Scaffolding provides basic GUI for CRUD
  41. 41. GRAILS // Taking control of GRAILS V iew M odel C ontroller grails generate-controller /grails-app/controllers grails generate-views /grails-app/views grails create-domain-class /grails-app/model J obs S ervices /grails-app/jobs /grails-app/services grails create-app 1 2 Web Test Unit Test 4 5 6 grails generate-all 3
  42. 42. GRAILS // VIEW CONTROLLER INTERACTION Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006
  43. 43. GRAILS // Hibernate interaction • Hibernate is the de facto ORM solution • Domain classes are automatically and transparently mapped with Hibernate • 1:1, 1:n & m:n realtionships supported • Various database environments (dev, test, prod) • Default HSQLDB in-memory config • You can even provide your own Hibernate mapping files for legacy schemas • You can also reuse your EJB3 ! V M C S J
  44. 44. GRAILS // A more complex domain class Author { String firstName String lastName def hasMany = [books: Book ] String toString() { “ $firstName $lastName” } } class Book { String title Author author Publisher publisher def belongsTo = [ Publisher , Author ] String toString() { title } } class Publisher { String name def hasMany = [ books: Book ] String toString() { name } } Author has many Books Publisher has many Books V M C S J
  45. 45. GRAILS // Domain with constraints to keep valid Add an email to Author class Author { String email // … static constraints = { email (email: true) } } Add an ISBN to Book class Book { Stringisbn // … static constraints = { isbn (matches: “ [0-9] {9} [0-9X ]”) } } V M C S J
  46. 46. GRAILS // ... and even more constraints • Many constraints available: blank , creditcard, email, inList , length, min, minLength, minSize, matches , max, maxLength, maxSize, notEqual, nullable , range , size, unique , url , validator • And you can create your own closure validator: even( validator: { it % 2 == 0 )} V M C S J
  47. 47. GRAILS // Querying your Model <ul><li>Grails provides various querying mechanisms: </li></ul><ul><li>Dynamic finder methods </li></ul><ul><li>Query by example </li></ul><ul><li>Criteria builders </li></ul><ul><li>Full-blown HQL queries </li></ul>V M C S J
  48. 48. GRAILS // Query Examples • Book. find By Title (“The Stand”) Book.findByTitle Like (“Harry Pot%”) Book.findByReleaseData Between (start, end) Book.findByTitleLike Or ReleaseData LessThan ( “ %Grails%”, someData) • Find by relationship Book.find All By Author ( Author.get(1) ) • Affect sorting Book.findAllbyAuthor(me, [sort:‘title’,order:’asc’] ) V M C S J
  49. 49. GRAILS // Views • Spring MVC under the hood • Support for flash scope between requests • GSP : Groovy alternative to JSP • Dynamic taglib development: no TLD, no configuration, just conventions • Adaptive AJAX tags (Yahoo, Dojo, Prototype) • Customizable layout with SiteMesh • Page fragments through reusable templates • View under grails-app/views V M C S J TIP: Use grails install-templates to install and customize your the templates to be used for generation (templates in ../src/templates)
  50. 50. GRAILS // GSP Groovy Server Pages <html> <head> <meta name=“layout“ content=“main“ /> <title>Book List</title> </head> <body> <a href=“ $ {createLinkTo(dir:’’)} ”>Home</a> <g:link action=“create”> New Book</g:link> <g:if test=“ $ { flash.message } ”> ${flash.message} </g:if> <g:each in=“${bookList}”> $ {it.title} </g:each> </body> </html> V M C S J
  51. 51. GRAILS // Rich Set of Dynamic Tag Libs • Logical: if, else, elseif • Iterative: while, each, collect, findAll… • Linking: link, createLink, createLinkTo • Ajax: remoteFunction, remoteLink, formRemote, submitToRemote… • Form: form, select, currencySelect, localSelect, datePicker, checkBox… • Rendering: render*, layout*, paginate… • Validation: eachError, hasError, message • UI: rich TextEditor… V M C S J
  52. 52. GRAILS // URL Convention • URL mapping convention: controller/action/id http://localhost:8080/library/ book / show / 1 • Scaffolding can be ▪ dynamic (def scaffold = true) ▪ static (code generation) • Controllers pass data to the view through maps • Direct access to parameters • Easy redirect and forward • Can define allowed methods for each action V M C S J
  53. 53. GRAILS // Controllers provide actions to execute (call) class Book Controller { def index = { redirect(action:list,params:params) } def list = { [ bookList: Book.list( params )] } def show = { [ book : Book.get( params.id ) ] } def edit = { def book = Book.get( params.id ) if(!book) { flash.message = “Book ${params.id} not found” redirect(action:list) } else return [ book : book ] } } V M C S J
  54. 54. GRAILS // Chaining and Flashing Source: G. K. Rocher, The Definite Guide to Grails, Apress, 2006
  55. 55. GRAILS // Services • Services are Groovy classes that should contain your business logic • Automatic injection of services in controllers & services simply by declaring a field: class BookController { MySuperService mySuperService } V M C S J
  56. 56. Grails // Jobs • You can create recuring events with Quartz under the hood, configured by Spring • Again a convention on the name and directory • Regular intervals, or cron definitions • class My Job {} def cronExpression = “0 0 24 * * ?” def execute() { print “Job run!” } } V M C S J
  57. 57. Further Reading
  58. 58. Concluding Notes <ul><li>Slides (largely) inspired by the following two presentations </li></ul><ul><ul><li>Rod Cope and James Strachan The Groovy Programming Language Presentation held at JavaOne 2004 </li></ul></ul><ul><ul><li>Graeme Rocher Rapid Web Application Development with Grails Presentation held at JavaOne 2006 </li></ul></ul><ul><li>Get started with... </li></ul><ul><ul><li>GRAILS: grails.codehaus.org </li></ul></ul><ul><ul><li>GROOVY: groovy.codehaus.org </li></ul></ul>
  1. A particular slide catching your eye?

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

×