SlideShare a Scribd company logo
1 of 80
Download to read offline
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
Grails @ Java User Group Silicon Valley
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
Grails @ Java User Group Silicon Valley
Grails @ Java User Group Silicon Valley
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

More Related Content

Similar to Grails @ Java User Group Silicon Valley

Griffon - Making Swing Fun Again
Griffon - Making Swing Fun AgainGriffon - Making Swing Fun Again
Griffon - Making Swing Fun AgainDanno Ferrin
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails IntroductionEric Weimer
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Tugdual Grall
 
IPhone Web Development With Grails from CodeMash 2009
IPhone Web Development With Grails from CodeMash 2009IPhone Web Development With Grails from CodeMash 2009
IPhone Web Development With Grails from CodeMash 2009Christopher Judd
 
Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008Jeffrey Clark
 
Introduction to segmentation fault handling
Introduction to segmentation fault handling Introduction to segmentation fault handling
Introduction to segmentation fault handling Larion
 
Java to Golang: An intro by Ryan Dawson Seldon.io
Java to Golang: An intro by Ryan Dawson Seldon.ioJava to Golang: An intro by Ryan Dawson Seldon.io
Java to Golang: An intro by Ryan Dawson Seldon.ioMauricio (Salaboy) Salatino
 
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGuillaume Laforge
 
Spring boot 3g
Spring boot 3gSpring boot 3g
Spring boot 3gvasya10
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
Spring-batch Groovy y Gradle
Spring-batch Groovy y GradleSpring-batch Groovy y Gradle
Spring-batch Groovy y GradleAntonio Mas
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기YoungSu Son
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with RubyAnis Ahmad
 
Tales from the Field
Tales from the FieldTales from the Field
Tales from the FieldMongoDB
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 

Similar to Grails @ Java User Group Silicon Valley (20)

Spring ME JavaOne
Spring ME JavaOneSpring ME JavaOne
Spring ME JavaOne
 
Whats New In Groovy 1.6?
Whats New In Groovy 1.6?Whats New In Groovy 1.6?
Whats New In Groovy 1.6?
 
Griffon - Making Swing Fun Again
Griffon - Making Swing Fun AgainGriffon - Making Swing Fun Again
Griffon - Making Swing Fun Again
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails Introduction
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007
 
IPhone Web Development With Grails from CodeMash 2009
IPhone Web Development With Grails from CodeMash 2009IPhone Web Development With Grails from CodeMash 2009
IPhone Web Development With Grails from CodeMash 2009
 
Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008Bfg Ploneconf Oct2008
Bfg Ploneconf Oct2008
 
Introduction to segmentation fault handling
Introduction to segmentation fault handling Introduction to segmentation fault handling
Introduction to segmentation fault handling
 
Java to Golang: An intro by Ryan Dawson Seldon.io
Java to Golang: An intro by Ryan Dawson Seldon.ioJava to Golang: An intro by Ryan Dawson Seldon.io
Java to Golang: An intro by Ryan Dawson Seldon.io
 
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
 
Spring boot 3g
Spring boot 3gSpring boot 3g
Spring boot 3g
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Spring-batch Groovy y Gradle
Spring-batch Groovy y GradleSpring-batch Groovy y Gradle
Spring-batch Groovy y Gradle
 
닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기닷넷 개발자를 위한 패턴이야기
닷넷 개발자를 위한 패턴이야기
 
GWT Extreme!
GWT Extreme!GWT Extreme!
GWT Extreme!
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
Tales from the Field
Tales from the FieldTales from the Field
Tales from the Field
 
GAEO
GAEOGAEO
GAEO
 
GAEO
GAEOGAEO
GAEO
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 

More from Sven Haiges

NFC and Commerce combined
NFC and Commerce combinedNFC and Commerce combined
NFC and Commerce combinedSven Haiges
 
End to End Realtime Communication using Mobiel Devices and the Web
End to End Realtime Communication using Mobiel Devices and the WebEnd to End Realtime Communication using Mobiel Devices and the Web
End to End Realtime Communication using Mobiel Devices and the WebSven Haiges
 
NFC Android Introduction
NFC Android IntroductionNFC Android Introduction
NFC Android IntroductionSven Haiges
 
Gesture-controlled web-apps
Gesture-controlled web-appsGesture-controlled web-apps
Gesture-controlled web-appsSven Haiges
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
NFC on Android - Near Field Communication
NFC on Android - Near Field CommunicationNFC on Android - Near Field Communication
NFC on Android - Near Field CommunicationSven Haiges
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishGrails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishSven Haiges
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006
Grails 0.3-SNAPSHOT Presentation WJAX 2006Grails 0.3-SNAPSHOT Presentation WJAX 2006
Grails 0.3-SNAPSHOT Presentation WJAX 2006Sven Haiges
 

More from Sven Haiges (11)

NFC and Commerce combined
NFC and Commerce combinedNFC and Commerce combined
NFC and Commerce combined
 
End to End Realtime Communication using Mobiel Devices and the Web
End to End Realtime Communication using Mobiel Devices and the WebEnd to End Realtime Communication using Mobiel Devices and the Web
End to End Realtime Communication using Mobiel Devices and the Web
 
NFC Android Introduction
NFC Android IntroductionNFC Android Introduction
NFC Android Introduction
 
Gesture-controlled web-apps
Gesture-controlled web-appsGesture-controlled web-apps
Gesture-controlled web-apps
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
NFC on Android - Near Field Communication
NFC on Android - Near Field CommunicationNFC on Android - Near Field Communication
NFC on Android - Near Field Communication
 
Android UI
Android UIAndroid UI
Android UI
 
Html5
Html5Html5
Html5
 
Grails and Dojo
Grails and DojoGrails and Dojo
Grails and Dojo
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishGrails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006
Grails 0.3-SNAPSHOT Presentation WJAX 2006Grails 0.3-SNAPSHOT Presentation WJAX 2006
Grails 0.3-SNAPSHOT Presentation WJAX 2006
 

Recently uploaded

UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 

Recently uploaded (20)

20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 

Grails @ Java User Group Silicon Valley

  • 1. g ra ils Sven Haiges , Nov 18 g 2 leplex , 008, JU G Meeti ng, Goo A in View, C Mounta
  • 2. spring MVC hibernate sitemesh groovy
  • 3. Flexibility = Complexity
  • 5. convention over configuration
  • 7. coding1 creating the domain model, applying some validaton and scaffolding the rest
  • 8. convention over configuration
  • 9. NetBeans IDE free groovy grails griffon
  • 10. domain class mapping& validation easy 1:1, 1:n, m:n validation constraints
  • 11. dynamic scaffolding on the fly views & controller quick prototypes
  • 12. coding2 adding some test data into the DB, creating a basic quiz UI and writing the quiz controller
  • 13. URL mapping controller/action/id easy customization
  • 14. BootStrap .groovy test data great for demos HSQLDB
  • 15. 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; } }
  • 16. SiteMesh layouts out of the box easy customization one place
  • 17. GSP taglibs similar to JSP built-in taglibs custom taglibs
  • 18. <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>
  • 19. 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>
  • 20. grails controllers scopes injected methods
  • 21. render() render quot;makes my ajax calls happyquot;
  • 22. render() render( text:quot;<xml>plain xml</xml>quot;, contentType:quot;text/xmlquot;, encoding:quot;UTF-8quot; )
  • 23. render() render( template:quot;questionTemplatequot;, model:[question:questionObject] ) render( view:quot;showquot;, model:[question:questionObject] )
  • 24. render() def list = Question.list() render(contentType:quot;text/xmlquot;) { questions { list.each { q -> question(title:q.title,level:q.level) } } }
  • 25. <questions> <question title=quot;Who is...quot; level=quot;easyquot;/> ... </questions>
  • 26. render() render Question.list() as XML render Question.list() as JSON
  • 27. GORM easy in and out
  • 28. easy in def question = new Question(params) question.save()
  • 30. coding3 pushing the app into mor.ph AppSpace and making it publicly available
  • 35. what else? some more resources about Groovy, Grails & Griffon
  • 40. 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
  • 41. 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.
  • 42. 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)
  • 43. 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.
  • 44. 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.
  • 45. 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....
  • 46. 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.
  • 47. coding1 creating the domain model, applying some validaton and scaffolding the rest 7
  • 48. 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
  • 49. 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.
  • 50. 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.
  • 51. 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.
  • 52. coding2 adding some test data into the DB, creating a basic quiz UI and writing the quiz controller 12
  • 53. URL mapping controller/action/id easy customization 13 TODO
  • 54. 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.
  • 55. 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;)
  • 56. 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.
  • 57. 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.
  • 58. <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?
  • 59. 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.
  • 60. 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.
  • 61. 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.
  • 62. 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.
  • 63. 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.
  • 64. 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.
  • 65. <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.
  • 66. 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.
  • 67. 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.
  • 68. 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.
  • 69. 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)
  • 70. coding3 pushing the app into mor.ph AppSpace and making it publicly available 30
  • 72. 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/
  • 73. 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.
  • 74. 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.
  • 75. 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 ...
  • 76. 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!
  • 77. 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.
  • 78. 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.
  • 80. 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