Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Groovy & Grails for Java Developers

Groovy & Grails for Java Developers

Groovy is a dynamic language for the JVM with a Java-like syntax, and Grails is a rapid web application framework that uses the language extensively.

Find out how Groovy can improve a Java developer's life and what jobs it's really good for. Also learn about Grails and how it provides more than just a CRUD web framework, with strong enterprise integration features.

pledbrook

May 02, 2012
Tweet

Other Decks in Technology

Transcript

  1. Groovy and Grails for Java
    developers
    Peter Ledbrook
    SpringSource
    t: @pledbrook
    g: +PeterLedbrook
    e: [email protected]

    View full-size slide

  2. What is Groovy?
    • A dynamic language for the JVM
    – ...with a Java-like syntax
    – ...and optional static types
    • Uses and extends the JDK
    • Write scripts as well as classes
    • Seamless integration with Java
    – ...call Java from Groovy
    – ...or call Groovy from Java
    – ...all in the same project
    • Great IDE support in IntelliJ and Eclipse
    – NetBeans also has Groovy (& Grails support)

    View full-size slide

  3. 3
    GroovyBean syntax

    View full-size slide

  4. 4
    Define properties as fields...

    View full-size slide

  5. 5
    ...and initialize them on construction

    View full-size slide

  6. 6
    Define a getter method...

    View full-size slide

  7. 7
    ...and still use property syntax to access it

    View full-size slide

  8. 9
    Properties implicitly have getter and setter methods

    View full-size slide

  9. 11
    Use the @Immutable annotation...

    View full-size slide

  10. 12
    ...and typed properties...

    View full-size slide

  11. 13
    ...to get a standard constructor...

    View full-size slide

  12. 14
    ...and make instances immutable

    View full-size slide

  13. 17
    Use single or double-quotes for strings

    View full-size slide

  14. 18
    Double quotes allow for embedded expressions

    View full-size slide

  15. 19
    Use array syntax to access characters of a string

    View full-size slide

  16. 21
    Array syntax with ranges extracts substrings

    View full-size slide

  17. 22
    and can even allow for reversing of the substring

    View full-size slide

  18. 23
    Triple quotes for multi-line strings

    View full-size slide

  19. 25
    Java doubles are not exact

    View full-size slide

  20. 27
    Java solution with BigDecimal is ugly

    View full-size slide

  21. 28
    Groovy uses BigDecimal by default and provides operator support

    View full-size slide

  22. 29
    for precise floating-point calculations

    View full-size slide

  23. 31
    List literals

    View full-size slide

  24. 32
    Extra collection methods for convenience

    View full-size slide

  25. 34
    Easy map iteration with key and value as separate arguments

    View full-size slide

  26. 36
    Collection filtering with closures

    View full-size slide

  27. 38
    Map one collection to another by applying a function to each element

    View full-size slide

  28. 39
    Same collection, but each element has a value of 3 less than before

    View full-size slide

  29. 41
    Slashy string literals for use with regular expressions

    View full-size slide

  30. 42
    Backslash in regex does not need escaping

    View full-size slide

  31. 43
    Iterate over matches...

    View full-size slide

  32. 44
    ...and use array syntax to access the match groups

    View full-size slide

  33. 45
    Literal for compiled patterns

    View full-size slide

  34. 46
    Generate XML from Groovy code

    View full-size slide

  35. 47
    Methods with closures become nested elements

    View full-size slide

  36. 49
    Named arguments become attributes

    View full-size slide

  37. 51
    Because it’s Groovy code, use conditions and loops

    View full-size slide

  38. 53
    Easy XML parsing

    View full-size slide

  39. 54
    Parse and create a DOM-like object

    View full-size slide

  40. 55
    And use properties, array-syntax, etc. to access elements and content

    View full-size slide

  41. 58
    ‘@’-syntax for accessing attributes

    View full-size slide

  42. 60
    Even incorporate filtering

    View full-size slide

  43. Where to use Groovy
    • Scripts
    – especially with groovyserv
    – cross-platform
    • Tests
    – syntax more expressive
    – Spock for BDD
    • Java application plugins/scripting
    – GroovyShell
    – GroovyClassLoader
    • Domain Specific Languages
    • Higher-level application development

    View full-size slide

  44. Scripting with SQL
    62

    View full-size slide

  45. Scripting with SQL
    63
    Create a new Sql instance with JDBC connection details

    View full-size slide

  46. Scripting with SQL
    64
    Easy querying and processing or results

    View full-size slide

  47. Scripting with SQL
    65
    Easy, safe updates with GStrings

    View full-size slide

  48. 66
    Scripting with XML content

    View full-size slide

  49. 67
    Scripting with XML content
    Grab content from URLs with automatic closing of the stream

    View full-size slide

  50. 68
    Scripting with XML content
    Then hook into other Groovy features for processing the content

    View full-size slide

  51. 69
    Scripting with XML content
    Easy writing to files, with safe file stream close

    View full-size slide

  52. 70
    Scripting with XML content
    Print to the new file

    View full-size slide

  53. 71
    Scripting with XML content
    Iteration over elements in the XML

    View full-size slide

  54. Scripting with GORM
    72

    View full-size slide

  55. Scripting with GORM
    73
    Use @Grab to include external dependencies

    View full-size slide

  56. Scripting with GORM
    74
    Define a domain class...

    View full-size slide

  57. Scripting with GORM
    75
    ...and use GORM/MongoDB to save data

    View full-size slide

  58. Spock
    • BDD testing framework
    • Encourages simple test structure
    • ...and documented tests
    • given...when...then
    • + data-driven tests!
    • Can run via JUnit test runner
    76
    http://code.google.com/p/spock/
    http://meetspock.appspot.com/

    View full-size slide

  59. 77
    Using Spock

    View full-size slide

  60. Implementing a DSL
    78

    View full-size slide

  61. Groovy in Maven
    79

    View full-size slide

  62. Groovy in Maven
    80

    View full-size slide

  63. Groovy in Maven
    81

    View full-size slide

  64. • Grails for Swing applications
    • MVC model
    • SwingBuilder for views
    82
    application(title: 'DemoConsole', pack: true, locationByPlatform: true) {
    panel(border: emptyBorder(6)) {
    borderLayout()
    scrollPane(constraints: CENTER) {
    textArea(
    text: bind(target: model, targetProperty: 'scriptSource'),
    enabled: bind {model.enabled},
    columns: 40, rows: 10)
    }
    }
    }
    http://griffon.codehaus.org/

    View full-size slide

  65. Gradle
    • Build tool with built-in dependency management
    • Conventions through plugins
    • Multi-project support
    • Full access to tasks and dependency tree
    • Easy to write your own tasks
    – either in the build file
    – or via Groovy/Java classes
    83
    http://www.gradle.org/

    View full-size slide

  66. • Parallel processing for Groovy
    • Actors library making full use of closures
    84
    @Grab(group='org.codehaus.gpars', module='gpars', version='0.11')
    import groovyx.gpars.GParsPool
    GParsPool.withPool {
    def animals = ['dog', 'ant', 'cat', 'whale']
    println(animals.anyParallel {it ==~ /ant/} ?
    'Found an ant' : 'No ants found')
    println(animals.everyParallel {it.contains('a')} ?
    'All animals contain a' : 'Some animals can live without an a')
    }
    http://gpars.codehaus.org/

    View full-size slide

  67. Try it out!
    85
    http://groovyconsole.appspot.com/

    View full-size slide

  68. What is Grails?
    • Rapid Web Application Development Framework
    – for the JVM
    – with first-class Java integration
    • Inspired by Ruby on Rails, Django and others
    – Convention over Configuration
    – Don’t Repeat Yourself (DRY)
    86

    View full-size slide

  69. Grails
    What is Grails?
    87
    Build
    Web MVC GSP (Views)
    GORM
    (Data Access)
    Doc Engine
    Servlet
    Container
    Test Support
    Database I18n

    View full-size slide

  70. Grails
    What is Grails?
    88

    View full-size slide

  71. What is Grails?
    89
    Web Controllers
    The Domain Model
    Business Logic
    Custom View Tags
    Views & Layouts
    Libraries (JARs)
    Additional Sources
    Web Resources
    i18n bundles
    Build Commands
    Tests

    View full-size slide

  72. Say bye-bye to the plumbing!
    90

    View full-size slide

  73. Enterprise requirements
    92
    Web App
    Messaging
    Legacy
    Databases
    Services
    JEE
    Is this a problem for Grails apps?

    View full-size slide

  74. Build
    93
    • Remember the Grails project structure?
    – add in build events and...
    Can’t build natively with other build tools!
    Grails Build System
    Ant Gradle
    Maven

    View full-size slide

  75. Dependency DSL
    grails.project.dependency.resolution = {
    inherits "global"
    log "warn"
    repositories {
    grailsHome()
    mavenCentral()
    mavenRepo "http://localhost:8081/..."
    }
    ...
    }
    94

    View full-size slide

  76. Dependency DSL
    grails.project.dependency.resolution = {
    inherits "global"
    log "warn"
    ...
    dependencies {
    runtime "mysql:mysql-connector-java:5.1.17"
    test "org.gmock:gmock:0.8.1"
    ...
    }
    plugins {
    compile ":spring-security-core:1.2.7"
    ...
    }
    }
    95

    View full-size slide

  77. ‘Legacy’ Databases
    • Grails can create a database from your domain model...
    • ...but what if you don’t own the database?
    – DBA determines structure
    – Company conventions
    – Existing ‘legacy’ database
    96

    View full-size slide

  78. • No existing domain model
    • Schema not too far off the beaten track
    97
    Option 1: Custom ORM mapping
    class Book {
    ...
    static mapping = {
    table "books"
    title type: "books"
    author column: "author_ref"
    }
    }

    View full-size slide

  79. • Existing Java/JPA domain model
    Option 2: JPA annotations
    98
    grails-app/conf/hibernate/hibernate.cfg.xml






    ...


    View full-size slide

  80. • You have Java model + Hibernate mapping files
    • Schema is way off the beaten track
    99
    grails-app/conf/hibernate/hibernate.cfg.xml
    Option 3: Hibernate XML Mappings






    ...


    View full-size slide

  81. constraints = {
    title blank: false, unique: true
    ...
    }
    Constraints
    Given domain class:
    Then:
    org.example.myapp.domain.Book
    src/java/org/example/myapp/domain/BookConstraints.groovy
    100

    View full-size slide

  82. • GORM layer over JPA
    • Use your own JPA provider
    • Useful for cloud services that only work with JPA, not
    Hibernate
    101
    Option 4: GORM JPA Plugin

    View full-size slide

  83. Database Migration Plugin
    102
    Pre-production, Hibernate ‘update’ or ‘create-drop’
    dbm-generate-changelog
    dbm-changelog-sync
    Change domain model
    dbm-gorm-diff
    dbm-update

    View full-size slide

  84. Reverse Engineering Plugin
    103
    class Person {
    String name
    Integer age
    ...
    }

    View full-size slide

  85. Grails is Spring
    • Spring MVC under the hood
    • Grails provides many useful beans
    – e.g. grailsApplication
    • Define your own beans!
    – resources.xml/groovy
    – In a plugin
    104

    View full-size slide

  86. Example
    import ...
    beans = {
    credentialMatcher(Sha1CredentialsMatcher) {
    storedCredentialsHexEncoded = true
    }
    sessionFactory(ConfigurableLocalSessionFactoryBean) {
    dataSource = ref("dataSource")
    hibernateProperties = [
    "hibernate.hbm2ddl.auto": "create-drop",
    "hibernate.show_sql": true ]
    }
    }
    105

    View full-size slide

  87. Enterprise Integration
    • Spring opens up a world of possibilities
    – Spring Integration/Camel
    – Messaging (JMS/AMQP)
    – ESB
    – RMI, HttpInvoker, etc.
    • Web services & REST
    106

    View full-size slide

  88. Grails Plugins
    • Routing
    • JMS, RabbitMQ
    • CXF, Spring-WS, WS-Client
    • REST
    107

    View full-size slide

  89. Summary
    • Various options for integrating Grails with:
    – Development/build
    – Deployment processes
    • Works with many external systems
    – Solid support for non-Grailsy DB schemas
    – Flexible messaging & web service support
    108

    View full-size slide

  90. More info
    • w: http://grails.org/
    • f: http://grails.org/Mailing+Lists
    • e: [email protected]
    • t: pledbrook
    • b: http://blog.springsource.com/author/peter-ledbrook/
    109

    View full-size slide