Tuesday, October 27, 2009

RSS Builder in Grails in a Few minutes

As I planned to include RSS feeds into www.spenddaywithkids.com I needed possibility to create kind of RSS Builder. The good example of what I needed is IceRocket RSS Builder. So you are not generating RSS feeds directly from the data on your site but you are writing them manually. This way RSS feeds become kind of communication channel between the web site and users.

I would stay with IceRocket but I couldn’t find possibility to do even simple formatting for RSS items. So my thought was let see how it is complicated to do it in Grails. And it turned out that it takes only few minutes to get very similar functionality. So here is short example done almost step by step.

Note: As my site is currently running on Grails 1.0.3 maybe not everything will be compatible with 1.1 version out of the box.

So let go with implementation.

First create grails application and named it rssbuilder.

grails create-app rssbuilder
Then create two domain classes:
class RssChannel {
String name
String channelLink
String description

static constraints = {
name(blank:false, nullable:false, unique:true)
channelLink(blank:false, nullable:false, unique:false, url:true)
description(blank:true, nullable:true, maxSize:30000)
}
}


class RssItem {
String title
String itemLink
String summary
RssChannel rssChannel
Date dateCreated
Date lastUpdated

static constraints = {
title(blank:false, nullable:false, unique:false)
itemLink(blank:false, nullable:false, unique:false, url:true)
summary(blank:false, nullable:false, unique:false, maxSize:50000)
rssChannel(blank:false, nullable:false, unique:false)
}
}
Ah, don’t forget to install two plugins: Feeds Plugin and RichUI plugin.

Now we can generate controllers and views for two domain classes:
grails generate-all RssChannel
grails generate-all RssItem
Well now if you start application you are able to specify RSS channel and items for RSS channel. To provide possibility to specify better formatting for RssItem we can reuse <richui:richTextEditor tag from the RichUI plugin. In the create and edit view of the RssItem change summary and bind it to the richTextEditor. More or less you should input tag with the following:

<richui:richTextEditor name="summary" value="${rssItem?.summary}" width="525" height="525" />
Now to generate RSS feed we can reuse functionality of the Feed plugin. So create FeedController class with command grails create-controller Feed.

The code of the feed controller should be:

    def rss = {
if (!params.id) {
render "missing id in params"
return
}

RssChannel rssChannel = RssChannel.get(new Long(params.id))

if(!rssChannel) {
render "rss channel not found"
return
}


render(feedType:"rss", feedVersion:"2.0") {
title = rssChannel.name
link = rssChannel.channelLink
description = rssChannel.description
RssItem.findAllByRssChannel(rssChannel, [sort:"dateCreated", order:"desc"]).each() { item ->
entry(item.title) {
link=item.itemLink
item.summary
}
}
}
}
So now if you start application and create RSS channel and some items in that channel all you need to know is ID of that channel.

If the Id of the channel is e.g. 1 in the browser write http://localhost:8080/rssbuilder/feed/rss/1 and you will see your feed.

I believe this was really easy :)

As soon as I switch fun places to go with kids to the Grails 1.1 I will create plugin from this.

Monday, October 26, 2009

Grails scaffolding for domain classes in packages

While working on one simple subproject for spend day with kids I got one interesting issue. I don't use scaffolding too often but this time I needed to get proof of concept. And I came to something where I am not sure if it is a bug or feature. And just to be clear this is happening with Grails version 1.0.3 and I am not sure if it is reproducible in later versions.

Note: Having packages for domain classes is highly advisable and you should always use packages for all domain classes.
So let get to the point. I have create following domain class (please notice that package is defined).

com.jan.rssbuilder.domain.RssChannel
And after that I have created RssChannelController this way:
package com.jan.rssbuilder.domain

class RssChannelController {
def scaffold = true
}
After accessing this controller I got following exception:
java.lang.IllegalStateException: Scaffolder supports action [index] for controller [com.jan.rssbuilder.domain.RssChannelController] but getAction returned null!
After changing controller by specifying domain class everything worked fine:
package com.jan.rssbuilder.domain

class RssChannelController {
def scaffold = com.jan.rssbuilder.domain.RssChannel
}

Sunday, October 18, 2009

Tips for working with front-end in Grails

I have implemented few web projects with Grails and some techniques while working with Grails front-end turned out to be better than other. When I didn’t follow them later on I usually had to refactor the code and did it the correct way.

If you are reading this blog you noticed that I write very often about developing front-end with Grails. The reason is not that I am the best in the front-end but the reason is that I am the worst in the front-end. I am back-end developer and what I was missing in the majority of web frameworks was impossibility to make front-end more modular. In Grails this is easily to achieve thanks to Grails templates and tags. And then you are almost to code in the normal java code.

But come back to tips.

Tip 1: Always create one gsp page per state of the result.

Tip 2: Use templates and tags to make your pages more modular.

Tip 3: When ever it gives sense send custom model classes to the gsp page (not the domain classes).

Well tips are nothing without some example. As an example I will take my latest project fun things to do with kids.

In the first installment home page had following responsibilities:

  • As a starting point for visitors
  • To display found places to go with kids
  • To inform user that the city provided cannot be uniquely identified (there is more than one city with provided name)
  • To inform user that no attractions were found around provided city

As you can see that is obvious break of the SRP (single responsibility principle). Because of too much responsibilities the model I was sending to the page was quite complex and the page contained number of if blocks. And you must admit that having if blocks in the html page is not the best practice. Another side effect was that page had about 300 lines that is simply too much.

So what I did? Well, of course I did some refactoring.

I have created one page per responsibility and depending on result controller decide which page to display and provides correct data model (is this maybe kind of strategy pattern?). This way it is much easier to understand what pages are doing. And now they are up to 30 lines long.

But if you check pages you can see they are quite similar:

To see home page navigate to: spend day with kids
To see page with results navigate to: things to do with kids in Nottingham
To see page where there are multiple cities e.g. search for Malinovo. Select Malinovo, Slovakia to see places to visit nearby my home :)
To see page where there are no results check e.g. for Belgrade.

If you checked all these pages you can notice that they are very similar but little bit different. So how do you solve similarities. Very easy. Use templates and tags.

And the last but not the least, it is obvious that the data models delivered to the pages can be quite different and even some cases need not to contain any domain classes.

So I hope that those tips will help you while working on your own grails projects.

Saturday, October 17, 2009

New features on spend day with kids

I have finally found some free time so I decided to implement some new features on spend day with kids.

So far all searches have been performed with the same default parameters. The defaults were distance is 100 kms and the sorting of attractions was by type.

Very soon after the launch of the site I got mail from Jeff where he proposed that results should be displayed in the order of proximity from the provided city. I liked the idea immediately and now this feature is supported.

So now you can provide city or even address and specify the distance of places to be searched and additionally to select ordering type. Possible ordering types are of course by distance and by city.

As you probably know spend day with kids site helps you find great family days out and is implemented with Grails. While developing this site, so far I didn't hit any special interesting features that could be worth for blogging about. But if you have any ideas just let me know

Saturday, October 10, 2009

Hope to have more material for blogging

I am aware that last few weeks I was quite lazy with blogging but as I was changing employer so lot of responsibilities have been in front of me. Of course, important part was knowledge transfer. From the October I am in my new company.

First I would like to thanks my previous company for having a chance to work on interesting and exciting projects.

In the new company I am coming to the position of Head of Software Development. It is a small start up company and we are working on the green field project. Yes, you see it right, its green field :)

As my future work will include some new technologies and different market I hope that I will have lot of materials for blogging. We will mainly work with affiliate networks and mobile web development. As this is quite new field for me I believe I will be able to share a lot of interesting discoveries.

As the field we will be working in is very dynamic we are of course on Scrum and agile software development. Dynamic projects and agile software development create great combination. I am very sure we will have lot of fun.

Wednesday, October 7, 2009

Software books reviews down - permanently (so far)

It has been some time as I planned to take down software books reviews. Although I don't think that the idea was bad it takes time to make the site grow and support from the community was not so good.
As running site takes some money, lot of time and I have two other sites online too: grails tutorials and things to do with kids I have to choose which one to take down.
So my decision was to take down the software books reviews.

Now I want to be able to concentrate on my new work and to try to extend functionality of the spend day with kids site. I promised few months ago that I will open source grails tutorials and I still plan to do that. The problem is that I need few days of additional work before I open source it and I am not able to find those day.

So for all that were visiting software books reviews, sorry but I had to take it down.

Sunday, September 27, 2009

Getting data into Grails tags and templates

In the post describing how to create and use grails templates and tags I made short example that showed how gsp pages can be readable if you are using tags and templates. One of the questions asked in comments was how do I get data into tag and/or template. Instead writing answer as comment I decided to write the whole post.

Scoped variables
Common way to get data into tag and template is using Grails scoped variables like application, session, request. This means that both, tags and templates, have access to those variables so you can use them.

Templates
To send data into templates you can and should use standard approach with the grails model.

For example if you are rendering template from tag or from controller (or some groovy code) you should use construct like this one:

render(template:"/templates/common/messageBoxTemplate", model:[title:"hello world"])

If you are rendering template from gsp page you should use construct like this one (actually taken from grails documentation):

<g:render template="displaybook" model="['book':book,'author':author]" />

To be honest I try to avoid using <g:render... from gsp pages because if you are using tags it is easier to read the gsp page. Another advantage of using tags is that it is easier to refactor the gsp pages. So when you find yourself writing <g:render template.... in the gsp page, introduce grails tag for that.

Tags

The advantage of tags is that they have access to the GORM classes and you can inject any grails service into tag. So if you need to perform some calculation that needs to be displayed on the gsp page tag is the right place for that.

Another way to send data into grails is via attrs map. Each tag is specified in the file ending with TagLib and the format of the tag is:

def messageBox = {attrs, body ->
out << render(template:"/templates/common/messageBoxTemplate", model:[title:attrs.title, body:body()])
}

So tag is closure with two variables: attrs and body. Using attrs you can access any custom data sent to the tag.

So how do we send that data?

When displaying tag from the gsp page you are using construct like this one:

<g:messageBox title="Register, it takes only seconds">

In this case the title is custom data sent to the tag.

To execute given tag from the controller or some other groovy code you can use construct like this one:

g.messageBox(title:"Register, it takes only seconds") {
//body to be displayed
}

So for example, to display number of registered users on the grails and groovy tutorials page I am using direct access to database from the tag and then sending those data to the model. But I could also create e.g. application scoped variable for this and gain some performance. So currently the code in the tag looks like this:

def dataInfo = {attrs, body ->
def postsCount = TutorialLink.count()
def userCount = User.count()
out << render(template:"/templates/common/statsTemplate", model:[userCount:userCount, postsCount:postsCount])
}

Monday, August 17, 2009

Agile, TDD and upfront desing

As TDD and agile software development are emerging as more and more used technologies for software development lot of software developers are jumping into it without having real knowledge.

From my point of view one of the misconceptions about TDD and agile is that you don't need any design and architecture upfront. TDD with refactoring will give me the right architecture in all cases.

Although I am big fun of agile software development I don't believe this is idea of the agile. Agile is here to help develop better software for better customer satisfaction. But it in no cases claims that you should forget about big picture, about documentation and about having at least basic understanding of your system design.

From my point of view you need to do basic design at least at the high level. Then for important parts you need to go to lower levels (if really necessary). And then agile together with TDD will help you to really get it right. To separate concerns, to make separation between domain objects in different tiers and so on.

So as conclusion, agile does not mean no more thinking. Agile means think about the problem, do basic planning and then use TDD and other agile tools to get it right.

Monday, August 10, 2009

g:form, g:actionSubmit and Internet Explorer 8

While working on my latest grails powered web site things to do with kids I have noticed that one form performs ok in Firefox and Chrome but not in Internet Explorer. If this would be case with grails tutorials I wouldn't care too much because majority of visitors have Firefox or Chrome. But my statistics for things to do with kids are showing that there is more visitors using IE than other browsers.

The problem was following. E.g. on the home page of things to do with kids you enter the city name and then press enter on your keyboard. In Firefox and Chrome you get the list of places to visit but in IE8 nothing happened.

But if you used tab to move focus on the Show Me button then everything worked also in IE.

The initial code looked like this:

<g:form controller="home" method="GET">
<input name="locationName" class="span-10 last" />
<g:actionSubmit value="Show me" action="placesAroundLocation" />
</g:form>

After some investigation I noticed that closure called from IE was actually index in the HomeController. So this means that in IE8 when enter is pressed while focus is in the input box default action of the controller is called while in Firefox and Chrome action of the button was called.

So to fix the problem with the IE I have slightly change the code. I added form default action so now it looks like this:

<g:form controller="home" action="placesAroundLocation" method="GET">
<input name="locationName" class="span-10 last" />
<g:actionSubmit value="Show me" action="placesAroundLocation" />
</g:form>

I didn't check behavior in other versions of IE but if you have similar problem this may help you.

Tuesday, July 28, 2009

You don't need session in Grails service

From time to time there are questions or blog posts that explain how to obtain access to web session from the grails service or domain class. If you really need to access session from the service class e.g. this post from Robert can help you.

But before you start reusing session in your services or even domain classes be careful and think if you really want that. Service should be more or less simple Java class and when ever possible should not depend on special environment classes. And session is actually very special web application environment class.

So what to do if in the service you really need that value from the session? Well the answer is of course very simple. Send it as a method parameter. Or another way is Robert's approach to create service that will return that value from session and inject it into service that really needs that value.

This way your services will not depend on the web container context and you can easily port them to other environment.

Tuesday, July 21, 2009

UK included on spend day with kids

As you may know few weeks ago I have launched spend day with kids web site. In the first release only USA was covered but yesterday I have finished entering attractions for UK.

So please feel invited to visit spenddaywithkids.com and search for ideal places to have a day full of fun with your kids.

Friday, July 17, 2009

Groovy and Grails help build apps faster

Actually this is not my post but a very interesting article about productivity gained using Grails and Groovy.

Usually I am not posting links to other articles but my feeling is that this one deserves this. I didn't notice link to this articles on other grails/groovy related sites so I want to share it.

So navigate to "Groovy and Grails help build apps faster" to read the whole case.

Sunday, July 5, 2009

Spend day with kids Grails web app launched

I have launched new Grails powered web site www.spenddaywithkids.com.

Idea of the web site is to help you find interesting places where you can go with kids. There are places like zoos, water parks, theme parks....

Developing this application was interesting for me because this was for me the first time I used google maps in some of my application. Also new for me was geocoding but actually this turned out to be as easy as reuse formulas available online. Currently on USA is covered but Europe should come soon.

Currently I have three sites online: grails tutorials, software books reviews and spend day with kids.
For me it is just prove that development of web applications with Grails is easy and fun but know I will concentrate on extending my existing site and hope I will not get any fun idea soon :)

Let me know if you have some proposals for any of mentioned sites.

Tuesday, June 30, 2009

Book Review: Grails in Action

I was lucky enough to get copy of the book Grails in Action from Manning. And of course I have promised to write review of the book.

My feelings about the book are somehow mixed. Basically book is divided into four parts:
  • Introducing Grails
  • Core Grails
  • Everyday Grails
  • Advanced Grails
The first two parts, Introducing Grails and Core Grails, are for more or less newcomers to the Grails so if you already have experience with Grails they are somehow boring. That wouldn't be a problem if my opinion wouldn't be that they are not written in an appropriate way for the Grails/Groovy beginners. My feeling is that beginners will get confused as the authors jump too much directly into action. So my advice for the beginners is to read e.g. Getting Started with Grails and then come back to the book Grails in Action.

But even if you already have Grails experience don't just skip over the first two parts, because after having some Grails foundation the first two parts become very useful and very easy understandable. Even for me (and I have some experience with Grails) there were useful information and discoveries.

Very good approach in this two parts from the authors is that they have devoted lot of energy to explain how to test Grails application. This is something I should definitely start to do on my own projects :)

The real fun comes with the second two parts - Everyday Grails and Advanced Grails. I have really enjoyed reading chapters from those parts. They are very nice and are really covering lot of skills you will need during real Grails projects.

In the third part authors are explaining how not to reinvent wheel by using number of available plugins. They show you how to fast and reliably put together advance features by reusing already existing functionality. I liked this approach and using it myself a lot.
There are also chapters devoted to workflows, exposing interface to outside world and using messaging.

After finishing third part you have really solid foundation to do some serious Grails development.

The fourth part is really advanced although I would include basic transactional behavior into at least third part of the book as this is probably more everyday grails than advanced grails. The fourth part will explain advance GORM related features, advance usage of spring and something you will for sure meet in the corporate environment - build and deploy process.

Conclusion
At the end I was very happy that I got a chance to read this book. This book will lead you from the beggining to the really advanced features of the Grails. If you are developing with Grails I am very sure you will have this book near you.
If you are just starting with Grails I would recommend, first read something simplier and then come back to this book. I am sure you will enjoy reading it.


And if you want to buy the book you can do it here :)


Sunday, June 14, 2009

Book Review: Becoming Agile

When I started to think that majority of agile books are somehow breaking DRY (don't repeat yourself) principle I was lucky enough to get a copy of the book Becoming Agile: ...in an imperfect world.

Introduction

What I liked the most in this book is that it is completely oriented to the real world. Therefore it will not try to teach you any of the existing agile frameworks but will help you to make your company (team) agile taking into account all constraints surrounding you. Book is oriented around agile principles and authors consider you environment agile if you are following agile manifesto principles.
Another value of the book is that agile introduction is taken from the complete beginning. From company readiness assessment up to the project deployment and spreading your agile process through out the whole company. The whole project lifecycle is covered. From the vision, through adapting idea to the deployment. This is something that I was missing the most in lot of books about agile.

Book follows imaginary company Acme media and its move toward more agile environment.
Getting started chapter will explain how to check your company readiness to adopt agile processes, ensure buy-in and inject agility into your existing process. When you have selected pilot project you are moving forward.

Kicking off
chapter explains how to make feasibility study and how to decide if you should continue or stop with the project.

If you decided to continue with the project Populating the product backlog chapter will show how to create product backlog, what means "just enough" for a feature card and how to estimate and prioritize the product backlog.

Enough information for scheduling creates release plan and explains in how much details you should plan your iterations. And don't forget that having plan is not enough. What you need is planning because during the project your plan will change for sure.

When you have release and iteration plan you can move to the Building the product chapter. You will see how to welcome change, how to apply agile principles into development and how to ensure that you have working software at the end of iteration.

Embracing change chapter cope with adapting to change requirements. It explains common reasons for requirement changes and how to adapt to them. Next parts of this chapter will show you how to plan deploying and how to improve your process using retrospective.

If your pilot project was successful you will want to spread the agile process throughout the company. The Moving forward chapter will help you with this process.

Rest of the book explains the whole process from two different points of view. In one chapter the overall diagram of the project lifecycle is displayed and shortly explained while another chapter contains text description of the overall process.

Conclusion
Although at the beginning I was not sure if I want to read this book I must admit I have really enjoyed reading the book. I believe that this book must be mandatory read for anyone who want to become member of agile community.
The only downside of the book is that it covers really wide area (complete project lifecycle) and thus after reading this book you will need to read other books to improve your knowledge about e.g. estimating, testing, writing good user stories...

I really recommend this book to everyone that already are or want to enter the agile world.



Tuesday, May 19, 2009

Analyzing domain of the problem - GORM classes

[From the series - creating software books reviews grails web application]

In the previous posts I have created basic empty grails application. All the steps done to get up to this point are linked in this post. When the basic layout of the application is prepared it is obviously time to analyze domain objects. Domain objects in the grails are called GORM (grail's object relational mapping). Database schema is automatically generated from GORM objects and they probably represent the most powerful feature of the grails framework.

As software books reviews site is about providing reviews for the books the main features that need to be covered by application are following.

Visitor comes to the web site. From here he can navigate through existing books and read reviews and summaries. Review can be written on the site or link to the web site with the review can be provided. Summary is expressed as number (from 1 to 5) of some book aspects. Visitor can register and then he is able to post reviews and summaries for the books. Additionally there are some tasks for the administrator like: moderating books, posting new books...

If I try to express this short description as a list of user stories we get following:

As visitor I want to register.

As registered user I want to login.

As visitor I want to see books and reviews/summaries of the books.

As registered user I want to post book review.

As registered user I want to post summary.

As administrator I want to moderate books (this is probably epic).

Although user stories should be implemented one by one it is not a mistake to make an overview of the whole system. So described system can be pictured like this:

domain_model

On the picture above I have depicted domain object classes that I will create for the sbr project. For those that already have some knowledge about GORM the class BookAuthor may be surprising. In the GORM it is possible to model "many-to-many" relationship directly. I don't like this way and most of the time I create additional domain class that is representing connection object. Of course you can use what ever approach but for me this is much more flexible because I can easily navigate in both directions in the relationship and even having custom logical methods in the connecting class - BookAuthor in this case.

Let me write few words about this domain objects model. As you can see the central place in the model plays the Book class. It is not surprise because sbr is more or less about books. For each book we want to have different details except reviews and summaries. Those details are Author and Publisher.

The relationship between Book and Author is many-to-many. This means that each book can have more than one author and each author can write more than one book. Thus domain object BookAuthor is created.

The relationship between Book and Publisher is many-to-one. This means that each book can have only one publisher. Or from the other point of the relationship, each publisher can publish many books.

Next interesting part of the diagram is BookReview and BookSummary and User. The logic here is that book review and book summary must be provided for an existing book by an existing user. There is no limit on the domain level how many reviews/summaries user can provide for the same book. This limit is set as a business logic. Registered user can post one review/summary per book while moderator can post many reviews per book and one summary per book.

Knowing all these we are ready to start with implementation. If you do it in hurry you can start with the book class. But as we already know that we will need possibility to register and we will need User class it is good moment to have a look into grails plugins.

Before you start implementing anything in the Grails it is good idea to see what is available from the Grails plugins. Very often functionality you need is already implemented as a plugin and you can simply reuse it. The same story is for registration and the User class. For software books reviews site I am using Spring security plugin (former Acegi security plugin). So you need to install this plugin. How to do that you can find in the plugins section of the Grails web site. After installing it create two roles: admin and user. This plugin offers out of the box login, logout, register pages and lot of useful methods that can be used in the application.

So in my next post I will install Spring (Acegi) security plugin, initialize default roles on the startup (if they are not initialized already) and then we will include register/login links on the home page and implement the first two user stories: As visitor I want to register and As registered user I want to login. So stay tuned.

P.S. Don't forget to write some review or post summary on the software books reviews.

Tuesday, May 5, 2009

Integrating blueprint into Grails application

[From the series - creating software books reviews grails web application]

In the previous post we have created home and admin page. Now it is time to create layout of the application. If you visit software books reviews site you can see that layout of the page is header and footer and three columns. If you are not a CSS expert creating such layout can be probably complex so it is good idea to use help of some CSS framework. My CSS framework is blueprint.

Blueprint is the grid based framework with the fixed width. Screen is divided into 24 columns and you can specify "boxes" and number of columns they should span through. The most important thing to remember is that sum of the box widths may not be bigger than 24. It can be smaller but not bigger.

The short example of the web page with the blueprint can look like this:

<div class="container">
<div id="one" class="span-24 last">
<!-- some content -->
</div>
<hr/>
<div id="two" class="span-4 colborder">
<!-- some content -->
</div>
<div id="three" class="span-14 colborder">
<!-- some content -->
</div>
<div class="span-4 last">
</div>
</div>

In this short code example the most important features of the blueprint framework are already visible.

The first div with class container is mandatory and blueprint will work inside this div.

<div id="one" class="span-24 last"> defines box that should spread through all 24 columns. This means that content will take the whole row of the screen. "last" class is used to specified that it is last box in the given row. This class has more sense when the sum of box widths is less than 24 but you want to put next box into the new row.

<hr> is blueprint tag that just makes more space between two rows.

Next three <divs> are actually more interesting. Here you are defining that row should be divided into three columns. First column of the width 4, next column of the width 14, and last column of the width 4. What you can notice immediately is that sum of these numbers is 22.

The reason is that class colborder separates two columns and actually takes the space of the whole column.

Now when we have basic knowledge about blueprint it is time to integrate it into our sbr application. The first step is to download the blueprint framework from their site. When you extract the downloaded zip file, copy the three css files from the blueprint folder. The file to copy are: ie.css, screen.css, and print.css.

You should copy them into web-app/css folder of the sbr application.

Now it is time to define layout of our application. As already mentioned we want that all pages are same and have header/footer and three columns: left, middle and right column. If you have read Starting with front-end in Grails application post then it should be clear that the right place where to specify this is the main.gsp template. This template specifies how all pages that are based on this template will look like. First of all we need to reference css files we have copied to the css folder. To do this change to grails-app/views/layouts/main.gsp to look like this:

<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'main.css')}" />
<g:layoutHead />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'screen.css')}" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'print.css')}" type="text/css" media="print" />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'ie.css')}" type="text/css" media="screen, projection" />
<g:javascript library="application" />
</head>
<body>
<g:layoutBody />
</body>
</html>

The three lines to notice are:

<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'screen.css')}" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'print.css')}" type="text/css" media="print" />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'ie.css')}" type="text/css" media="screen, projection" />

They are added as specified by the blueprint framework. The only difference is that I have used createLinkTo grails construct.

Now when we are referencing necessary css files we can specify layout of the template.

<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'main.css')}" />
<g:layoutHead />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'screen.css')}" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'print.css')}" type="text/css" media="print" />
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'ie.css')}" type="text/css" media="screen, projection" />
<g:javascript library="application" />
</head>
<body>
<div class="container">
<div id="header" class="span-24 last">
header
</div>
<hr/>
<div id="left-sidebar" class="span-4 colborder">
left sidebar
</div>
<div id="content" class="span-14 colborder">
<g:layoutBody />
</div>
<div id="right-sidebar" class="span-4 last">
right sidebar
</div>
<hr/>
<div id="footer" class="span-24 last">
footer
</div>
</div>
</body>
</html>

As you can see that is quiet easy and understandable. And what is good it is all what we need to the to get required layout. If you start the application now you will see that home page of the sbr application has correct layout. Of course we still need to populate all parts with the real content but that will be part of the next posts.

I know that usually I am announcing what will be topic of the next post but this time I am not sure. But for sure good reading is introduction into grails templates and tag libs mechanism that I have described in this and this post.

P.S. Don't forget to write some review or post summary on the software books reviews.

Tuesday, April 28, 2009

Creating home and admin page

[From the series - creating software books reviews grails web application]

In the previous post I have explained some basic aspects of grails front-end. Having this knowledge it is a time to create home page of sbr application. For the list of steps how I got up to this point you may want to have a look at this post pointing to all posts related to sbr series.

If you start sbr application (grails run-app) default home page generated by grails is displayed. This is not very useful page as a home page but will be very useful as admin page. It can be very useful as a admin page because it displays all controllers in your application. For each controller you can generate default list/show/create/edit pages.

So let create home page. To create home page I usually create HomeController. So the first step is to generate home controller. To create home controller type the following command:

grails create-controller Home

This command will generate HomeController.groovy file in the grails-app/controllers folder and home folder in the grails-app/views folder. In this folder we should put our new home page.

So to create home page in the home folder create file home.gsp that should look like this one:

<html>
<head>
<title>SBR</title>
<meta name="layout" content="main" />
</head>
<body>
Welcome to the SBR
</body>
</html>

We want to display this page when ever the HomeController is accessed. This is very easy to achieve. Update the code of the HomeController to look like this:

class HomeController {
def index = {
render (view:'home')
}
}

index closure is default closure of the controller and is executed when controller is accessed without specifying action to be executed. So if you type in your browser http://localhost:8080/sbr/home, index action will be executed. And this action is telling that the view 'home' should be displayed. As you are in the HomeController it will look for the file home.gsp in the grails-app/views/home folder. But if you want in the render closure you can specify the full path to the page to be displayed relative to the views folder. So render (view:'home/home') would be valid too.

Now it is time to create admin page. For admin page we will need AdminController. To create AdminController execute following command:

grails create-controller admin

Same as for the HomeController this command will create file AdminController.groovy and folder admin. To create admin page in the admin folder create admin.gsp file. Copy the content of the web-app/index.gsp file into the admin.gsp file. At the end admin.gsp should look like this:

<html>
<head>
<title>SBR admin</title>
<meta name="layout" content="main" />
</head>
<body>
<div class="dialog" style="margin-left:20px;width:60%;">
<ul>
<g:each var="c" in="${grailsApplication.controllerClasses}">
<li class="controller"><g:link controller="${c.logicalPropertyName}">${c.fullName}</g:link></li>
</g:each>
</ul>
</div>
</body>
</html>

We still need ability to display admin page. To process is the same as for the HomeController. Change the AdminController so it looks like this:

class AdminController {
def index = {
render (view:'admin')
}
}

But still, when you start application and access the link http://localhost:8080/sbr you are getting old index page. To change this change the web-app/index.gsp file to this:

<html>
<body>
<%response.sendRedirect(request.getContextPath()+"/home/");%>
</body>
</html>

This will redirect you to the HomeController and home page will be displayed after accessing sbr application.

We are almost done. But what is still remaining is to update template that we use for our pages. So go the the grails-app/views/layouts/main.gsp file and change it to look like this:

<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'main.css')}" />
<g:layoutHead />
<g:javascript library="application" />
</head>
<body>
<g:layoutBody />
</body>
</html>

What I did are just simple changes to this file. Actually I have only removed some code from file generated by default.

As it turned out that this post is longer than I have expected let me summarize steps I have done. So after your grails application is generated you are ready to create home and future admin page. I am usually doing these steps:

  • Create HomeController and home.gps page
  • Create AdminController and admin.gsp page
  • Change index.gsp file so it redirects to the HomeController
  • Make main.gsp layout file simple.

After those steps basic skeleton of the grails application is prepared.

What remains is to prepare layout of the home.page and this can be achieved by changing main.gsp file. If you remember from the previous post, main.gsp is actually template that we can reuse for all the pages in the grails application. Actually we already did it for the home and admin page.

In the next post I will describe layouting of the main.gsp file or to be more precise I will integrate blueprint css framework into sbr application.

P.S. Don't forget to write some review or post summary on the software books reviews.

Tuesday, April 21, 2009

Starting with front-end in grails application

[From the series - creating software books reviews grails web application]

In the previous post I have explained how to create grails application and some general aspects of the grails application. If you are expert for the web front-end you can probably jump into domain logic but if you are like me, front-end is probably harder part of the web application development. As it is generally advised to start with the more complex parts of the application I am usually setting up at least general aspects of the user interface. So let us see how is solved front-end of the grails application.

View technology of the grails application is groovy server pages or shorter gsp while sitemesh is used as main templating mechanism. To gain knowledge of the existing gsp tags visit grails documentation. There is description and short example for each tag. If you don't know site mesh don't worry because I don't know it either. The main usage is very easy and does not require knowledge of the sitemesh.

First interesting file to notice is main.gsp that is located in the grails-app/views/layouts. This file is template for other pages of the application. Just to notice, you can have any number of "main.gsp" files in your grails application. One for each different situation you need. E.g. one for pages with three columns, one for pages with two columns and so on.

The most important part of the main.gsp file is:

<g:layoutBody />

When some page as template uses main.gsp, the whole content of the main.gsp page will be displayed and the <g:layoutBody /> will be replaced with the body element of the mentioned page. To specify which template should be used for the gsp page, put following construct in the <head> element of the page.

<meta name="layout" content="NAME_OF_TEMPLATE_FILE" />

and replace the NAME_OF_TEMPLATE_FILE with the name of template without gsp extension.

So if you have page like this one:

<html>
<head>
<meta name="layout" content="main" />
</head>
<body>
<p>Hello World</p>
</body>
</html>

the main.gsp will be displayed an the element <g:layoutBody /> will be replaced with <p>Hello World</p>. I am not sure that this is 100% correct but this is generally how it behaves.

If this is still confusing let try to make some simple example. Assume that we have two template files: main1.gsp and main2.gsp that are of course placed in the grails-app/views/layouts directory.

// main1.gsp
<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<g:layoutHead />
</head>
<body>
<h1>Hello World</h1>
<g:layoutBody />
</body>
</html>



//main2.gsp
<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<g:layoutHead />
</head>
<body>
<g:layoutBody />
<h1>Hello World</h1>
</body>
</html>

And if we create following two gsp pages

// test1.gsp that uses main1.gsp as a template
<html>
<head>
<meta name="layout" content="main1" />
</head>
<body>
<p>Page 1</p>
</body>
</html>



// test2.gsp that uses main2.gsp as a template
<html>
<head>
<meta name="layout" content="main2" />
</head>
<body>
<p>Page 2</p>
</body>
</html>

test1.gsp will be displayed as:

Hello World
Page 1

while test2.gsp will be displayed as:

Page 2
Hello World

This way you have very powerful tool to create set of pages that look the same and you are just changing the business content of the page. The "same" part should be located in the template file while the "business content" should be located in the page. If for some set of pages you need different layout just create new common template for them. All this magic is possible because grails in the background uses sitemesh for this.

Now when there is basic understanding how front-end works in the grails application we are ready to create our home page. And this will be topic of my next post. I will create dummy home page, admin page from the index.gsp and redirect application to the home page.

P.S. Don't forget to write some review or post summary on the software books reviews.

Friday, April 17, 2009

General Aspects of the Grails Application

[From the series - creating software books reviews grails web application]

In the previous post I have created empty "sbr" grails application. Before changing it to the real grails application it would be good to cover some basic aspects and communication flows of the more or less each grails application. This way it will be more clear what is happening. On the picture below I tried to write main aspects and communication flows of the grails application at least as I see them. I don't claim it is correct. If you need completely correct picture and definitions please refer to the Grails documentation.

general_aspects_of_grails_application

Lets start from the top of the picture.

Probably as a first thing you want to display something to the end-user.

GSP stands for groovy server pages and is the view technology used in the grails. This means that front-end of the grails application is written in the GSP. To make GSP pages more readable and more scalable you can use TagLibs and Templates. As I like to write easily readable code, taglibs and templates are features of the grails that enables you to write readable GSP pages.

As the input into the GSP page you send a model. Just not to be confused, model is actually map of [key,value] pairs where key is the string and the value can be instance of any groovy or java class available on the classpath. Important part to remember is that value can be instance of any class - not only domain objects. I am making this clear because for the "long" time I was limiting data in the model to the instances of domain objects.

So when you are displaying GSP page, you are using gsp tags, custom taglibs, and templates. Data to be displayed on the page is contained in the model. Example of the map representing model can [bookToDisplay:book]. The bookToDisplay is the key (can be any string) while the book is instance of the groovy class. To e.g. display title of the book in the GSP page you would write ${bookToDisplay.title}.

Now when information is displayed there is big chance we want to send some data back to server and process it.

Controllers are groovy classes stored in the controllers folder. Each closure defined in the controller is considered as action and can be called from the GSP pages. So for example if you click the button on the GSP pages that is wired to some action in the controller, action in that controller will be called. Important thing to remember is that controllers are stateless. Controllers have access to the domain objects and to the services. This means, no business logic should be contained in the controller. Controller should use business logic available in the domain objects and services.

Data sent from the GSP page to the controller is available to the controller via params. params is actually variable containing all the request parameters. Thanks to the groovy it is injected into each controller so you have easy access to all request parameters.

So for example, if you have input field with the name bookTitle, content of the field is available to the controller via construct params.bookTitle.

Now when we got down from the GSP to the controller and we have all necessary data available via params variable the rest is easy.

From the controller class it is very easy to use domain objects and/or services. And when you are on the level of the domain object or service you are working with normal groovy and/or java.

Services are groovy classes stored within services folder. Services provide transactional context for database operations and can by dynamically injected into controller and domain classes. Business logic that is not directly connected with concrete domain object should be put into service. Additionally you can use service to surround transactional behavior around multiple calls on the domain objects.

Domain Objects represents domain of the problem you are solving. They are stored in the domain folder. They are famous because they represent GORM classes, grails solution for persistence. Domain classes are mapped to the databases and the database is automatically generated or updated for you according to relationships between domain objects.

And of course the whole grails framework is built on the top of the hibernate and spring. This ensures stability and scalability of the grails applications.

Summary

When you click on some button or link in the GSP page you are forwarded to the corresponding action in the controller. After performing basic validation in the controller you can use domain objects and services to perform application logic. After all necessary actions are performed you are creating model that is sent and displayed on the GSP page.

In the next post I will return back to the "sbr" project. I will create home page and explain basic layouting options.

P.S. Don't forget to write some review or post summary on the software books reviews.

Tuesday, April 7, 2009

Eager fetching and searchable plugin in Grails

What came as surprise to me is that eager fetching even when specified on the level of the domain class does not work with the searchable plugin. I hit this problem while working on the software books reviews and statement and description why I found on one blog post. Unfortunately I cannot find the mentioned post again so I am not able to give a credit to the original author by linking to his/her post.

So for example lets have Book domain class that among other properties has publisher property specified like this:

class Book {
static searchable = true
Publisher publisher

static fetchMode = [publisher:"eager"]
}

Using searchable plugin you can search for the books like this:

 Map<String,String> options = new HashMap<String, String>()
if (params.offset) {
options.put('offset',new Long(params.offset))
}
options.put('escape', true)
options.put('max',10)
def searchResult = Book.search(params.searchTerm, options)

After executing given query searchResult.result will be populated with the list of found Book instances. And in this moment you hope that everything is fine. You send the found list of books to the view but to your surprise you see that publisher is not displayed for each of the book. You check if the book has publisher and it is in the database. The reason for the missing publisher is that the domain classes are created differently when loaded from the lucene index file.

To resolve this problem I have actually reloaded all the found books from the database. This way all the books are of course loaded as specified in the domain object. So code for searching looks like this:

Map<String,String> options = new HashMap<String, String>()
if (params.offset) {
options.put('offset',new Long(params.offset))
}
options.put('escape', true)
options.put('max',10)
def searchResult = Book.search(params.searchTerm, options)

// create new results because those current one are actually not loaded eagery
def newResults = new ArrayList()
searchResult.results.each {book ->
def bookToAdd = Book.get(book.id)
newResults.add(bookToAdd)
}

searchResult.results = newResults

So if you have integrated searching into your grails application and expects that some parts of the domain object are loaded eagerly you should probably use approach similar to this one.

P.S. Don't forget to write some review or post summary on the software books reviews.

Monday, April 6, 2009

Creating Grails Application

[From the series - creating software books reviews grails web application]

In this post just for the sake of completeness I will shortly describe how to create grails application. As in the series of the post I will more or less explain some aspects of programming in the Grails and partially recreate software books reviews site the project to create I will call sbr (short for software books reviews).

Note: I am currently using Grails 1.0.3 version.

Creating Grails application is very easy. Open some command line tool and execute the command:

grails create-app sbr

Now the folder named sbr is create and in this folder is new grails application.

Actually you are already able to start this web application by executing following command from the sbr folder:

grails run-app

To access the application in the browser enter: http://localhost:8080/sbr.

In the case you want to start application on another port you can do that using following command:

grails -Dserver.port=[port_number] run-app

And of course instead of the [port_number] you should enter number of the port on which you want to start web application.

When Grails application is started this way without any changes it is run using embedded Jetty web container and in-memory HSQLDB that is default Grails configuration. Later on I will explain how to change database and how to deploy to Tomcat.

Let me shortly explain folders of the grails application. The top level folders are displayed on the following screen shot:


grails_folder

Short explanation of generated folders is:

  • grails-app actually contains the main part of the grails application and will be explained separately
  • lib - contains all external dependencies to other java libraries and is by default empty
  • scripts - contains scripts and is by default empty
  • src - contains java and groovy source files and is by default empty
  • test - contains unit and integration tests and is by default empty
  • web-app - contains web application

The content of the grails-app folder is much more interesting because it contains the heart of your web application.


grails_app_folder

Names of the folders should be self descriptive enough but shortly:

  • conf - contains configuration of the application. From this folder you are able to configure different aspects of the grails application like: datasources, hibernate, spring, bootstrap and so on. In the later post I will explain at least some of those files.
  • controllers - contains controllers of the web application. Controllers are accessed from the views and of course represents C of the MVC pattern
  • domain - is folder that will contain all application domain objects. All application domain objects are persisted while the database schema is automatically generated using hibernate. All domain objects are thanks to Groovy by default enriched with number of useful methods.
  • i18n - is folder used to localized application
  • services - are different services that can be used by controllers or domain objects. They are automatically initialized and inserted using spring. They also provide transactional behavior.
  • taglib - folder that will contain custom tag libraries. Tag libraries are excellent feature of the grails that enables you to modularize front-end of the grails application. I am using them heavily.
  • views - is the folder that contains html and gsp files of the application. In the one word it contains "pages" of the web application.

And although not directly visible in the folder list, another important part for modularizing front-end of the grails application are templates. I will explain how templates can be used in the later posts.

In the next post I will shortly explain general aspects of the grails application, or namely all folders of the grails-app folder. So stay tuned :)

P.S. Don't forget to write some review or post summary on the software books reviews.

Series from the Developing Software Books Reviews

As I have already promised few days ago, I will write a number of posts explaining my experience gained during development of the software books reviews and partially grails tutorials site. Actually during the series of the posts I will more or less recreate software books reviews grails application. Just for the convenience, I will regularly update this post so it points to all posts from this series. So if you will like those posts come and visit this post from time to time.

So the list of the posts so far is:

Friday, April 3, 2009

Developing Web Applications with Grails

As I have recently released software books reviews I believe I have finally improved my skills also when working with pure front end (html, css) of web application. As I also mentioned in the previous post, I plan to write series of posts explaining development work on the 'software books reviews' site. I hope my experience will be useful for additional developers. As I am coming from back-end Java development, while developing my first Grails applications the hardest part for me was HTML, css, layout... I believe posts I will write will also help other back-end developers to write web sites using Grails.

I plan to write at least one post per week (till there is enough to write). I do not plan to cover basics like how to install grails or how to generate applications. There are already lot of articles covering these topics. But I hope posts will be clear enough so even beginners will be able to understand them.

Lets go to the first topic :)

So if you are reading this probably you want to write web applications using Grails. Let us see what topics one needs to cover to write web application:

  • It is necessary to create nice front-end (HTML, css styles, layouts)  (disclaimer: I don't claim that I am making nice front-ends :) )
  • It is necessary to implement business logic - behavior of the application
  • Probably it is necessary to include security into application
  • It is necessary to store data into database
  • And very often it is necessary to provide some additional features that are not directly connected with business logic but in these days are more or less "must have". Obvious feature are RSS feeds.

Grails can help us with most of these requirements while hiding most of the complexity from us. Thanks to grails the most complex things are hidden from us but we still have access to them.

Domain objects - domain objects of course describe domain of our business logic. They are automatically persisted and loaded from the database. This means that database schema generation is something we don't need to think about most of the time.

Services - provide functionality that is not part of the domain objects. In services you include functions that are not naturally fitting into domain objects. Further on services handle transactional behavior for you. You can configure them with simple flag.

Plugins - Grails has excellent system of plugins. As we don't want to reinvent wheel we can reuse what is already implemented for us. Plugins will provide us with security, nice front-end components, RSS generation....

Sitemesh - is decorator engine supported by Grails to support view layouts. I am using it only on the basic level but even in such scenario it is very useful.

So these are some basics that will help us to make developing web application fun and fast.  Using those features we will go through example implementation of the software books reviews.

In the next post I will describe how I start project, and at least what are my basic first steps. I don't claim that it is the correct way but for me it turned out to be good.

Some advertisement: if you are reading software related books please be so kind to post review or link to review on the software books reviews.