Grails @ Java User Group Silicon Valley
Upcoming SlideShare
Loading in...5
×
 

Grails @ Java User Group Silicon Valley

on

  • 10,633 views

Grails presentation by Sven Haiges at Silicon Valley Java User Group on Nov 18, 2008. Check github for code. http://github.com/hansamann/groovyquiz-demo

Grails presentation by Sven Haiges at Silicon Valley Java User Group on Nov 18, 2008. Check github for code. http://github.com/hansamann/groovyquiz-demo

Statistics

Views

Total Views
10,633
Views on SlideShare
10,300
Embed Views
333

Actions

Likes
9
Downloads
324
Comments
0

10 Embeds 333

http://www.anyware.co.uk 271
http://www.slideshare.net 17
http://www.net4java.com 17
http://www.techgig.com 14
http://www.linkedin.com 5
https://www.linkedin.com 3
http://static.slideshare.net 2
http://webcache.googleusercontent.com 2
http://blog.net4java.in 1
https://craftler.dyndns.org:1111 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Grails @ Java User Group Silicon Valley Grails @ Java User Group Silicon Valley Presentation Transcript

  • g ra ils Sven Haiges , Nov 18 g 2 leplex , 008, JU G Meeti ng, Goo A in View, C Mounta
  • spring MVC hibernate sitemesh groovy
  • Flexibility = Complexity
  • zero configuration
  • convention over configuration
  • coding1 creating the domain model, applying some validaton and scaffolding the rest
  • convention over configuration
  • NetBeans IDE free groovy grails griffon
  • domain class mapping& validation easy 1:1, 1:n, m:n validation constraints
  • dynamic scaffolding on the fly views & controller quick prototypes
  • coding2 adding some test data into the DB, creating a basic quiz UI and writing the quiz controller
  • URL mapping controller/action/id easy customization
  • BootStrap .groovy test data great for demos HSQLDB
  • Gr ai ls beans { Fi xt easyQuestion(Question) { ur es title = quot;Which color is #00FF00?quot; answers = [red, green, blue] } red(Answer) { title = quot;Redquot; } green(Answer) { title = quot;Greenquot; correctAnswer = true } blue(Answer) { title = quot;Bluequot; } }
  • SiteMesh layouts out of the box easy customization one place
  • GSP taglibs similar to JSP built-in taglibs custom taglibs
  • <g:each in=quot;${questions}quot; var=quot;questionquot;> <div class=quot;questionquot;> <div class=quot;questionTitlequot;>${question?.title}</div> <g:each in=quot;${question.answers}quot; var=quot;answerquot;> <g:link action=quot;answerquot; id=quot;${params.id}quot;>${answer?.title}</g:link><br/> </g:each> </div> </g:each> <g:each in=quot;${questions}quot; var=quot;questionquot;> <g:renderQuestion question=quot;${question}quot;/> </g:each>
  • class QuizTagLib { def renderQuestion = { attrs -> out << render(template:quot;questionTemplatequot;, model:[question:attrs.question]) } } <div class=quot;questionquot;> <div class=quot;questionTitlequot;>${question?.title}</div> <g:each in=quot;${question?.answers}quot; var=quot;answerquot;> <g:link action=quot;answerquot; id=quot;${params.id}quot; >${answer?.title}</g:link><br/> </g:each> </div>h>
  • grails controllers scopes injected methods
  • render() render quot;makes my ajax calls happyquot;
  • render() render( text:quot;<xml>plain xml</xml>quot;, contentType:quot;text/xmlquot;, encoding:quot;UTF-8quot; )
  • render() render( template:quot;questionTemplatequot;, model:[question:questionObject] ) render( view:quot;showquot;, model:[question:questionObject] )
  • render() def list = Question.list() render(contentType:quot;text/xmlquot;) { questions { list.each { q -> question(title:q.title,level:q.level) } } }
  • <questions> <question title=quot;Who is...quot; level=quot;easyquot;/> ... </questions>
  • render() render Question.list() as XML render Question.list() as JSON
  • GORM easy in and out
  • easy in def question = new Question(params) question.save()
  • easy out Question.findAllByLevel(quot;easyquot;) Question.findAllByCreatedBetween(a, b) Question.findByTitleLike(quot;%Graeme%quot;)
  • coding3 pushing the app into mor.ph AppSpace and making it publicly available
  • community
  • marc palmer
  • marcel overdijk
  • peter ledbrook
  • what else? some more resources about Groovy, Grails & Griffon
  • groovymag.com svjugnov08
  • we're on twitter @grailspodcast
  • thx Jason rudolph for his great open source Grails Slides, Matthew Fang for the intro slide image (CC), alidarbac for the community soccer photo (cc), Zeno_ for the sounds of complexity image (cc), Andres Almiray for suggesting me for a GRAils presentation at JUG, thomas lopatic for reviewing the presentation, the groovy & Grails community for all the great news, glen smith for podcasting with me. IF you have read that far you are a super brave reader. Listen to the grails podcast. www.grailspodcast.com grails.org
  • gr ails Sven H aiges, g Nov 18 , Googl 2008, J eplex, UG Meetin w, CA Mo unt ain Vie 1 ● Welcome to this JUG Session about Grails ● Sven Haiges, live in the Bay Area for a bit more than a year and this is the first opportunity to talk about sth. I realy love: Grails. Thanx Van for allowing me and thanx Google for filming and youtube all the rest :-) ● What is Grails? ● Grails is a web framework. More specifically, a Java Web Framework.(yes, Grails is mostly Java, but it uses a lot of Groovy and your own code is written in groovy most times, too). Right, there are millions out there, so why should you care. Well, Grails does not just make everyhing more perfect and complex again, Grails really makes your life easy and fun again. And after all, that's what development is all about: having fun and meanwhile doing a great job. So let's take a closer look at the ingredients t Grails.
  • spring MVC hibernate sitemesh groovy 2 First spring/hibernate/sitemesh appears Spring: leading Java/J2EE application framework, very famous for it's Inversion of Control/ Dependency Injection features. Spring MVC is a action-based web framework which is part of Spring, very flexible but also a bit complex and hard to configure. Hibernate: the defacto O/R mapping soution for java persistency. EJB 3 just took on what Hibernate started, easy Java persistence. Sitemesh: a powerful decoration framework, use it to give your pages a common look and feel. It all comes preconfigured, which is nice. Groovy: groovy holds it all together and your own code is most times developed in groovy. The dynamic nature of groovy and its many features like closures allow for some really elegant soliutions (GORM)
  • Flexibility = Complexity This more looks like another configuration nightmare right now. In fact the configuraton needs to be somewhere, but with Grails, it does not need to be that bad. Typically great flexibility, like provided by Hibernate, Spring and Sitemesh means a lot of lines of configuration. And a lot of lines of configuration, which is good for flexibility, means lot's f complexity. Most times, your app does not have a complex behaviour at all. It is more off-the-shelf request processing. So why should 90% of your request handling need the same complex configuration? Next Slide.
  • zero configuration 4 Would it not be cool to have zero configuration? Just forget about all those HBM files, that ton of spring xml configuration of your last project just to have a controller to respond to some requests that come in? everything easier. Well no configuration... not really, but... pretty close. Next slide.
  • convention over configuration 5 Convention over Configuration is able to drastically reduce the amount of configuration. CoC means that Grails chooses sensible defaults for you. There are defaults how properties of Domain Classes are mapped to the database, there is a default for the database table itself, there is a convention how incoming requests are mapped onto controllers and how the right view is determined after a controllers action has been called. Whereever there is a convention, it means you have to code less. And if you need to escape the convention, Grails makes it easy provide your own configuration. Grails still provides the flexiblity of Spring under the hood. If you need it, it's there and you can take advantage of it. If you don't need it, don't let spring get into your way. Instead of talking, let's start codig a basic app....
  • 6 Basic App GroovyQuiz is a basic web game that has three possible difficulty levels: easy, medium and hard. The user navigates to the web site and clicks on an answer of a question. If the answer is right, it disappears, otherwise not.
  • coding1 creating the domain model, applying some validaton and scaffolding the rest 7
  • convention over configuration 8 Before I explain more what we have done, let's revisit CoC again. What conventions have we already seen? For example we did not have to create Hibernate Mapping Files or Annotations in our Domain Classes. Grails used a convention to figure out which table it will use and the same is true for the columns. Also, we were using the default URLMapping, our Urls looked like <appname>/question/list, which is based on the default URLMapping. Both things can be changed, will alk more abou tthsi later TODO
  • NetBeans IDE free groovy grails griffon 9 Netbeans is free and open source, plus supports groovy, grails and griffon It is the best free IDE out there today and keeps getting better all the time. Geertjan Wielenga is the key resource from Sun behind this effort and he blogs a lot so it is easy to keep up to date about latest (nightly) features. Even if you started on the command line, Netbeans will import your Grails project correctly, just <open> the project. There are wizards for Groovy Scripts and Grails Projects, most targets are executable from Netbeans. Still, you see what is going on on the command line.
  • domain classmapping& validation easy 1:1, 1:n, m:n validation constraints 10 Domain classes are the core of any Grails application, they hold state and implement behaviour They may be linked together through relationships: 1:1, 1:n. These relationships can easily be expressed in grails domain classes, no HBM xml needed but it still uses Hibernate under the cover. Even unidirectional and bidirectional associations are trivial in Grails, for uni just leave the 'returning' property out. The CRUD methods are automatically available on each domain class (plus more like dynamic finders as we will find out in the next coding section). For special mapping cases, there is a ORM dsl. Allows you to define a mapping closure which then in turn allows you to define each table/column name, column type, foreign keys names, should the 'm' part be mapped back using a new column or a new jointable, etc. 1:m's are typically Sets. To make it sorted, just make it a SortedSet in your domain class and implement Comparable in the m part. For our quiz, random or near-random behaviour was just right. By default, domain classes are configured for optimistic locking. Each domain class has a version column. Querying... we will see a quick example in the next part.
  • dynamic scaffolding on the fly views & controller quick prototypes 11 Dynamic scaffolding → there is also static Dynamic: each view and the controller who receives the requests is generated on the fly, not written to disk as a file. Benefit: quick changes to domain model to get it right. The views and controller adjust automatically. It is not very performant, that's why it is used only in the early stages of a project Most devs switch to static scaffolding after a few days and after the domain model is confirmed. Static means views and controller are editable on disk. If they are on disk, it means you can take a look. And that means that you got perfect, domain-relevant examples for the CRUD actions right in front of you. Scaffolding is a really great learning tool, it will get you up to speed in no time. A lot of websites now used scaffolded views as their administrative backends. A few tweaks to the sitemesh layout of the admin pages here and there and we're good to go. The frontend pages are still heavily customized, but often the backend does not have to be as pretty as the front door. Grails allows you to install all templates so you can create your companies default scaffolded look and feel. Also, the Xtemplates plugin was recently released. It allows you to create templates for more than the standard CRUD behaviour or internationalized templates.
  • coding2 adding some test data into the DB, creating a basic quiz UI and writing the quiz controller 12
  • URL mapping controller/action/id easy customization 13 TODO
  • BootStrap .groovy test data great for demos HSQLDB 14 The BootStrap is a great place to create some test / development data. Once the BootStrap's init() is executed, you have a fully functional Grails app in memory. To create your test data, the Grails Fixtures plugin recently provides great support. It allows you to create a graph of domain objects that can be used to initialize the database for each test run or in development mode. The syntax is very easy to understand and allows lazy referencing, e.g. reference objects that are later created in the fixture.
  • Gr ai ls beans { Fi x easyQuestion(Question) { tu re title = quot;Which color is #00FF00?quot; s answers = [red, green, blue] } red(Answer) { title = quot;Redquot; } green(Answer) { title = quot;Greenquot; correctAnswer = true } blue(Answer) { title = quot;Bluequot; } } 15 This would an example using the Grails Fixtures Plugin (which was just released in October, it is v0.1) Use it to define a dataset during development or for your integration tests. You will have the same, predictable data each time you start your application. Fixtures can be saved in the fixtures folder, based on your needs you can activate different fixtures (e.g. based on the integration test you run) The Plugin uses the Spring Bean DSL of Grails. You can use it to extend the Spring config that Grails creates under the hood. fixtureLoader.load(quot;somefixturequot;)
  • SiteMesh layouts out of the box easy customization one place 16 Grails comes with SiteMesh preconfigured. The scaffolded views all use the main layout, which is defined in the layout's directory main.gsp file Again, as you always got one example, creating your own layouts is easy. Copy and paste the initial layout and the Grails Documentation tells you the rest The three tags you need to be aware of are layoutHead & layoutTitle, layoutBody. To specify the layout, use the layout meta tag in <head> :<meta name=quot;layoutquot; content=quot;mainquot;></meta> Or use layout by convention. Create layout/<domain> and it will be used by all <domain>Controller views.
  • GSP taglibs similar to JSP built-in taglibs custom taglibs 17 Grails comes with a lot of built-in tags, like logical (if/else), iterative(while/each but also cool stuff like grep or findAll), form and validation tags. Grails also has AJAX tags that by default will use prototype, but will switch to YUI or Dojo based on what you import in the head. You can get a small taste of Grails Real Power when you see how easy it is to create your own tag library. While you make changes, you don't even have to restart the server... let's see.
  • <g:each in=quot;${questions}quot; var=quot;questionquot;> <div class=quot;questionquot;> <div class=quot;questionTitlequot;>${question?.title}</div> <g:each in=quot;${question.answers}quot; var=quot;answerquot;> <g:link action=quot;answerquot; id=quot;${params.id}quot;>${answer?.title}</g:link><br/> </g:each> </div> </g:each> <g:each in=quot;${questions}quot; var=quot;questionquot;> <g:renderQuestion question=quot;${question}quot;/> </g:each> 18 We want to change the above code, which is quite verbose, into the below code. The idea is that there are many views that have to render questions sometimes. So we put the whole question rendering into a tag and can reuse the renderQuestion tag. Makes sense?
  • class QuizTagLib { def renderQuestion = { attrs -> out << render(template:quot;questionTemplatequot;, model:[question:attrs.question]) } } <div class=quot;questionquot;> <div class=quot;questionTitlequot;>${question?.title}</div> <g:each in=quot;${question?.answers}quot; var=quot;answerquot;> <g:link action=quot;answerquot; id=quot;${params.id}quot; >${answer?.title}</g:link><br/> </g:each> </div>h> 19 We will first define a QuizTagLib.groovy file in grails- app/taglibs All we do in the taglib is render the questionTemplate. That way, we keept the GSP code in the template fiel and do not mix it up with the rest of the code. The questionTemplate simply contains the previous markup we iterated over. The benefit is that we now got a single place to make changes to question rendering and we can use an easy to remember tag, the renderQuestion tag.
  • grails controllers scopes injected methods 20 In the Demo, we created our first real controller, the QuizController. Controllers respond to requests and create or prepare the response. Controllers are request scoped, each new request = a new controller instance. Controllers have actions, which are simple groovy closures. The controller itself is just an ordinary groovy class, but it needs to be saved in the grails-app controllers directory. The URLMapping we quikly touched is responsible for matchign each incoming request with a controller and an action in that controller. (more next slides....) Each controller has automatically access to scopes, which are hash-like objects. In our example, we used the flash scope. * servletContext - Also known as application scope, this scope allows you to share state across the entire web application. The servletContext is an instance of javax.servlet.ServletContext * session - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of HttpSession * request - The request object allows the storage of objects for the current request only. The request object is an instance of HttpServletRequest * params - Mutable map of incoming request (CGI) parameters * flash - See below. Grails supports the concept of flash scope is a temporary store for attributes which need to be available for this request and the next request only. There are also a bunch of methods available, like the realy powerful render method or simple ones like the redirect methdod . Let's look first at some examples for render and then let's take a look at data binding.
  • render() render quot;makes my ajax calls happyquot; 21 This will simply render some plain text to the response. Pretty basic, but exactly what we often need to do in really simple AJAX calls.
  • render() render( text:quot;<xml>plain xml</xml>quot;, contentType:quot;text/xmlquot;, encoding:quot;UTF-8quot; ) 22 Also pretty obvious, we now return a piece of xml we have built ourselves and set the right content type. Nothing fancy, but again something we often need to do for AJAX calls.
  • render() render( template:quot;questionTemplatequot;, model:[question:questionObject] ) render( view:quot;showquot;, model:[question:questionObject] ) 23 Shows two examples for rendering GSP templates. The first one renders a tempalte file, it will be called _questionTemplate.gsp and lives in the view/controllerName/ directory. We pass a quesitonObject under the name 'question'. The GSP can then access ${question} The second example will do the same, but in this case we pass the question object to the view called 'show'. Grails will look for show.gsp in the views/controllerName/ directory.
  • render() def list = Question.list() render(contentType:quot;text/xmlquot;) { questions { list.each { q -> question(title:q.title,level:q.level) } } } 24 This is a somewhat advanced example of wrting some XML back to the client. In this case we use groovy's XML Builder and have total control of what is being rendered. We can iterate with each() over the question list and then write any attributes we want. Let's look how this would look like.
  • <questions> <question title=quot;Who is...quot; level=quot;easyquot;/> ... </questions> 25 BTW, there is also a JSONBuilder, so the same response would be as easy in JSON. Simply use contentType:text/json instead.
  • render() render Question.list() as XML render Question.list() as JSON 26 The easiest option if you don't care too much how much you are writing to the response is this. You give up control over how the xml structure looks like. Let's try that out. Create a new action to demonsrate XML in QuizController def questionsAsXml = { render Question.list() as XML } There are two types of XML converters, the 'normal' one and the 'deep' converter. The normal converter will render the first level of properties and then references to the deeper objects like answer. Deep will render it all.
  • GORM easy in and out 27 GORM is a really powerful O/R Mapping technology, based on Hibernate. It provides Grails an easy was to get data into the DB and also out again. We could talk about this for hours, but there's not much time. Gorm supports all possible associations, Compositon, Inheritance, Mapping of Sets/Lists/Maps, eager/lazy fetching, pessimistic and optimistic locking (default optimistic using version column) For special cases, there is the ORM DSL. Allows you to map to different than convention table names, columns, express specific column types, etc.
  • easy in def question = new Question(params) question.save() 28 This is basically about data binding. Data binding is the act of quot;bindingquot; incoming request parameters onto the properties of an object or an entire graph of objects. Data binding should deal with all necessary type conversion since request parameters, which are typically delivered via a form submission, are always strings whilst the properties of a Groovy or Java object may well not be. Grails uses Spring's underlying data binding capability to perform data binding. In this example, the domain classes' implicit constructor is used. It will bind all matches of incoming parameter names to the properties names. For security resons, you might want to use the bindData method in controllers. With that method, you can exclude properties from being set.
  • easy out Question.findAllByLevel(quot;easyquot;) Question.findAllByCreatedBetween(a, b) Question.findByTitleLike(quot;%Graeme%quot;) 29 GORM makes it easy to get your data back, too. This is about querying the database. You can use dynamic finders, criterias or the HQL. In this example we just show some dynamic finders, Critieras and HQL are pretty much the same as in standard Hibernate. The possible comparators include: * LessThan - less than the given value * LessThanEquals - less than or equal a give value * GreaterThan - greater than a given value * GreaterThanEquals - greater than or equal a given value * Like - Equivalent to a SQL like expression * Ilike - Similar to a Like, except case insensitive * NotEqual - Negates equality * Between - Between two values (requires two arguments) * IsNotNull - Not a null value (doesn't require an argument) * IsNull - Is a null value (doesn't require an argument)
  • coding3 pushing the app into mor.ph AppSpace and making it publicly available 30
  • community extremely active friendly tons of resources g2one
  • marc palmer Together with Graeme Rocher, Marc has created the excellent Grails dpcumentation and has also contributed several plugins. Among those are the mail plugin, the authentication plugin or the feeds plugin. All plugins share the common theme that they are easy to use and most show a demo functionality right out of the box after installing. Besides this, he is an awesome awesome speaker and if you have a chance to see him live, go for it. Blog at http://www.anyware.co.uk/
  • marcel overdijk Marcel is the Uber-Plugin creator. He literally wrote so many plugin I cannot even name them all. Among the most prominent plugins are probably the YUI and the Xtemplates plugins (among others like I18N templates, RefCode, OpenID, Ext plugin, Sifr Plugin, PeekInGrails) Xtemplates provides extensible template capabilities for static scaffolding. The default scaffolding templates are limited to generate list, create, edit and show views. With the xtemplates plugin you can generate any number of views. In the xtemplates generation process also a runtime loaded Helper class (which can be customized just like the templates) is binded so you can execute any code in the generation process.
  • peter ledbrook Last but not least, Peter ledbrook is also a serial plugin creator plus provided a tremendous amount of Grails Mailing List support over the past months. The most prominent plugin he authored is probably the Jsecurity Plugn, it provides security features like authentication and authorization for very little configuration. A plugin to watch out for (or not as it will be in Grails 1.1) is the testing plugin. It will provide easy unit testing support for all grails artefacts. UrlMappings, Controllers, Tag libaries, etc. Peter is also co-authoring GRIA, Grails in Action, which might hit the shelves early 2009.
  • what else? some more resources about Groovy, Grails & Griffon 35 The website to hear the official voice of grails is of course grails.org. There you will find the excellent online documentation, links to mailing lists and every thign else. Now as Grails grew really fast, it is already quite tough to keep up with all the news. There are two websites I would like to mention here that help to reduce the clutter. The first is ...
  • groovymag.com svjugnov08 36 The first issue of GroovyMag was just released this month. It comes as a PDF document and can be purchased at groovymag.com for 5$ via Paypal. The first issue features an excellent getting started tutorial by Robert Fischer. It will introduce you to Grails in a similar way the demo in this session did. Go grab this issue if you seriously want to get into Grails and do the first step. Other topics include groovy & Grails news, also news and info about Griffon by Andres Almiray – who is here in the audience, too!
  • 37 GroovyBlogs.org. It scans several hundred groovy/grails/griffon blogs and shows you the most recent or most popular entries. It was created by Glen Smith who is an early Groovy & Grails supporter and joined me in podcasting this year. So, the second website, is – shameless plug – the website of our grails podcast.
  • 38 Glen and Me publish a new podcast about every two weeks and we aggregate the news we heard of the last two weeks into each episode. We have about 70 episodes by now, interviews with the key Grails contributors like Graeme Rocher the current Grails Project lead or Guillaume Laforge the Groovy Project lead. Each episode includes a SoapBox, that's one topic we speak about a bit longer. Typically it is a new plugin or some development methodology, how to test, etc. Have a listen, go to grailspodcast.com and subscribe to our RSS feed or listen right on the page.
  • we're on twitter @grailspodcast 39
  • thx Jason rudolph for his great open source Grails Slides, Matthew Fang for the intro slide image (CC), alidarbac for the community soccer photo (cc), Zeno_ for the sounds of complexity image (cc), Andres Almiray for suggesting me for a GRAils presentation at JUG, thomas lopatic for reviewing the presentation, the groovy & Grails community for all the great news, glen smith for podcasting with me. IF you have read that far you are a super brave reader. Listen to the grails podcast. www.grailspodcast.com grails.org 40