java users group charleston, sc june 25, 2008 introduction to grails by jason mcdonald

33
Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Upload: willis-griffith

Post on 30-Dec-2015

216 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Java Users GroupCharleston, SC

June 25, 2008

Introduction to Grailsby Jason McDonald

Page 2: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Getting Started

Page 3: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Grails Basics

• Open Source• Fully integrated with Java• Groovy based– Uses ANTLR to compile Groovy down to JVM

compatible bytecode

• Predicated on DRY principle

Page 4: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Underlying Technologies

• Spring• Hibernate• Log4J• Junit• Quartz• Ant

Page 5: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Native Support

• HSQL• MySQL• Servlet container servers– Jetty– Tomcat

• AJAX and DHTML– Dojo– Prototype– Yahoo!

Page 6: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Installation

• Visit http://www.grails.org• Download and extract files• Create GRAILS_HOME environment variable• Add %GRAILS_HOME% to PATH environment

variable• That’s it!

Page 7: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Grails Structure

Page 8: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Goovy Roots

• Built on top of Java• Very similar syntax to java• Supports closures• Method returns can be slightly different• Case sensitive• No semi-colons needed• All classes end in .groovy

Page 9: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Conditional Environments

• Environment conditionals allow for variations for a specific environment– Database– Initialization options– More

• Three environment choices– Development– Testing– Production

Page 10: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Script Based Code Generation

• grails create-app [app name]• grails create-controller [controller name]• grails create-domain-class [class name]• grails create-service [service name]• grails create-unit-test [test name]• grails create-tag-lib [taglib name]• grails generate-all [class name]• grails generate-views [class name]

Page 11: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Building, Deploying, and Managing

• grails clean• grails compile• grails console• grails doc• grails install-plugin• grails run-app• grails war

Page 12: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Important Files

• conf/DataSource.groovy– Database connections

• conf/UrlMapping.groovy– Routing

• conf/BootStrap.groovy– Bootstrap file

• conf/Config.groovy– Configurations (MIME mappings, more…)

Page 13: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Routing

• Route rules found in conf/UrlMapping.groovy• Default route:– application/controller/action/id[?params]

• Additional rules and restrictions can be applied herestatic mappings = { "/product/$id?"(controller:"product"){

action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]

} }

Page 14: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Databases

• db configuration is in conf/DataSource.groovy• Can define at environment level or global level• Defaults to HSQL• Change to MySQL by:– Dropping MySQL connector in the lib– Changing DataSource.groovy to point at MySQL

Page 15: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Database Create Scheme

• dbCreate– create-drop: creates tables on startup and drops

them on shutdown (DEV)– create: creates tables on startup, deletes data on

shutdown (DEV, TEST)– update – creates tables on startup, saves data

between restarts (TEST, PROD)

Page 16: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Grails MVC

Page 17: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

MVC Framework

• Standard MVC implementation• Sits on top of Spring MVC– Reduces repetition of XML developers must

maintain– Gives access to Spring DSL

Page 18: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Views

• Groovy Server Pages– GSP extension– Based on JSP pages– Use• Tag libraries• Expressions

– similar to JSP EL but allows any expression within ${…}

Page 19: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Tag Libraries

• Ordering and sorting<g:sortableColumn property="releaseDate" defaultOrder="desc"

title="Release Date" titleKey="book.releaseDate" />

• Form display<g:form name="myForm"

action="myaction" id="1"><g:passwordField name="myPasswordField“

value="${myPassword}" />...

</g:form>

• Formatting<g:formatDate format="yyyy-MM-dd" date="${date}"/>

Page 20: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Custom Tag Libraries

• Custom tag libraries are just groovy classes that end with TagLib

• Defaults to ‘g’ namespaces unless declared• Closure defines actual tag:

class FormattingTagLib { static namespace = ‘fmt’ def dateFormat = { attrs -> out << new java.text.SimpleDateFormat(

‘dd-MM-yyyy’).format(attrs.date) }}<fmt:dateFormat date=‘${plan.effDate}’ />

Page 21: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Internationalization Support

• Based on Java i18n specifications• Define properties files with language specific

entries• Views can read i18n entries with a tag:

<g:message code=‘my.message’ args=‘${[‘One’, ‘Two’]}’/>

• Tag libraries can read entries with code:g.message(code: ‘my.message’, args: [‘One’, ‘Two’])

Page 22: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Models

• POGOs– Fields default to private– Getters and setters provided automatically– Must use wrapper objects – no primitives (1.5?)– Field validation defined within:

static constraints = { date(nullable: false) }

• Can define custom messages using convention:– className.propertyName.constraint = ‘’Err msg’’

– Automatic parameter mapping from viewbook.properties = params

Page 23: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

GORM

• Grails Object Relational Mapping• Uses Hibernate3• Dynamic methods for finding

Book.findByTitle(“The Dark Tower“)Book.findByTitleAndAuthor(“The Dark Tower”, “Stephen King”Book.findByTitle(“Christine”, [sort: ‘edition’, order: ‘asc’] )

• Relational mapping defined within– One to many:

static hasMany = [ attendances:Attendance ]

– One to one:Attendance attendance

Page 24: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

GORM Caching

• Provides the same caching mechanisms that can be found with Hibernate3

• Updates to DataSource.groovy can toggle caching:

hibernate { cache.use_second_level_cache = true cache.use_query_cache = true cache.provider_class =

‘org.hibernate.cache.EhCacheProvider’}

Page 25: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Controllers

• House actions (methods) that respond to a request

• Actions should map to GSP of same name• index is the default action• Can define the method each action is allowed:

def allowedMethods = [save:'POST', update:'POST']

– GET is the default• Auto scaffolding sets up CRUD without files

def scaffold = true // In Controller class

Page 26: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Action Responses

• All actions respond in one of three ways:– redirect• Equivalent ot response.sendRedirect• Can specify actions, controller, params, and more

– return• Returns a value and calls a GSP of the same name

(action method ‘go’ will forward to go.gsp)

– render• Calls a GSP by name• Has the ability to pass arguments

Page 27: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Grails in Action

Page 28: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Web Services

• REST– Provide RESTful mappings in UrlMappings.groovy– Implement controller to accept and return

marshalled data

• SOAP– Supported through XFire plug-in– Simply expose a service:

static expose = [‘xfire’]

Page 29: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Testing

• Test framework based on JUnit• Unit tests– By convention uses mock objects

• Integration tests– By convention use real objects

• Functional tests– Supports Canoo WebTest integration

Page 30: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Running the Application

• Bootstrapping data– Allows for initialization and test data

• Jetty Server– Specify port and environment on command line

grails dev –Dserver.port=9999 run-app

• Tomcat– As war– Exploded

Page 31: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

The Example

Page 32: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Requirements

• Application needs to:– Store meetings, people, and which meetings each

person attends• People should store first and last name• Meetings should store date and subject of meeting

– Must have full CRUD capability– Must be web based– Must be able to integrate with Java environments

(to meet future integration needs)

Page 33: Java Users Group Charleston, SC June 25, 2008 Introduction to Grails by Jason McDonald

Open Discussion