SlideShare a Scribd company logo
1 of 88
Groovy & Grails
 Kabisa Kennis Sessie - March 9, 2010




 { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Groovy




          { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Groovy

     Groovy is an agile and dynamic language for the JVM
     ā€¢ With a Meta-Object Protocol
     ā€¢ Compiles down to bytecode
     ā€¢ But also supports static typing




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Groovy

     Groovy is an agile and dynamic language for the JVM
     ā€¢ With a Meta-Object Protocol
     ā€¢ Compiles down to bytecode
     ā€¢ But also supports static typing
     Java on steroids:
     ā€¢ Builds upon the strengths of Java, but...
     ā€¢ With power features borrowed from Smalltalk/Python/Ruby
     ā€¢ Makes modern programming features available to Java
       developers with a ļ¬‚at learning curve




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Groovy

     Groovy is an agile and dynamic language for the JVM
     ā€¢ With a Meta-Object Protocol
     ā€¢ Compiles down to bytecode
     ā€¢ But also supports static typing
     Java on steroids:
     ā€¢ Builds upon the strengths of Java, but...
     ā€¢ With power features borrowed from Smalltalk/Python/Ruby
     ā€¢ Makes modern programming features available to Java
       developers with a ļ¬‚at learning curve
     Seamlessly integrates with all existing Java objects and
     libraries


               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Groovy

     Groovy is an agile and dynamic language for the JVM
     ā€¢ With a Meta-Object Protocol
     ā€¢ Compiles down to bytecode
     ā€¢ But also supports static typing
     Java on steroids:
     ā€¢ Builds upon the strengths of Java, but...
     ā€¢ With power features borrowed from Smalltalk/Python/Ruby
     ā€¢ Makes modern programming features available to Java
       developers with a ļ¬‚at learning curve
     Seamlessly integrates with all existing Java objects and
     libraries
     Feels natural to Java developers

               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
From Java to Groovy

     A normal Java program
     public class HelloWorld {

         private String name;

         public void setName(String name) {
           this.name = name;
         }

         public String getName() {
           return name;
         }

         public String greet() {
           return "Hello " + name;
         }

         public static void main(String[] args) {
           HelloWorld helloWorld = new HelloWorld();
           helloWorld.setName("Groovy");
           System.out.println(helloWorld.greet());
         }
     }


                     { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
From Java to Groovy

     A valid Groovy program
     public class HelloWorld {

         private String name;

         public void setName(String name) {
           this.name = name;
         }

         public String getName() {
           return name;
         }

         public String greet() {
           return "Hello " + name;
         }

         public static void main(String[] args) {
           HelloWorld helloWorld = new HelloWorld();
           helloWorld.setName("Groovy");
           System.out.println(helloWorld.greet());
         }
     }


                     { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
From Java to groovy

     But hey?
     Where are the steroids?




              { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
From Java to Groovy

     A Groovier program
     class HelloWorld {
       def name
       def greet() { "Hello ${name}" }
     }

     helloWorld = new HelloWorld(name: "Groovy")
     println helloWorld.greet()




     Dynamic types using the def keyword
     Everything in Groovy is public unless deļ¬ned otherwise
     Automatic getters and setters
     Semicolons at end-of-line are optional
     Variable interpolation through GStrings
     Return keyword is optional

                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
From Java to Ruby

     A Ruby program
     class HelloWorld < Struct.new(:name)
       def greet
         "Hello #{name}"
       end
     end

     hello_world = HelloWorld.new("Ruby")
     puts hello_world.greet




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
JVM Languages




                { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Joint Compilation

     Total interoperability


         Java Interface                            Groovy Interface


         Groovy Class                                     Java Class


           Java Class                                 Groovy Class


               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Native Syntax Constructs

     Lists
     ā€¢ Java: int[] numbers = new int[] { 1, 2, 3 };
     ā€¢ Groovy: numbers = [1, 2, 3]
     ā€¢ Ruby: numbers = [1, 2, 3]




                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Native Syntax Constructs

     Lists
     ā€¢ Java: int[] numbers = new int[] { 1, 2, 3 };
     ā€¢ Groovy: numbers = [1, 2, 3]
     ā€¢ Ruby: numbers = [1, 2, 3]

     Maps/Hashes
     ā€¢ Java: Map countries = new HashMap();
              countries.put("nl", "Netherlands");
              countries.put("be", "Belgium");

     ā€¢ Groovy: countries = [nl: "Netherlands", be: "Belgium"]
     ā€¢ Ruby: countries = {:nl => "Netherlands", :be => "Belgium"}



                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Iterating

      Looping
      ā€¢ Groovy: for (i in list) { println i }
      ā€¢ Ruby: for i in list
                  puts i
                end




                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Iterating

      Looping
      ā€¢ Groovy: for (i in list) { println i }
      ā€¢ Ruby: for i in list
                  puts i
                end




      Looping with closures
      ā€¢ Groovy: list.each { println it }
      ā€¢ Ruby: list.each {|i| puts i }




                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
GStrings

     GStrings are interpolated strings
     ā€¢ Placeholder variables are replaced
     ā€¢ You can have multiline strings
       def person = "Marcel"
       def letter = """
           ${new Date()}
           Hello ${person},
           You have won 100,000,000GBP in the UK lottery!
       """




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Special Operators

     Elvis operator
     ā€¢ A shortening of Java's ternary operator
       def displayName = user.name ? user.name : "Anonymous"
       def displayName = user.name ?: "Anonymous"




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Special Operators

     Elvis operator
     ā€¢ A shortening of Java's ternary operator
        def displayName = user.name ? user.name : "Anonymous"
        def displayName = user.name ?: "Anonymous"


     Safe Navigation Operator
     ā€¢ Java: String postalCode = null;
              if (user != null) {
                Address address = user.getAddress();
                if (address != null) {
                  postalCode = address.getPostalCode();
                  if (postalCode != null) {
                    postalCode = postalCode.toUpperCase();
                  }
                }
              }

     ā€¢ Groovy: def postalCode = user?.address?.postalCode?.toUpperCase()
                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
The Groovy Truth

    Booleans
    def a = true
    def b = false
    assert a
    assert !b

    Collections
    def numbers = []
    assert !numbers // false, as numbers is an empty collection
    numbers = [1, 2, 3]
    assert numbers // true, as numbers is not empty

    Strings
    assert 'This is true'
    assert !''

    Numbers
    assert !0 // yeah, 0s are false, like in Perl
    assert 1 // this is also true for all other number types

    Objects
    assert new Object()


                    { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Meta Programming

    You can add methods and properties to any Object at
    runtime
    You can intercept method calls and property access
    (similar to AOP)
    def s = "Hello Groovy"
    println s
    println s.toUpperCase() // standard JDK method
    String.metaClass {
      toMixedCase { delegate.toUpperCase() } // add method
      toUpperCase { delegate.toLowerCase() } // override existing method
      multiply { i -> delegate * i } // add method with argument
    }
    println s.toMixedCase()
    println s.toUpperCase()
    println s.multiply(3)




                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Builders

     Simple mechanism for creating any create any structured
     tree of data
     ā€¢ You can use out-of-the-box builders
     ā€¢ You can create your own builders
           import groovy.xml.MarkupBuilder

           def mkp = new MarkupBuilder()
           mkp.html {
             head {
               title "Kabisa ICT"
             }
             body {
               div(class: "container") {
                 p "Welcome to Kabisa ICT"
               }
             }
           }

           println mkp



                     { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Do you want to be Groovy?




                                    ?
              { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Grails




          { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Grails

     Full-stack web application framework inspired by
     ā€¢ Code by Convention
     ā€¢ Donā€™t Repeat Yourself (DRY)
     ā€¢ Ruby on Rails, Django, TurboGears




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Grails

     Full-stack web application framework inspired by
     ā€¢ Code by Convention
     ā€¢ Donā€™t Repeat Yourself (DRY)
     ā€¢ Ruby on Rails, Django, TurboGears
     Built on the shoulders of Giants
     ā€¢ Java/JEE
     ā€¢ Spring framework
     ā€¢ Hibernate




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Grails

     Full-stack web application framework inspired by
     ā€¢ Code by Convention
     ā€¢ Donā€™t Repeat Yourself (DRY)
     ā€¢ Ruby on Rails, Django, TurboGears
     Built on the shoulders of Giants
     ā€¢ Java/JEE
     ā€¢ Spring framework
     ā€¢ Hibernate
     Reduces complexity




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Grails

     Full-stack web application framework inspired by
     ā€¢ Code by Convention
     ā€¢ Donā€™t Repeat Yourself (DRY)
     ā€¢ Ruby on Rails, Django, TurboGears
     Built on the shoulders of Giants
     ā€¢ Java/JEE
     ā€¢ Spring framework
     ā€¢ Hibernate
     Reduces complexity
     Increases productivity



               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Introduction to Grails

     Full-stack web application framework inspired by
     ā€¢ Code by Convention
     ā€¢ Donā€™t Repeat Yourself (DRY)
     ā€¢ Ruby on Rails, Django, TurboGears
     Built on the shoulders of Giants
     ā€¢ Java/JEE
     ā€¢ Spring framework
     ā€¢ Hibernate
     Reduces complexity
     Increases productivity
     ā€œJavaā€


               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Full-stack Web Application Framework

     Easy Object Relational Mapping (ORM) based on
     Hibernate
     View layer with Groovy Server Pages (GSP), dynamic Tag
     Libraries and SiteMesh
     Controller layer based on Spring MVC / Spring Web Flow
     Dependency Injection (DI) using the Spring Container
     Transactional service layer based on Springā€™s transaction
     abstraction
     Internationalization (i18n) based on Springā€™s
     MessageSource concept
     Embedded Tomcat servlet container for on the ļ¬‚y
     reloading

              { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
About SpringSource, G2One and VMware

    First version of Spring framework was released in 2003




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
About SpringSource, G2One and VMware

    First version of Spring framework was released in 2003
    SpringSource was founded in 2004




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
About SpringSource, G2One and VMware

    First version of Spring framework was released in 2003
    SpringSource was founded in 2004
    G2One (The Groovy Grails Company) was founded in
    2007 by the Groovy and Grails project leads




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
About SpringSource, G2One and VMware

    First version of Spring framework was released in 2003
    SpringSource was founded in 2004
    G2One (The Groovy Grails Company) was founded in
    2007 by the Groovy and Grails project leads
    In November 2008 G2One was acquired by SpringSource




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
About SpringSource, G2One and VMware

    First version of Spring framework was released in 2003
    SpringSource was founded in 2004
    G2One (The Groovy Grails Company) was founded in
    2007 by the Groovy and Grails project leads
    In November 2008 G2One was acquired by SpringSource
    In August 2009 SpringSource was acquired by VMware for
    $420m




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
About SpringSource, G2One and VMware

    First version of Spring framework was released in 2003
    SpringSource was founded in 2004
    G2One (The Groovy Grails Company) was founded in
    2007 by the Groovy and Grails project leads
    In November 2008 G2One was acquired by SpringSource
    In August 2009 SpringSource was acquired by VMware for
    $420m
    SpringSource is now a division of VMware




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Grails Stack


                     Grails
                                                        Other
   JEE         Spring            Hibernate
                                                       Libraries
                                                                         Groovy

                                  Java Development Kit
     Java Language
                                          (JDK)


                        Java Virtual Machine

               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Grails Command Line
    grails   create-app book
    grails   create-domain-class nl.kabisa.book
    grails   create-controller nl.kabisa.book
    grails   generate-all nl.kabisa.book
    grails   install plugin acegi
    grails   run-app
    grails   test-app
    grails   war
    grails   console
    ..
    Custom commands (scripts) can be added to project


             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Grails Project Breakdown
     grails-app               Top level source folder with Grails artifacts
     ā€¢   conf                    Conļ¬guration sources
     ā€¢   controlllers            Controller layer
     ā€¢   domain                  Model layer
     ā€¢   i18n                    Internationalized Resource Bundles
     ā€¢   services                Service layer
     ā€¢   taglib                  Dynamic Tag Libraries
     ā€¢   views                   Groovy Server Pages (GSP)
     web-app                  Stylesheets, Javascript, ...
     scripts                  Custom command-line scripts
     src                      Other project sources
     ā€¢ groovy                    Other Groovy project sources
     ā€¢ java                      Other Java project sources
     lib                      3th Party Libraries
     test                     Unit, Integration and Functional tests

                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Conļ¬guration per environment
   dataSource {
     pooled = true
     driverClassName = "org.hsqldb.jdbcDriver"
     username = "sa"
     password = ""
   }
   hibernate {
     cache.use_second_level_cache = true
     cache.use_query_cache = true
     cache.provider_class = "net.sf.ehcache.hibernate.EhCacheProvider"
   }
   // environment specific settings
   environments {
     development {
       dataSource {
         dbCreate = "create-drop" // one of 'create', 'create-drop','update'
         url = "jdbc:hsqldb:mem:devDB"
       }
     }
     production {
       dataSource {
         dbCreate = "update"
         url = "jdbc:hsqldb:file:prodDb;shutdown=true"
       }
     }
   }

                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
GORM

   GORM (Grails Object Relational Mapping)
   ā€¢   Domain Modeling
   ā€¢   Basic CRUD methods
   ā€¢   Dynamic Finders
   ā€¢   Events and Auto Timestamping
   ā€¢   Validations
   ā€¢   Custom ORM mappings with ORM Domain Speciļ¬c Language




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
GORM

   GORM (Grails Object Relational Mapping)
   ā€¢   Domain Modeling
   ā€¢   Basic CRUD methods
   ā€¢   Dynamic Finders
   ā€¢   Events and Auto Timestamping
   ā€¢   Validations
   ā€¢   Custom ORM mappings with ORM Domain Speciļ¬c Language
   NO MIGRATIONS
   ā€¢ LiquiBase Plugin




             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
GORM

   GORM (Grails Object Relational Mapping)
   ā€¢   Domain Modeling
   ā€¢   Basic CRUD methods
   ā€¢   Dynamic Finders
   ā€¢   Events and Auto Timestamping
   ā€¢   Validations
   ā€¢   Custom ORM mappings with ORM Domain Speciļ¬c Language
   NO MIGRATIONS
   ā€¢ LiquiBase Plugin
   Domain model is OOP based, not database based (as in
   Rails)


             { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Domain Classes

   Grails                                            Rails
   class Book {                                      class User < ActiveRecord::Base
     String title                                    end
     String isbn
     BigDecimal price
   }




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Domain Classes

   Grails                                            Rails
   class Author {                                    class Auhor < ActiveRecord::Base
     static hasMany = [books: Book]                    has_many :books
     String name                                     end
   }


   class Book {                                      class Book < ActiveRecord::Base
     static belongsTo = [author: Author]               belongs_to :author
     String title                                    end
     String isbn
     BigDecimal price
   }




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Validations, Events, Auto Timestamping, Mappings
   class Book {
     static belongsTo = [author: Author]

       String title
       String isbn
       BigDecimal price
       Date dateCreated
       Date lastUpdated

       def beforeInsert() {
         dateCreated = new Date()
       }

       static constraints = {
         title(blank: false, maxSize: 100)
         isbn(blank: false, matches: "[0-9]13", minSize: 13, maxSize: 13, unique: true)
         price(nullable: true, min: 0.0, max: 9999.99, scale: 2)
       }

       static mapping = {
         table "books"
         price column: "sales_price"
       }
   }




                      { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Basic CRUD methods

   Grails                                            Rails
   // create                                         # create
   def a = new Author(name: "Rowling")               a = Author.new(:name => "Rowling")
   a.save()                                          a.save

   // read                                           # read
   def a = Author.get(1)                             a = Author.find(1)

   // update                                         # update
   def a = Author.get(1)                             a = Author.find(1)
   a.name = "J.K. Rowling"                           a.name = "J.K. Rowling"
   a.save()                                          a.save

   // delete                                         # delete
   def a = Author.get(1)                             a = Author.find(1)
   a.delete()                                        a.delete




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Querying with GORM
   // query all authors
   def authors = Author.list()

   // pagination
   def authors = Author.list(max: 10, offset: 20)

   // sorting
   def authors = Author.list(order: "name", sort: "desc")

   // pagination and sorting
   def authors = Author.list(max: 10, offset: 20, order: "name", sort: "desc")




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
GORM Dynamic Finders

    FindBy (ļ¬rst result)
    FindAllBy (all results)
    Comparators
    ā€¢ LessThan, LessThanEquals, GreaterThan, GreaterThanEquals
    ā€¢ Like, Ilike, NotEqual, InList, Between
    ā€¢ IsNotNull, IsNull
    def author = Author.findByName("J.K. Rowling")

    def books = Book.findAllByTileIlike("harry p%")

    def books = Book.findAllByPriceLessThan(10.0)

    def books = Book.findAllByTitleLikeAndPriceBetween("Harry P%", 10.0, 20.0)




                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Criteria and HQL
   // using criteria builder
   def c = Book.createCriteria()
   def books = c {
       like("title", "Harry P%")
       and {
           between("price", 10.0, 20.0)
       }
       order("title", "asc")
   }

   // using HQL (Hibernate Query Language)
   def books = Book.findAll("from Book as b where b.title like ?", ["Harry P%"])




                    { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Controllers

     Responsible for handling requests
     Render or prepare responses
     Bind request data to the model (including type conversions)
     Support interceptors
     Support content negotiation
     class SomeController {
       def action = {
         // do controller logic
         // create model
         return model
       }
     }




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Controllers

     Grails
     class BookController {
       def list = {
         [bookList: Book.list()]
       }
     }


     <ul>
         <g:each in="${bookList}">
             <li>${it.title}</li>
         </g:each>
     </ul>




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Controllers

     Grails
     class BookController {
       def list = {
         [bookList: Book.list()]
       }
     }


     <ul>
         <g:each in="${bookList}">
             <li>${it.title}</li>
         </g:each>
     </ul>



     Rails
     class BooksController < ApplicationController
       def list
         @books = Book.all
       end
     end




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Example Controller
   class BookController {

       static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

       def index = { redirect(action: "list", params: params) }

      def list = {
          [bookInstanceList: Book.list(params), bookInstanceTotal: Book.count()]
      }

      def create = {
          def bookInstance = new Book()
          bookInstance.properties = params
          return [bookInstance: bookInstance]
      }

      def save = {
          def bookInstance = new Book(params)
          if (bookInstance.save()) {
              redirect(action: "show", id: bookInstance.id)
          }
          else {
              render(view: "create", model: [bookInstance: bookInstance])
          }
      }


                    { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Example Controller
     def edit = {
         def bookInstance = Book.get(params.id)
         if (!bookInstance) {
             redirect(action: "list")
         }
         else {
             return [bookInstance: bookInstance]
         }
     }

     def update = {
         def bookInstance = Book.get(params.id)
         if (bookInstance) {
             bookInstance.properties = params
             if (!bookInstance.hasErrors() && bookInstance.save()) {
                 redirect(action: "show", id: bookInstance.id)
             }
             else {
                 render(view: "edit", model: [bookInstance: bookInstance])
             }
         }
         else {
             redirect(action: "list")
         }
     }


                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Example Controller
       def delete = {
           def bookInstance = Book.get(params.id)
           if (bookInstance) {
               bookInstance.delete(flush: true)
               redirect(action: "list")
           }
           else {
               redirect(action: "list")
           }
       }

       def show = {
           def bookInstance = Book.get(params.id)
           if (!bookInstance) {
               redirect(action: "list")
           }
           else {
               [bookInstance: bookInstance]
           }
       }

       def beforeInterceptor = { // do something }

       def afterInterceptor = { // do something }
   }


                    { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
XML Responses
   def list = {
       def bookList = Book.list()
       render(contentType: "text/xml") {
           books {
                for (b in bookList) {
                    book(title: b.title)
               }
           }
       }
   }

   // automatic xml marshalling
   def list = {
       render Book.list() as XML
   }




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Content Negotiation

     You can use HTTP Accept Header
     You can use format request paramter (/book/list?format=xml)
     You can use URI extension (/book/list.xml)
     Use the withFormat method to deal with different
     formats
     class BookController {
         def list = {
             def books = Book.list()
             withFormat {
                 html bookList:books
                 js { render "alert('hello')" }
                 xml { render books as XML }
             }
         }
     }




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Views

    Groovy Server Pages (GSP)
    ā€¢ Similar like technologies like JSP and ASP
    ā€¢ A mix of markup and GSP tags
    ā€¢ Groovy code can be embedded, but is discouraged




              { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Views

    Groovy Server Pages (GSP)
    ā€¢ Similar like technologies like JSP and ASP
    ā€¢ A mix of markup and GSP tags
    ā€¢ Groovy code can be embedded, but is discouraged
    NO HAML :-(




              { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Views

    Groovy Server Pages (GSP)
    ā€¢ Similar like technologies like JSP and ASP
    ā€¢ A mix of markup and GSP tags
    ā€¢ Groovy code can be embedded, but is discouraged
    NO HAML :-(
    def show = {
        [book: Book.get(params.id)]
    }




                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Views

    Groovy Server Pages (GSP)
    ā€¢ Similar like technologies like JSP and ASP
    ā€¢ A mix of markup and GSP tags
    ā€¢ Groovy code can be embedded, but is discouraged
    NO HAML :-(
    def show = {
        [book: Book.get(params.id)]
    }


    <%= book.title %>




                  { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Views and Tag Libraries

     Embedded Groovy code
     <html>
         <body>
             <% [1, 2, 3, 4].each { num ->
                 if (num > 2) { %>
                     <p><%= "Hello ${num}!" %></p>
             <% }
                } %>
         </body>
     </html>




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Views and Tag Libraries

     Embedded Groovy code
     <html>
         <body>
             <% [1, 2, 3, 4].each { num ->
                 if (num > 2) { %>
                     <p><%= "Hello ${num}!" %></p>
             <% }
                } %>
         </body>
     </html>

     Use Tag Libraries instead
     <html>
         <body>
             <g:each in="${[1, 2, 3, 4]}" var="num">
                 <g:if test="${num > 2}">
                     <p>Number ${num}</p>
                 </g:if>
             </g:each>
         </body>
     </html>




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails
     Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>




                 { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails
     Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>
     Links and Resources
     <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
     <g:link controller="book" action="list">Book List</g:link>




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails
     Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>
     Links and Resources
     <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
     <g:link controller="book" action="list">Book List</g:link>

     Forms and Fields
     <g:textField name="title" value="${bookInstance.title}" />
     <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" />
     <g:datePicker name="publishDate" value="${bookInstance.publishDate}" />




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails
     Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>
     Links and Resources
     <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
     <g:link controller="book" action="list">Book List</g:link>

     Forms and Fields
     <g:textField name="title" value="${bookInstance.title}" />
     <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" />
     <g:datePicker name="publishDate" value="${bookInstance.publishDate}" />

     Formatting




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails
     Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>
     Links and Resources
     <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
     <g:link controller="book" action="list">Book List</g:link>

     Forms and Fields
     <g:textField name="title" value="${bookInstance.title}" />
     <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" />
     <g:datePicker name="publishDate" value="${bookInstance.publishDate}" />

     Formatting
     Ajax



                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails
     Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>
     Links and Resources
     <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
     <g:link controller="book" action="list">Book List</g:link>

     Forms and Fields
     <g:textField name="title" value="${bookInstance.title}" />
     <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" />
     <g:datePicker name="publishDate" value="${bookInstance.publishDate}" />

     Formatting
     Ajax
     and more...

                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Core Tag Libraries

     Much more attractive than embedded Groovy code
     Like helpers in Rails
     Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>
     Links and Resources
     <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
     <g:link controller="book" action="list">Book List</g:link>

     Forms and Fields
     <g:textField name="title" value="${bookInstance.title}" />
     <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" />
     <g:datePicker name="publishDate" value="${bookInstance.publishDate}" />

     Formatting
     Ajax
     and more...

                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Custom Tag Libraries

     Very complex and painful in standard Java
     ā€¢ Complex interfaces to implement
     ā€¢ Additional Tag Library Descriptors (XML) must be written
     ā€¢ And need to be conļ¬gured in web.xml




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Custom Tag Libraries

     Very complex and painful in standard Java
     ā€¢ Complex interfaces to implement
     ā€¢ Additional Tag Library Descriptors (XML) must be written
     ā€¢ And need to be conļ¬gured in web.xml
     But so easy in Grails
     class SimpleTagLib {
         static namespace = "auth"
         def isAdmin = { attrs, body ->
             if (attrs.user.admin)
                 out << body()
         }
     }


     <auth:isAdmin user="${session.user}">
         // some restricted content
     </auth:isAdmin>




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Views and Layouts
   <html>
     <head>
       <meta name="layout" content="main" />
       <title>Book List</title>
     </head>
     <body>
       <div class="nav">
          <span><a class="home" href="${createLink(uri: '/')}">Home</a></span>
          <span><g:link class="create" action="create">New Book</g:link></span>
       </div>
       <div class="body">
          <div class="list">
            <table>
              <g:each in="${bookInstanceList}" status="i" var="bookInstance">
                 <tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
                   <td><g:link action="show" id="${bookInstance.id}">${bookInstance.id}</
   g:link></td>
                   <td>${bookInstance.title}</td>
                 </tr>
              </g:each>
            </table>
          </div>
       </div>
     </body>
   </html>


                    { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
URL Mappings

   Used for mapping URLā€™s to controllers
    ā€¢ Similar like routes in Rails
    ā€¢ Default convention is /controller/action/id




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
URL Mappings

   Used for mapping URLā€™s to controllers
     ā€¢ Similar like routes in Rails
     ā€¢ Default convention is /controller/action/id
   class UrlMappings {
       static mappings = {
           "/product" (controller: "product", action: "list")
           "/product/$id" (controller: "product")
           "/$blog/$year/$month/$day/$id" (controller: "blog", action: "show")
       }
   }




                   { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Filters

      Controllers already support ļ¬ne grained interceptors but
      these are difļ¬cult to manage in larger applications




               { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Filters

      Controllers already support ļ¬ne grained interceptors but
      these are difļ¬cult to manage in larger applications
      Use ļ¬lters instead
      ā€¢   A Domain Speciļ¬c Language is available for deļ¬ning ļ¬lters
      ā€¢   You can deļ¬ne scopes (all controllers, a speciļ¬c controller/action, URI pattern)
      ā€¢   You can deļ¬ne interceptor types (before, after, afterView)
      ā€¢   You can use variables (params, request, response, session, grailsApplication)




                    { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Filters

      Controllers already support ļ¬ne grained interceptors but
      these are difļ¬cult to manage in larger applications
      Use ļ¬lters instead
      ā€¢   A Domain Speciļ¬c Language is available for deļ¬ning ļ¬lters
      ā€¢   You can deļ¬ne scopes (all controllers, a speciļ¬c controller/action, URI pattern)
      ā€¢   You can deļ¬ne interceptor types (before, after, afterView)
      ā€¢   You can use variables (params, request, response, session, grailsApplication)
      class SecurityFilters {
         def filters = {
             loginCheck(controller: '*', action: '*') {
                 before = {
                    if(!session.user && !actionName.equals('login')) {
                        redirect(action: 'login')
                         return false
                     }
                 }
             }
         }
      }
                    { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Services

     Donā€™t put core/reusable logic in controllers, but instead
     use the service layer
     Services are by default transactional
     Services can be scoped
     class BookService {

           static scope = "singleton" // other options include prototype, request, session
           static transactional = true

           def doSomething() {
               // TODO: implement
           }
     }




                     { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Plugins

     Grails is designed with a plugin architecture in mind
     Grails core features are built on plugins
     Plugins can provide basic artifacts
     ā€¢ Domain Classes, Tag Libraries, Services, ...
     Plugins can provide new artifact types
     Plugins can hook into build events
     Plugins can hook into runtime conļ¬guration
     Plugins can add dynamic methods at runtime




                { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Plugins

     Spring Security                              LDAP
     Quartz                                       Commentable
     Searchable                                   Selenium RC
     Mail                                         Fixtures
     Canoo Webtest                                ReCaptcha
     GWT                                          LiquiBase
     Feeds                                        GORM-JPA
     Taggable                                     iWebKit
     Rateable                                     Webdriver
     XFire                                        Axis2
     Spring WS                                    Wicket

              { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Tooling

     Integrated Development Environments
     ā€¢ SpringSource Tool Suite (STS)
     ā€¢ NetBeans
     ā€¢ IDEA IntelliJ
     TextMate




                { Agile Development } { Ruby on Rails } { Java / J2EE }
Groovy & Grails
Discussion & Demo




                             !?
             { Agile Development } { Ruby on Rails } { Java / J2EE }
{ Agile Development } { Ruby on Rails } { Java / J2EE }

More Related Content

What's hot

GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf
Ā 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8confGR8Conf
Ā 
Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020
Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020
Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020Johnny Sung
Ā 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageHoat Le
Ā 
Whats New In Groovy 1.6?
Whats New In Groovy 1.6?Whats New In Groovy 1.6?
Whats New In Groovy 1.6?Guillaume Laforge
Ā 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
Ā 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovypaulbowler
Ā 
Groovy overview, DSLs and ecosystem - Mars JUG - 2010
Groovy overview, DSLs and ecosystem - Mars JUG - 2010Groovy overview, DSLs and ecosystem - Mars JUG - 2010
Groovy overview, DSLs and ecosystem - Mars JUG - 2010Guillaume Laforge
Ā 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
Ā 
re-frame Ć  la spec
re-frame Ć  la specre-frame Ć  la spec
re-frame Ć  la specKent Ohashi
Ā 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Guillaume Laforge
Ā 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailszenMonkey
Ā 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?Guillaume Laforge
Ā 
Groovy & Grails
Groovy & GrailsGroovy & Grails
Groovy & GrailsMichael Yan
Ā 
Groovy AST Demystified
Groovy AST DemystifiedGroovy AST Demystified
Groovy AST DemystifiedAndres Almiray
Ā 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
Ā 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
Ā 

What's hot (20)

GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
Ā 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
Ā 
Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020
Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020
Flutter ę˜Æ什éŗ¼ļ¼Ÿē”Ø Flutter ꜃ēœåˆ°ę™‚é–“å—Žļ¼Ÿ @ GDG Devfest2020
Ā 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming Language
Ā 
Whats New In Groovy 1.6?
Whats New In Groovy 1.6?Whats New In Groovy 1.6?
Whats New In Groovy 1.6?
Ā 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
Ā 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovy
Ā 
Greach 2014 - Metaprogramming with groovy
Greach 2014 - Metaprogramming with groovyGreach 2014 - Metaprogramming with groovy
Greach 2014 - Metaprogramming with groovy
Ā 
Groovy overview, DSLs and ecosystem - Mars JUG - 2010
Groovy overview, DSLs and ecosystem - Mars JUG - 2010Groovy overview, DSLs and ecosystem - Mars JUG - 2010
Groovy overview, DSLs and ecosystem - Mars JUG - 2010
Ā 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
Ā 
re-frame Ć  la spec
re-frame Ć  la specre-frame Ć  la spec
re-frame Ć  la spec
Ā 
OpenLogic
OpenLogicOpenLogic
OpenLogic
Ā 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Ā 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And Grails
Ā 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
Ā 
Groovy & Grails
Groovy & GrailsGroovy & Grails
Groovy & Grails
Ā 
Groovy AST Demystified
Groovy AST DemystifiedGroovy AST Demystified
Groovy AST Demystified
Ā 
Dart
DartDart
Dart
Ā 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012
Ā 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
Ā 

Similar to Groovy & Grails

Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
Ā 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle GroovyDeepak Bhagat
Ā 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy TestingAndres Almiray
Ā 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
Ā 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
Ā 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyAndres Almiray
Ā 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyAndres Almiray
Ā 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails IntroductionEric Weimer
Ā 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovymanishkp84
Ā 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
Ā 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java DevelopersAndres Almiray
Ā 
Groovy Up Your Code
Groovy Up Your CodeGroovy Up Your Code
Groovy Up Your CodePaulo TraƧa
Ā 
Ugo Cei Presentation
Ugo Cei PresentationUgo Cei Presentation
Ugo Cei PresentationRubyOnRails_dude
Ā 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to GroovyKevin H.A. Tan
Ā 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
Ā 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for JavaCharles Anderson
Ā 
Startup groovysession1
Startup groovysession1Startup groovysession1
Startup groovysession1kyon mm
Ā 
Dslė”œ ė§Œė‚˜ėŠ” groovy
Dslė”œ ė§Œė‚˜ėŠ” groovyDslė”œ ė§Œė‚˜ėŠ” groovy
Dslė”œ ė§Œė‚˜ėŠ” groovySeeyoung Chang
Ā 

Similar to Groovy & Grails (20)

Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
Ā 
JRuby Basics
JRuby BasicsJRuby Basics
JRuby Basics
Ā 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
Ā 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
Ā 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
Ā 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
Ā 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
Ā 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
Ā 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails Introduction
Ā 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovy
Ā 
Groovy intro
Groovy introGroovy intro
Groovy intro
Ā 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Ā 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
Ā 
Groovy Up Your Code
Groovy Up Your CodeGroovy Up Your Code
Groovy Up Your Code
Ā 
Ugo Cei Presentation
Ugo Cei PresentationUgo Cei Presentation
Ugo Cei Presentation
Ā 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
Ā 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
Ā 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
Ā 
Startup groovysession1
Startup groovysession1Startup groovysession1
Startup groovysession1
Ā 
Dslė”œ ė§Œė‚˜ėŠ” groovy
Dslė”œ ė§Œė‚˜ėŠ” groovyDslė”œ ė§Œė‚˜ėŠ” groovy
Dslė”œ ė§Œė‚˜ėŠ” groovy
Ā 

Recently uploaded

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
Ā 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
Ā 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfdanishmna97
Ā 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityVictorSzoltysek
Ā 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
Ā 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
Ā 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
Ā 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingWSO2
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
Ā 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Christopher Logan Kennedy
Ā 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
Ā 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
Ā 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
Ā 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
Ā 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
Ā 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
Ā 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
Ā 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
Ā 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
Ā 

Recently uploaded (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
Ā 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
Ā 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
Ā 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
Ā 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
Ā 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
Ā 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
Ā 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
Ā 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
Ā 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
Ā 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Ā 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
Ā 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
Ā 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
Ā 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
Ā 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
Ā 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
Ā 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
Ā 

Groovy & Grails

  • 1. Groovy & Grails Kabisa Kennis Sessie - March 9, 2010 { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 2. Groovy & Grails Groovy { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 3. Groovy & Grails Introduction to Groovy Groovy is an agile and dynamic language for the JVM ā€¢ With a Meta-Object Protocol ā€¢ Compiles down to bytecode ā€¢ But also supports static typing { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 4. Groovy & Grails Introduction to Groovy Groovy is an agile and dynamic language for the JVM ā€¢ With a Meta-Object Protocol ā€¢ Compiles down to bytecode ā€¢ But also supports static typing Java on steroids: ā€¢ Builds upon the strengths of Java, but... ā€¢ With power features borrowed from Smalltalk/Python/Ruby ā€¢ Makes modern programming features available to Java developers with a ļ¬‚at learning curve { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 5. Groovy & Grails Introduction to Groovy Groovy is an agile and dynamic language for the JVM ā€¢ With a Meta-Object Protocol ā€¢ Compiles down to bytecode ā€¢ But also supports static typing Java on steroids: ā€¢ Builds upon the strengths of Java, but... ā€¢ With power features borrowed from Smalltalk/Python/Ruby ā€¢ Makes modern programming features available to Java developers with a ļ¬‚at learning curve Seamlessly integrates with all existing Java objects and libraries { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 6. Groovy & Grails Introduction to Groovy Groovy is an agile and dynamic language for the JVM ā€¢ With a Meta-Object Protocol ā€¢ Compiles down to bytecode ā€¢ But also supports static typing Java on steroids: ā€¢ Builds upon the strengths of Java, but... ā€¢ With power features borrowed from Smalltalk/Python/Ruby ā€¢ Makes modern programming features available to Java developers with a ļ¬‚at learning curve Seamlessly integrates with all existing Java objects and libraries Feels natural to Java developers { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 7. Groovy & Grails From Java to Groovy A normal Java program public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public String greet() { return "Hello " + name; } public static void main(String[] args) { HelloWorld helloWorld = new HelloWorld(); helloWorld.setName("Groovy"); System.out.println(helloWorld.greet()); } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 8. Groovy & Grails From Java to Groovy A valid Groovy program public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public String greet() { return "Hello " + name; } public static void main(String[] args) { HelloWorld helloWorld = new HelloWorld(); helloWorld.setName("Groovy"); System.out.println(helloWorld.greet()); } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 9. Groovy & Grails From Java to groovy But hey? Where are the steroids? { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 10. Groovy & Grails From Java to Groovy A Groovier program class HelloWorld { def name def greet() { "Hello ${name}" } } helloWorld = new HelloWorld(name: "Groovy") println helloWorld.greet() Dynamic types using the def keyword Everything in Groovy is public unless deļ¬ned otherwise Automatic getters and setters Semicolons at end-of-line are optional Variable interpolation through GStrings Return keyword is optional { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 11. Groovy & Grails From Java to Ruby A Ruby program class HelloWorld < Struct.new(:name) def greet "Hello #{name}" end end hello_world = HelloWorld.new("Ruby") puts hello_world.greet { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 12. Groovy & Grails JVM Languages { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 13. Groovy & Grails Joint Compilation Total interoperability Java Interface Groovy Interface Groovy Class Java Class Java Class Groovy Class { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 14. Groovy & Grails Native Syntax Constructs Lists ā€¢ Java: int[] numbers = new int[] { 1, 2, 3 }; ā€¢ Groovy: numbers = [1, 2, 3] ā€¢ Ruby: numbers = [1, 2, 3] { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 15. Groovy & Grails Native Syntax Constructs Lists ā€¢ Java: int[] numbers = new int[] { 1, 2, 3 }; ā€¢ Groovy: numbers = [1, 2, 3] ā€¢ Ruby: numbers = [1, 2, 3] Maps/Hashes ā€¢ Java: Map countries = new HashMap(); countries.put("nl", "Netherlands"); countries.put("be", "Belgium"); ā€¢ Groovy: countries = [nl: "Netherlands", be: "Belgium"] ā€¢ Ruby: countries = {:nl => "Netherlands", :be => "Belgium"} { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 16. Groovy & Grails Iterating Looping ā€¢ Groovy: for (i in list) { println i } ā€¢ Ruby: for i in list puts i end { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 17. Groovy & Grails Iterating Looping ā€¢ Groovy: for (i in list) { println i } ā€¢ Ruby: for i in list puts i end Looping with closures ā€¢ Groovy: list.each { println it } ā€¢ Ruby: list.each {|i| puts i } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 18. Groovy & Grails GStrings GStrings are interpolated strings ā€¢ Placeholder variables are replaced ā€¢ You can have multiline strings def person = "Marcel" def letter = """ ${new Date()} Hello ${person}, You have won 100,000,000GBP in the UK lottery! """ { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 19. Groovy & Grails Special Operators Elvis operator ā€¢ A shortening of Java's ternary operator def displayName = user.name ? user.name : "Anonymous" def displayName = user.name ?: "Anonymous" { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 20. Groovy & Grails Special Operators Elvis operator ā€¢ A shortening of Java's ternary operator def displayName = user.name ? user.name : "Anonymous" def displayName = user.name ?: "Anonymous" Safe Navigation Operator ā€¢ Java: String postalCode = null; if (user != null) { Address address = user.getAddress(); if (address != null) { postalCode = address.getPostalCode(); if (postalCode != null) { postalCode = postalCode.toUpperCase(); } } } ā€¢ Groovy: def postalCode = user?.address?.postalCode?.toUpperCase() { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 21. Groovy & Grails The Groovy Truth Booleans def a = true def b = false assert a assert !b Collections def numbers = [] assert !numbers // false, as numbers is an empty collection numbers = [1, 2, 3] assert numbers // true, as numbers is not empty Strings assert 'This is true' assert !'' Numbers assert !0 // yeah, 0s are false, like in Perl assert 1 // this is also true for all other number types Objects assert new Object() { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 22. Groovy & Grails Meta Programming You can add methods and properties to any Object at runtime You can intercept method calls and property access (similar to AOP) def s = "Hello Groovy" println s println s.toUpperCase() // standard JDK method String.metaClass { toMixedCase { delegate.toUpperCase() } // add method toUpperCase { delegate.toLowerCase() } // override existing method multiply { i -> delegate * i } // add method with argument } println s.toMixedCase() println s.toUpperCase() println s.multiply(3) { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 23. Groovy & Grails Builders Simple mechanism for creating any create any structured tree of data ā€¢ You can use out-of-the-box builders ā€¢ You can create your own builders import groovy.xml.MarkupBuilder def mkp = new MarkupBuilder() mkp.html { head { title "Kabisa ICT" } body { div(class: "container") { p "Welcome to Kabisa ICT" } } } println mkp { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 24. Groovy & Grails Do you want to be Groovy? ? { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 25. Groovy & Grails Grails { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 26. Groovy & Grails Introduction to Grails Full-stack web application framework inspired by ā€¢ Code by Convention ā€¢ Donā€™t Repeat Yourself (DRY) ā€¢ Ruby on Rails, Django, TurboGears { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 27. Groovy & Grails Introduction to Grails Full-stack web application framework inspired by ā€¢ Code by Convention ā€¢ Donā€™t Repeat Yourself (DRY) ā€¢ Ruby on Rails, Django, TurboGears Built on the shoulders of Giants ā€¢ Java/JEE ā€¢ Spring framework ā€¢ Hibernate { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 28. Groovy & Grails Introduction to Grails Full-stack web application framework inspired by ā€¢ Code by Convention ā€¢ Donā€™t Repeat Yourself (DRY) ā€¢ Ruby on Rails, Django, TurboGears Built on the shoulders of Giants ā€¢ Java/JEE ā€¢ Spring framework ā€¢ Hibernate Reduces complexity { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 29. Groovy & Grails Introduction to Grails Full-stack web application framework inspired by ā€¢ Code by Convention ā€¢ Donā€™t Repeat Yourself (DRY) ā€¢ Ruby on Rails, Django, TurboGears Built on the shoulders of Giants ā€¢ Java/JEE ā€¢ Spring framework ā€¢ Hibernate Reduces complexity Increases productivity { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 30. Groovy & Grails Introduction to Grails Full-stack web application framework inspired by ā€¢ Code by Convention ā€¢ Donā€™t Repeat Yourself (DRY) ā€¢ Ruby on Rails, Django, TurboGears Built on the shoulders of Giants ā€¢ Java/JEE ā€¢ Spring framework ā€¢ Hibernate Reduces complexity Increases productivity ā€œJavaā€ { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 31. Groovy & Grails Full-stack Web Application Framework Easy Object Relational Mapping (ORM) based on Hibernate View layer with Groovy Server Pages (GSP), dynamic Tag Libraries and SiteMesh Controller layer based on Spring MVC / Spring Web Flow Dependency Injection (DI) using the Spring Container Transactional service layer based on Springā€™s transaction abstraction Internationalization (i18n) based on Springā€™s MessageSource concept Embedded Tomcat servlet container for on the ļ¬‚y reloading { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 32. Groovy & Grails About SpringSource, G2One and VMware First version of Spring framework was released in 2003 { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 33. Groovy & Grails About SpringSource, G2One and VMware First version of Spring framework was released in 2003 SpringSource was founded in 2004 { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 34. Groovy & Grails About SpringSource, G2One and VMware First version of Spring framework was released in 2003 SpringSource was founded in 2004 G2One (The Groovy Grails Company) was founded in 2007 by the Groovy and Grails project leads { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 35. Groovy & Grails About SpringSource, G2One and VMware First version of Spring framework was released in 2003 SpringSource was founded in 2004 G2One (The Groovy Grails Company) was founded in 2007 by the Groovy and Grails project leads In November 2008 G2One was acquired by SpringSource { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 36. Groovy & Grails About SpringSource, G2One and VMware First version of Spring framework was released in 2003 SpringSource was founded in 2004 G2One (The Groovy Grails Company) was founded in 2007 by the Groovy and Grails project leads In November 2008 G2One was acquired by SpringSource In August 2009 SpringSource was acquired by VMware for $420m { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 37. Groovy & Grails About SpringSource, G2One and VMware First version of Spring framework was released in 2003 SpringSource was founded in 2004 G2One (The Groovy Grails Company) was founded in 2007 by the Groovy and Grails project leads In November 2008 G2One was acquired by SpringSource In August 2009 SpringSource was acquired by VMware for $420m SpringSource is now a division of VMware { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 38. Groovy & Grails Grails Stack Grails Other JEE Spring Hibernate Libraries Groovy Java Development Kit Java Language (JDK) Java Virtual Machine { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 39. Groovy & Grails Grails Command Line grails create-app book grails create-domain-class nl.kabisa.book grails create-controller nl.kabisa.book grails generate-all nl.kabisa.book grails install plugin acegi grails run-app grails test-app grails war grails console .. Custom commands (scripts) can be added to project { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 40. Groovy & Grails Grails Project Breakdown grails-app Top level source folder with Grails artifacts ā€¢ conf Conļ¬guration sources ā€¢ controlllers Controller layer ā€¢ domain Model layer ā€¢ i18n Internationalized Resource Bundles ā€¢ services Service layer ā€¢ taglib Dynamic Tag Libraries ā€¢ views Groovy Server Pages (GSP) web-app Stylesheets, Javascript, ... scripts Custom command-line scripts src Other project sources ā€¢ groovy Other Groovy project sources ā€¢ java Other Java project sources lib 3th Party Libraries test Unit, Integration and Functional tests { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 41. Groovy & Grails Conļ¬guration per environment dataSource { pooled = true driverClassName = "org.hsqldb.jdbcDriver" username = "sa" password = "" } hibernate { cache.use_second_level_cache = true cache.use_query_cache = true cache.provider_class = "net.sf.ehcache.hibernate.EhCacheProvider" } // environment specific settings environments { development { dataSource { dbCreate = "create-drop" // one of 'create', 'create-drop','update' url = "jdbc:hsqldb:mem:devDB" } } production { dataSource { dbCreate = "update" url = "jdbc:hsqldb:file:prodDb;shutdown=true" } } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 42. Groovy & Grails GORM GORM (Grails Object Relational Mapping) ā€¢ Domain Modeling ā€¢ Basic CRUD methods ā€¢ Dynamic Finders ā€¢ Events and Auto Timestamping ā€¢ Validations ā€¢ Custom ORM mappings with ORM Domain Speciļ¬c Language { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 43. Groovy & Grails GORM GORM (Grails Object Relational Mapping) ā€¢ Domain Modeling ā€¢ Basic CRUD methods ā€¢ Dynamic Finders ā€¢ Events and Auto Timestamping ā€¢ Validations ā€¢ Custom ORM mappings with ORM Domain Speciļ¬c Language NO MIGRATIONS ā€¢ LiquiBase Plugin { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 44. Groovy & Grails GORM GORM (Grails Object Relational Mapping) ā€¢ Domain Modeling ā€¢ Basic CRUD methods ā€¢ Dynamic Finders ā€¢ Events and Auto Timestamping ā€¢ Validations ā€¢ Custom ORM mappings with ORM Domain Speciļ¬c Language NO MIGRATIONS ā€¢ LiquiBase Plugin Domain model is OOP based, not database based (as in Rails) { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 45. Groovy & Grails Domain Classes Grails Rails class Book { class User < ActiveRecord::Base String title end String isbn BigDecimal price } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 46. Groovy & Grails Domain Classes Grails Rails class Author { class Auhor < ActiveRecord::Base static hasMany = [books: Book] has_many :books String name end } class Book { class Book < ActiveRecord::Base static belongsTo = [author: Author] belongs_to :author String title end String isbn BigDecimal price } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 47. Groovy & Grails Validations, Events, Auto Timestamping, Mappings class Book { static belongsTo = [author: Author] String title String isbn BigDecimal price Date dateCreated Date lastUpdated def beforeInsert() { dateCreated = new Date() } static constraints = { title(blank: false, maxSize: 100) isbn(blank: false, matches: "[0-9]13", minSize: 13, maxSize: 13, unique: true) price(nullable: true, min: 0.0, max: 9999.99, scale: 2) } static mapping = { table "books" price column: "sales_price" } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 48. Groovy & Grails Basic CRUD methods Grails Rails // create # create def a = new Author(name: "Rowling") a = Author.new(:name => "Rowling") a.save() a.save // read # read def a = Author.get(1) a = Author.find(1) // update # update def a = Author.get(1) a = Author.find(1) a.name = "J.K. Rowling" a.name = "J.K. Rowling" a.save() a.save // delete # delete def a = Author.get(1) a = Author.find(1) a.delete() a.delete { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 49. Groovy & Grails Querying with GORM // query all authors def authors = Author.list() // pagination def authors = Author.list(max: 10, offset: 20) // sorting def authors = Author.list(order: "name", sort: "desc") // pagination and sorting def authors = Author.list(max: 10, offset: 20, order: "name", sort: "desc") { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 50. Groovy & Grails GORM Dynamic Finders FindBy (ļ¬rst result) FindAllBy (all results) Comparators ā€¢ LessThan, LessThanEquals, GreaterThan, GreaterThanEquals ā€¢ Like, Ilike, NotEqual, InList, Between ā€¢ IsNotNull, IsNull def author = Author.findByName("J.K. Rowling") def books = Book.findAllByTileIlike("harry p%") def books = Book.findAllByPriceLessThan(10.0) def books = Book.findAllByTitleLikeAndPriceBetween("Harry P%", 10.0, 20.0) { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 51. Groovy & Grails Criteria and HQL // using criteria builder def c = Book.createCriteria() def books = c { like("title", "Harry P%") and { between("price", 10.0, 20.0) } order("title", "asc") } // using HQL (Hibernate Query Language) def books = Book.findAll("from Book as b where b.title like ?", ["Harry P%"]) { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 52. Groovy & Grails Controllers Responsible for handling requests Render or prepare responses Bind request data to the model (including type conversions) Support interceptors Support content negotiation class SomeController { def action = { // do controller logic // create model return model } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 53. Groovy & Grails Controllers Grails class BookController { def list = { [bookList: Book.list()] } } <ul> <g:each in="${bookList}"> <li>${it.title}</li> </g:each> </ul> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 54. Groovy & Grails Controllers Grails class BookController { def list = { [bookList: Book.list()] } } <ul> <g:each in="${bookList}"> <li>${it.title}</li> </g:each> </ul> Rails class BooksController < ApplicationController def list @books = Book.all end end { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 55. Groovy & Grails Example Controller class BookController { static allowedMethods = [save: "POST", update: "POST", delete: "POST"] def index = { redirect(action: "list", params: params) } def list = { [bookInstanceList: Book.list(params), bookInstanceTotal: Book.count()] } def create = { def bookInstance = new Book() bookInstance.properties = params return [bookInstance: bookInstance] } def save = { def bookInstance = new Book(params) if (bookInstance.save()) { redirect(action: "show", id: bookInstance.id) } else { render(view: "create", model: [bookInstance: bookInstance]) } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 56. Groovy & Grails Example Controller def edit = { def bookInstance = Book.get(params.id) if (!bookInstance) { redirect(action: "list") } else { return [bookInstance: bookInstance] } } def update = { def bookInstance = Book.get(params.id) if (bookInstance) { bookInstance.properties = params if (!bookInstance.hasErrors() && bookInstance.save()) { redirect(action: "show", id: bookInstance.id) } else { render(view: "edit", model: [bookInstance: bookInstance]) } } else { redirect(action: "list") } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 57. Groovy & Grails Example Controller def delete = { def bookInstance = Book.get(params.id) if (bookInstance) { bookInstance.delete(flush: true) redirect(action: "list") } else { redirect(action: "list") } } def show = { def bookInstance = Book.get(params.id) if (!bookInstance) { redirect(action: "list") } else { [bookInstance: bookInstance] } } def beforeInterceptor = { // do something } def afterInterceptor = { // do something } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 58. Groovy & Grails XML Responses def list = { def bookList = Book.list() render(contentType: "text/xml") { books { for (b in bookList) { book(title: b.title) } } } } // automatic xml marshalling def list = { render Book.list() as XML } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 59. Groovy & Grails Content Negotiation You can use HTTP Accept Header You can use format request paramter (/book/list?format=xml) You can use URI extension (/book/list.xml) Use the withFormat method to deal with different formats class BookController { def list = { def books = Book.list() withFormat { html bookList:books js { render "alert('hello')" } xml { render books as XML } } } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 60. Groovy & Grails Views Groovy Server Pages (GSP) ā€¢ Similar like technologies like JSP and ASP ā€¢ A mix of markup and GSP tags ā€¢ Groovy code can be embedded, but is discouraged { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 61. Groovy & Grails Views Groovy Server Pages (GSP) ā€¢ Similar like technologies like JSP and ASP ā€¢ A mix of markup and GSP tags ā€¢ Groovy code can be embedded, but is discouraged NO HAML :-( { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 62. Groovy & Grails Views Groovy Server Pages (GSP) ā€¢ Similar like technologies like JSP and ASP ā€¢ A mix of markup and GSP tags ā€¢ Groovy code can be embedded, but is discouraged NO HAML :-( def show = { [book: Book.get(params.id)] } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 63. Groovy & Grails Views Groovy Server Pages (GSP) ā€¢ Similar like technologies like JSP and ASP ā€¢ A mix of markup and GSP tags ā€¢ Groovy code can be embedded, but is discouraged NO HAML :-( def show = { [book: Book.get(params.id)] } <%= book.title %> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 64. Groovy & Grails Views and Tag Libraries Embedded Groovy code <html> <body> <% [1, 2, 3, 4].each { num -> if (num > 2) { %> <p><%= "Hello ${num}!" %></p> <% } } %> </body> </html> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 65. Groovy & Grails Views and Tag Libraries Embedded Groovy code <html> <body> <% [1, 2, 3, 4].each { num -> if (num > 2) { %> <p><%= "Hello ${num}!" %></p> <% } } %> </body> </html> Use Tag Libraries instead <html> <body> <g:each in="${[1, 2, 3, 4]}" var="num"> <g:if test="${num > 2}"> <p>Number ${num}</p> </g:if> </g:each> </body> </html> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 66. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 67. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 68. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 69. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while> Links and Resources <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book" action="list">Book List</g:link> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 70. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while> Links and Resources <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book" action="list">Book List</g:link> Forms and Fields <g:textField name="title" value="${bookInstance.title}" /> <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" /> <g:datePicker name="publishDate" value="${bookInstance.publishDate}" /> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 71. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while> Links and Resources <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book" action="list">Book List</g:link> Forms and Fields <g:textField name="title" value="${bookInstance.title}" /> <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" /> <g:datePicker name="publishDate" value="${bookInstance.publishDate}" /> Formatting { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 72. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while> Links and Resources <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book" action="list">Book List</g:link> Forms and Fields <g:textField name="title" value="${bookInstance.title}" /> <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" /> <g:datePicker name="publishDate" value="${bookInstance.publishDate}" /> Formatting Ajax { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 73. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while> Links and Resources <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book" action="list">Book List</g:link> Forms and Fields <g:textField name="title" value="${bookInstance.title}" /> <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" /> <g:datePicker name="publishDate" value="${bookInstance.publishDate}" /> Formatting Ajax and more... { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 74. Groovy & Grails Core Tag Libraries Much more attractive than embedded Groovy code Like helpers in Rails Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while> Links and Resources <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book" action="list">Book List</g:link> Forms and Fields <g:textField name="title" value="${bookInstance.title}" /> <g:select name="author.id" from="${Author.list()}" value="${bookInstance.author.id}" /> <g:datePicker name="publishDate" value="${bookInstance.publishDate}" /> Formatting Ajax and more... { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 75. Groovy & Grails Custom Tag Libraries Very complex and painful in standard Java ā€¢ Complex interfaces to implement ā€¢ Additional Tag Library Descriptors (XML) must be written ā€¢ And need to be conļ¬gured in web.xml { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 76. Groovy & Grails Custom Tag Libraries Very complex and painful in standard Java ā€¢ Complex interfaces to implement ā€¢ Additional Tag Library Descriptors (XML) must be written ā€¢ And need to be conļ¬gured in web.xml But so easy in Grails class SimpleTagLib { static namespace = "auth" def isAdmin = { attrs, body -> if (attrs.user.admin) out << body() } } <auth:isAdmin user="${session.user}"> // some restricted content </auth:isAdmin> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 77. Groovy & Grails Views and Layouts <html> <head> <meta name="layout" content="main" /> <title>Book List</title> </head> <body> <div class="nav"> <span><a class="home" href="${createLink(uri: '/')}">Home</a></span> <span><g:link class="create" action="create">New Book</g:link></span> </div> <div class="body"> <div class="list"> <table> <g:each in="${bookInstanceList}" status="i" var="bookInstance"> <tr class="${(i % 2) == 0 ? 'odd' : 'even'}"> <td><g:link action="show" id="${bookInstance.id}">${bookInstance.id}</ g:link></td> <td>${bookInstance.title}</td> </tr> </g:each> </table> </div> </div> </body> </html> { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 78. Groovy & Grails URL Mappings Used for mapping URLā€™s to controllers ā€¢ Similar like routes in Rails ā€¢ Default convention is /controller/action/id { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 79. Groovy & Grails URL Mappings Used for mapping URLā€™s to controllers ā€¢ Similar like routes in Rails ā€¢ Default convention is /controller/action/id class UrlMappings { static mappings = { "/product" (controller: "product", action: "list") "/product/$id" (controller: "product") "/$blog/$year/$month/$day/$id" (controller: "blog", action: "show") } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 80. Groovy & Grails Filters Controllers already support ļ¬ne grained interceptors but these are difļ¬cult to manage in larger applications { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 81. Groovy & Grails Filters Controllers already support ļ¬ne grained interceptors but these are difļ¬cult to manage in larger applications Use ļ¬lters instead ā€¢ A Domain Speciļ¬c Language is available for deļ¬ning ļ¬lters ā€¢ You can deļ¬ne scopes (all controllers, a speciļ¬c controller/action, URI pattern) ā€¢ You can deļ¬ne interceptor types (before, after, afterView) ā€¢ You can use variables (params, request, response, session, grailsApplication) { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 82. Groovy & Grails Filters Controllers already support ļ¬ne grained interceptors but these are difļ¬cult to manage in larger applications Use ļ¬lters instead ā€¢ A Domain Speciļ¬c Language is available for deļ¬ning ļ¬lters ā€¢ You can deļ¬ne scopes (all controllers, a speciļ¬c controller/action, URI pattern) ā€¢ You can deļ¬ne interceptor types (before, after, afterView) ā€¢ You can use variables (params, request, response, session, grailsApplication) class SecurityFilters { def filters = { loginCheck(controller: '*', action: '*') { before = { if(!session.user && !actionName.equals('login')) { redirect(action: 'login') return false } } } } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 83. Groovy & Grails Services Donā€™t put core/reusable logic in controllers, but instead use the service layer Services are by default transactional Services can be scoped class BookService { static scope = "singleton" // other options include prototype, request, session static transactional = true def doSomething() { // TODO: implement } } { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 84. Groovy & Grails Plugins Grails is designed with a plugin architecture in mind Grails core features are built on plugins Plugins can provide basic artifacts ā€¢ Domain Classes, Tag Libraries, Services, ... Plugins can provide new artifact types Plugins can hook into build events Plugins can hook into runtime conļ¬guration Plugins can add dynamic methods at runtime { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 85. Groovy & Grails Plugins Spring Security LDAP Quartz Commentable Searchable Selenium RC Mail Fixtures Canoo Webtest ReCaptcha GWT LiquiBase Feeds GORM-JPA Taggable iWebKit Rateable Webdriver XFire Axis2 Spring WS Wicket { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 86. Groovy & Grails Tooling Integrated Development Environments ā€¢ SpringSource Tool Suite (STS) ā€¢ NetBeans ā€¢ IDEA IntelliJ TextMate { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 87. Groovy & Grails Discussion & Demo !? { Agile Development } { Ruby on Rails } { Java / J2EE }
  • 88. { Agile Development } { Ruby on Rails } { Java / J2EE }

Editor's Notes