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.

Tuesday, March 24, 2009

Have you recently read a software related book?

As number of other software developers I like to read books about software development too. Books I like to read are about general aspects of programming and about agile software development. As my latest free time burner is grails framework I put together these two passions and created web site Software Book Reviews of course using grails.
The web site is devoted to software related books. You can provide review directly on the site or link to an existing review on the Internet. Further on you can also provide summary of the book by providing answers to three short and easy questions.

As I like this web site and used little bit different approach than used for Grails Tutorials I plan that some post about about my adventures developing software books reviews will come soon.

In the meantime, if you have recently read some software related book maybe you can be so kind to post review on the site.

Sunday, January 25, 2009

Favorites Section on Grails Tutorials

After a long time I have added new feature to the grails tutorials.
The new section is favorites.
Now when you find interesting article on the grails tutorials you can add this article into your favorites. Later on you can access favorites and browse articles. Further on you can browse favorites of other users. Favorites of each user are also exposed as RSS feed so if you like somebody's collection of favorites you can follow it via RSS feed.

"Unfortunately" implementation of this feature was more or less straightforward so there is nothing I could really blog about.
More or less if you created your code with enough templates and custom tags, implementing new feature in most cases is actually adding one or more domain classes, reusing existing services and templates and using dynamic gorm methods.
Well and this is the part I really like about grails. Adding new features usually is more or less matter of hours (not days).

Tuesday, January 13, 2009

Don't forget to ask "why"

Recently I was browsing through stackoverflow searching for interesting questions and answers.

Question that raised my interest was:
"What you don't like in agile development?"

And the answer with the most votes started with: "I don't like seeing people focus on "what" and missing "why"."

You can have a look at the full thread here.

And actually asking "why" is one of the main attributes of the agile software development. But as hype was created around agile methodologies everybody are happy with the fast delivery and smaller number of bugs. And some agile teams had adapted to this style. They are developing everything that is thrown on them for the given iteration. Sometimes request does not give sense but it is implemented anyway.

But we should not forget that idea of the agile methodology is to help customer build better software. And we can build better software only if we ask customer "why?".

So next time when you meet strange requirement ask the customer "why?". And keep asking "why" as long as you don't get to the core of the problem. And don't expect that you will get easy to the core of the problem. But when you are at the core of the problem there is big probability that you will be able to propose better solution and thus help customer to build better software.

Don't forget that software development should be fun.

Tuesday, December 2, 2008

Grails Integration Testing - Some Tips and Tricks

As stated in the Grails documentation "Integration tests differ from unit tests in that you have full access to the Grails environment within the test". This actually means that you have access to database, you can inject necessary services into the test class.

All integration tests have to extend GroovyTestCase class.

Database

By default, integration tests use in memory HSQLDB. You can change this by updating DataSource.groovy.

Next important feature to remember is that integration tests run within transaction that is rollbacked after the test. So if you want to have data within database after the testing, in the test specify boolean transactional = false.

Services

To use default injection of specified service classes within test all that is necessary is to specify service as a field in the test class. For the rest magic of the Grails will take care. E.g. example would be FeedService feedService

Domain Classes

Within integration test you can use domain classes same as you would in the regular code. The main difference is that in the most cases methods on the domain classes should be called with the flush:true parameter.

Knowing all these it seems that integration testing with grails is really easy. And it is the case but there are some additional features to take care (some of them are valid also for the production code).

Some Tips

Tip: Saving domain object can fail without any error

Yes this can happen and happens often when you forget about some validation rule. And when you are not aware that your object was not saved your test results cannot be correct.

So for example following code snippet will not save the object but also no exception will be thrown:

FeedSource feed = new FeedSource(feedLink:"http://abc.com", title:"abc")
feed.save(flush:true)
Article article = new Article(title:"afaf", articleLink:"http://abc.com", source:feed)
article = article.save(flush:true)

Reason is that there is 'description' field that is mandatory for the article. To ensure that you don't get such surprises I use following code:

private Object save(Object object) {
validateAndPrintErrors(object)
Object result = object.save(flush:true)
assertNotNull("Object not created: " + object, result)
return result
}

private void validateAndPrintErrors(Object object) {
if (!object.validate()) {
object.errors.allErrors.each {error ->
println error
}
fail("failed to save object ${object}")
}
}

To check that there are no errors in the domain object you need to call method validate(). If there are validation errors you can get them through errors property of the domain object.

Next thing to notice is that method save() of the domain object returns instance of created object if it is correctly saved. So you can check if returned object is different than null.

Code for saving and validating can also be implemented as extension to domain classes using some nice groovy magic. Further on, this methods also works only thanks to groovy magic.

So initial code snippet should be changed to following.

FeedSource feed = new FeedSource(feedLink:"http://abc.com", title:"abc")
feed = save(feed)

Article article = new Article(title:"afaf", articleLink:"http://abc.com", source:feed, description:"asbfasfd")
article = save(article)

In this case there will be no surprise that domain object was not created within database without any exception thrown.

Tip: In some cases you need to reload domain object from database

As base for the GORM magic is hibernate, and we know that hibernate uses cache, there are cases when you need to reload object from database to ensure that it is in correct state. So for example if the rule is that when feed is deleted source of the article should be set to null, following code may fail.

feedService.deleteFeed(feed)
// we are sure that this article exists
article = Article.findByTitle("afaf")
assertNull("Article source should be null but is ${article.source}", article.source)

Reason is that deleting feed will not update source field of the article in the hibernate cache and the last line will fail. To ensure that you really have latest object from the database you should call refresh method on the article.

feedService.deleteFeed(feed)
// we are sure that this article exists
article = Article.findByTitle("afaf")

article.refresh()

assertNull("Article source should be null but is ${article.source}", article.source)