Design Pattern « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Design Pattern ’ Category

Setting count bubble in jQuery mobile Accordian Head

Posted by on October 18th, 2012

Sometimes we want to show count bubble in Accordion head that is different from the what jQuery mobile provides by default.

To add count bubble to Accordian head, we use following piece of code:

</pre>
<h2>Heading<span class="ui-li-count">10</span></h2>
<pre>

But it doesn’t give us the desired output and it looks like following:



If we want to set count bubble in Accordian head as per our use case , we have to add following css:


.ui-collapsible-heading .ui-btn-text{ display:block;}
.ui-collapsible-heading .ui-li-count { position: absolute; font-size: 11px; font-weight: bold; padding: .2em .5em; top: 50%; margin-top: -.9em; right: 10px;  border-radius: 1em 1em 1em 1em; background: linear-gradient(#FFFFFF, #F1F1F1) repeat scroll 0 0 #EEEEEE;  border: 1px solid #CCCCCC; color: #222222;font-weight: bold;text-shadow: 0 1px 0 #FFFFFF; }

After making the changes, our Accordian head looks like following:

Count Bubble after fix

Hope it helps.:)
Rajan Shergill
rajan@intelligrape.com
https://twitter.com/RajanShergill3

Redis: Heavyweight Tags – an awesome use-case for caching with Redis

Posted by on September 25th, 2012

Redis plugin provides a beautiful way to cache the html tags. Using this plugin we can make big savings on the time taken to render the gsp tags.

<redis:memoize  key="someKey" expire="3600" >
   //Some heavy weight tags rendering
  // Lots of db / network operations.
</redis:memoize>

I found this tag extremely helpful in rendering the public facing pages of our site. the pages which refreshed not very frequently and required few seconds to render(if done without caching).

The difference in the time taken to render the page is dependent on our choice of right candidate for Memoizing.

(more…)

Posted in Design Pattern, Grails

Groovy Delegation Pattern Using invokeMethod and propertyMissing methods

Posted by on September 24th, 2012

Following DRY is practised religously in my current project. Recently, I identified a case where code repetition had long been ignored. We used to pass either a domain object or a command object in the view model. Due to this, many domain methods had to be duplicated in the command object. This was probablematic because one would easily forget to create/modify a function in the command object if it was created/modified in the domain object. The code was smelling bad. The classes were something like this:

Class College{
//attributes

//somethods
}

Class CollegeCO{
College college

 //other attributes and constraints

 // repetitive College methods

}

Groovy intercepts all methods and property access via invokeMethod and get/SetProperty property hooks. So all I needed to do was to override invokeMethod() and propertyMissing() functions in the CommandObject like this:

def invokeMethod(String name, args) {
        college.invokeMethod(name, args)
    }

def propertyMissing(String name) {
        college."$name"
    }

So any missing method or property call on command object was automatically delegated to the college object. This is a simple way of utilising the Delegation Patttern using Groovy.

Hope this helps.

Imran Mir
Imran[at]intelligrape.com

Discriminator in Grails inheritance

Posted by on September 3rd, 2012

Whenever I have the use case of inheritance in my Grails application I prefer to have the single table for all the classes, to avoid joins and multiple save statement. But one thing I dont like about this is its class discriminator which have the full class name in it. I dont find it much readable when looking into the sql.

 

Grails provide cool mapping to customise the discriminator in Grails inheritance. To explain this I am taking the example  of  my last blog . So to change the value of discriminator I just need to add the discriminator mapping in every sub class and give them some unique identification value

static mapping = {
        discriminator "TextBlog"
    }

Now the class discriminator will store “TextBlog” rather than full class name e.g; com.intelligrape.example.TextBlog.

After doing this I change the discriminator column name because its not actually storing the class, so I add following mapping to my base class to change column name.

static mapping = {
        discriminator column: "type"
    }

After doing this the column name will change from “class” to “type”.

 

Hope it helps

Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

Posted in Design Pattern, GORM, Grails

Inheritance in Grails

Posted by on September 3rd, 2012

In Grails we can have inheritance with abstract base class as well as persistent base class. Lets take an example to explain this.(All the classes are in the package com.intelligrape.example)

class Blog{
    String authorName
    static constraints = {
         authorName (nullable:false)
    }
}
class TextBlog  extends Blog{
    String textContent
    static constraints = {
         textContent (nullable:false)
    }
}

class PodCast  extends Blog{
    byte[] content
    static constraints = {
          content (nullable:false)
    }
}

By creating such class structure Grails will create a single table and all the three classes will share it. Our table will look like as follow

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| version      | bigint(20)   | NO   |     | NULL    |                |
| author_name  | varchar(255) | NO   |     | NULL    |                |
| class        | varchar(255) | NO   |     | NULL    |                |
| text_content | varchar(255) | YES  |     | NULL    |                |
| content      | tinyblob     | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

We can see that other than the declared fields Grails created three more fields
id : Auto increment field, used as an identifier and managed by Grails itself
version : Used for optimistic locking, increments each time when object is updated
class : Discriminator column used to identify what specific type of blog is associated with given row e.g; com.intelligrape.example.TextBlog

There is a drawback with this approach, as you can see in the table, column text_content and content fields are nullable true although we have defined them as nullable false in domain class. Consequence of storing all kind of blog data in single table is that we can’t have non nullable columns in sub classes but because of single table, joins are not fired and our queries will be faster. Second disadvantage could be the long discriminator, which makes it difficult to read the data of a particular class in sql.

If you dont like having single table for all the data, Grails give you freedom to create multiple tables for each class. You just need to add the following mapping block in base class

static mapping = {
        tablePerHierarchy false
}

Now you can see three different tables for each class. But the major drawback in this approach is whenever you save the instance of sub-class it executes two queries for save like following

Hibernate: insert into blog (version, author_name) values (?, ?)
Hibernate: insert into text_blog (text_content, id) values (?, ?)

Second drawback is again on query performance. Whenever you execute some GORM query for fetching data it executes join query e.g; TextBlog.list() method will have the following join query

Hibernate: select this_.id as id2_0_, this_1_.version as version2_0_, this_1_.author_name as author3_2_0_, this_.text_content as text2_4_0_ from text_blog this_ inner join blog this_1_ on this_.id=this_1_.id

Now its our decision which makes more sense to our application.

Hope it helps
Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

Posted in Design Pattern, GORM, Grails

Using PostConstruct annotation with Grails Services

Posted by on August 27th, 2012

We can use PostConstruct with Grails Services and injected Spring Beans. This PostConstruct annotation can be used to annotate a method which needs to be executed after dependency injection to perform any initialization.

import javax.annotation.PostConstruct

class PostConstructDemoService {

    @PostConstruct
    private void init() {
          println "Initializing"
          //your initialization code goes here. e.g connect to some Messaging Service
     }
}

Check this for more details. We also have PreDestroy annotation.

Regards,
Ankur Tripathi
ankur@intelligrape.com

Posted in Design Pattern, Grails

Setting default layout in Grails application

Posted by on April 5th, 2012

Grails uses Sitemesh for adding layout to the views. Layouts are located in layouts folder and to add layouts to the view we generally add any of the following line in head

<g:applyLayout name="layoutName"/>
or
<meta name="layout" content="layoutName" />

But most of the time we have single layout, so why we repeat the same line for adding layout in our gsps. Grails has the solution for this as well.
Grails comes with a config property grails.sitemesh.default.layout which will set the layout of the page if there is no layout tag added to the gsp. We just need to write the following lind in Config.groovy and its all done

grails.sitemesh.default.layout = 'layoutName'

But the bad part is it doesn’t work with the scaffolded code even if I update the template of my view and remove the meta tag of layout. It would be nice if grails comes with this config property and I just need to update the layout property to change the layout.

Hope it helps
Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

Posted in Design Pattern, Grails

Grails 2.0 action arguments data binding

Posted by on February 20th, 2012

One feature that I really like in Grails 2.0 is action arguments databinding. While reading more about it I also found a nice grails.web.RequestParameter annotation. When you know something you always find its use case. In my recent project I need to take radius and height as params for creating a cylinder so my action looks like

def save(float radius, float cylinder){
....
}

but now I have changed my action as

def save(@RequestParameter('r')float radius, @RequestParameter('h')float height){
....
}

Now radius will initialize with params.r and height will initialize with params.h. It made my urls short and my code more readable.
I believe that the real benefit of this annotation would be in a scenario where an external API returns some result whose fields are not that intuitive.
However I have a wish here, that if we could use this annotation on command object fields as well then it will be more useful.


Hope it helps
Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

Posted in Design Pattern, Grails

Groovy annotations for ToString and EqualsAndHashCode

Posted by on January 29th, 2012

As I am a lazy programmer most of the time I dont implement toString and equals methods on my grails domain classes. I would like to say thanks to Groovy for helping me out and giving me a ready made recipe for this. Now I just need to annotate my class with ToString and EqualAndHashCode annotation it adds appropriate implementation of these methods for me. Now My domain class looks something like this.

@ToString(includeNames = true, includeFields = true, excludes = 'dateCreated,lastUpdated,metaClass')
@EqualsAndHashCode
class Item {
    String name
    Float price
    boolean active = true
    Date dateCreated
    Date lastUpdated
}

Before adding this annotation my domain class toString looks like this

Item item = new Item(name: "Chips", active: false, price: 15)
println "To String output -: " + item //To String output -: com.intelligrape.myapp.Item : null

Now I get the following output for Item object toString

Item item = new Item(name: "Chips", active: false, price: 15)
println "To String output -: " + item //To String output -: com.intelligrape.myapp.Item(name:Chips, price:15.0, active:false)

To get this annotation on all my domain classed I updated the template of grails domain classes so that whenever I do create-domain-class it give me the annotated domain classes

@artifact.package@
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@ToString(includeNames = true, includeFields = true, excludes = 'dateCreated,lastUpdated,metaClass')
@EqualsAndHashCode
class @artifact.name@ {

    Date dateCreated
    Date lastUpdated
}


Hope it helps
Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

Discovering grails goodness: Scoped Services

Posted by on December 29th, 2011

Recently, I got to learn about the scoped services in grails and I found it worth sharing. For instance: A Service marked as ‘session’ scoped would be instantiated once for a session and remains there throughout the lifetime of the session. This can be used to store user specific data in this service bean class.

class SessionDataService {
     static scope = 'session'
     Date lastLogin =new Date()
    String getInfo()
    {
        "lastLogin: ${lastLogin.format('HH:mm:ss')}"
    }
}

So, wherever I intend to use session for storing user data, I would rather use session scoped service.

Hope that helps.

Best Regards
Mohd Farid

Posted in Design Pattern, Grails