Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

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)

Slide 3

Slide 3 text

3 GroovyBean syntax

Slide 4

Slide 4 text

4 Define properties as fields...

Slide 5

Slide 5 text

5 ...and initialize them on construction

Slide 6

Slide 6 text

6 Define a getter method...

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

8

Slide 9

Slide 9 text

9 Properties implicitly have getter and setter methods

Slide 10

Slide 10 text

10

Slide 11

Slide 11 text

11 Use the @Immutable annotation...

Slide 12

Slide 12 text

12 ...and typed properties...

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

14 ...and make instances immutable

Slide 15

Slide 15 text

15

Slide 16

Slide 16 text

16

Slide 17

Slide 17 text

17 Use single or double-quotes for strings

Slide 18

Slide 18 text

18 Double quotes allow for embedded expressions

Slide 19

Slide 19 text

19 Use array syntax to access characters of a string

Slide 20

Slide 20 text

20

Slide 21

Slide 21 text

21 Array syntax with ranges extracts substrings

Slide 22

Slide 22 text

22 and can even allow for reversing of the substring

Slide 23

Slide 23 text

23 Triple quotes for multi-line strings

Slide 24

Slide 24 text

24

Slide 25

Slide 25 text

25 Java doubles are not exact

Slide 26

Slide 26 text

26

Slide 27

Slide 27 text

27 Java solution with BigDecimal is ugly

Slide 28

Slide 28 text

28 Groovy uses BigDecimal by default and provides operator support

Slide 29

Slide 29 text

29 for precise floating-point calculations

Slide 30

Slide 30 text

30

Slide 31

Slide 31 text

31 List literals

Slide 32

Slide 32 text

32 Extra collection methods for convenience

Slide 33

Slide 33 text

33

Slide 34

Slide 34 text

34 Easy map iteration with key and value as separate arguments

Slide 35

Slide 35 text

35

Slide 36

Slide 36 text

36 Collection filtering with closures

Slide 37

Slide 37 text

37

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

40

Slide 41

Slide 41 text

41 Slashy string literals for use with regular expressions

Slide 42

Slide 42 text

42 Backslash in regex does not need escaping

Slide 43

Slide 43 text

43 Iterate over matches...

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

45 Literal for compiled patterns

Slide 46

Slide 46 text

46 Generate XML from Groovy code

Slide 47

Slide 47 text

47 Methods with closures become nested elements

Slide 48

Slide 48 text

48

Slide 49

Slide 49 text

49 Named arguments become attributes

Slide 50

Slide 50 text

50

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

52

Slide 53

Slide 53 text

53 Easy XML parsing

Slide 54

Slide 54 text

54 Parse and create a DOM-like object

Slide 55

Slide 55 text

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

Slide 56

Slide 56 text

56

Slide 57

Slide 57 text

57

Slide 58

Slide 58 text

58 ‘@’-syntax for accessing attributes

Slide 59

Slide 59 text

59

Slide 60

Slide 60 text

60 Even incorporate filtering

Slide 61

Slide 61 text

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

Slide 62

Slide 62 text

Scripting with SQL 62

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

Scripting with SQL 64 Easy querying and processing or results

Slide 65

Slide 65 text

Scripting with SQL 65 Easy, safe updates with GStrings

Slide 66

Slide 66 text

66 Scripting with XML content

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

70 Scripting with XML content Print to the new file

Slide 71

Slide 71 text

71 Scripting with XML content Iteration over elements in the XML

Slide 72

Slide 72 text

Scripting with GORM 72

Slide 73

Slide 73 text

Scripting with GORM 73 Use @Grab to include external dependencies

Slide 74

Slide 74 text

Scripting with GORM 74 Define a domain class...

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

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/

Slide 77

Slide 77 text

77 Using Spock

Slide 78

Slide 78 text

Implementing a DSL 78

Slide 79

Slide 79 text

Groovy in Maven 79

Slide 80

Slide 80 text

Groovy in Maven 80

Slide 81

Slide 81 text

Groovy in Maven 81

Slide 82

Slide 82 text

• 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/

Slide 83

Slide 83 text

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/

Slide 84

Slide 84 text

• 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/

Slide 85

Slide 85 text

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

Slide 86

Slide 86 text

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

Slide 87

Slide 87 text

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

Slide 88

Slide 88 text

Grails What is Grails? 88

Slide 89

Slide 89 text

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

Slide 90

Slide 90 text

Say bye-bye to the plumbing! 90

Slide 91

Slide 91 text

Demo

Slide 92

Slide 92 text

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

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

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

Slide 95

Slide 95 text

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

Slide 96

Slide 96 text

‘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

Slide 97

Slide 97 text

• 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" } }

Slide 98

Slide 98 text

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

Slide 99

Slide 99 text

• 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 ...

Slide 100

Slide 100 text

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

Slide 101

Slide 101 text

• 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

Slide 102

Slide 102 text

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

Slide 103

Slide 103 text

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

Slide 104

Slide 104 text

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

Slide 105

Slide 105 text

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

Slide 106

Slide 106 text

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

Slide 107

Slide 107 text

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

Slide 108

Slide 108 text

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

Slide 109

Slide 109 text

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

Slide 110

Slide 110 text

Q&A