Intelligrape Groovy & Grails Blogs

Grails 2.0 action arguments data binding

Posted by Uday Pratap Singh 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
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted under Design Pattern, Grails

Using aliases in aggregate functions of criteria queries

Posted by puneet on February 13th, 2012

When using criteria queries, many times we encounter a use case where we need to order our result not on any field of domain class but on our result set, in these cases aliases can be used.


In my project, use case was to find most liked products from the domain:

ProductStat{
Date dateCreated
Product product
}

To find the result, the query I used was :

ProductStat.createCriteria().list() {
            projections {
                groupProperty("product")
                count("product", "totalProducts")  // alias totalProducts
            }
            order("totalProducts", "desc")
}

In this way using alias “totalProducts” I was able to order the result according to the count of products.


  • Share/Bookmark
Posted under Grails

Alphanumeric Sorting using Criteria Query (with MySQL database)

Posted by Gaurav Sharma on February 2nd, 2012

I am working on a Grails application with MySQL database. I had a use case in which I had to implement alphanumeric sorting using Criteria Query on Grails. By alphanumeric sorting I mean if there is a class Employee with field empId then on doing :

Employee e1 = new Employee(empId:'emp10').save()
Employee e2 = new Employee(empId:'emp2').save()
Employee e3 = new Employee(empId:'emp1').save()
Employee e4 = new Employee(empId:'1emp').save()
Employee e5 = new Employee(empId:'10emp').save()
Employee e6 = new Employee(empId:'2emp').save()

Employee.createCriteria().list([sort:'empId'])
            /* OR */
Employee.createCriteria().list{
    order('empId')
}

should give result like [e4,e6,e5,e3,e2,e1]. But according to sql sorting the result would be [e5,e4,e6,e3,e1,e2]

One thing to note was that criteria query implemented sorting at the database end.
After googling around, I came across a script that had a SQL function which converted the field value to string that can alphanumerically sorted easily at database end.

To migrate the functions in script to database you have to unzip the script and write following command on terminal:

mysql -u username -p database_name < /path/to/unzipped/directory/natsort.install.mysql

Now only thing I had to do was to get a derived field from the Grails property that had to be sorted alphanumerically which was easily possible as the Grails had ability to create transient field using formula (thanks to wonderful Blog by Uday). Thus I had to create a new transient field using SQL function in formula. So I did something like this :

class Employee {
    String empId
    String empIdSortField           //transient field
    static mapping = {
        empIdSortField formula: 'natsort_canon(empId, "natural")'
    }
}

Now if I had to get Employee objects are sorted by empId alphanumerically, what I would do is :

Employee.createCriteria().list {
    order('empIdSortField')
}

Hope this was helpful to you!

  • Share/Bookmark
Posted under Database, GORM, Grails

Groovy annotations for ToString and EqualsAndHashCode

Posted by Uday Pratap Singh 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
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap

  • Share/Bookmark
Posted under Design Pattern, Grails, Groovy

Extending Audit Logging Plugin to track changes to Persistent Collections

Posted by Ankur Tripathi on January 23rd, 2012

In one of our project we needed to maintain history of domain objects when they are updated. We saw Grails Audit Logging Plugin as a good candidate. But later, found that it doesn’t take care of persistent collections. So with help of my colleague Vivek and this Stack Overflow thread, we extended this plugin without making it inline, to handle this limitation.

Audit Logging plugin provides a bean named auditLogListener to handle Hibernate events and provide handlers in Grails Domain classes with old values map and new values map. So what we have to do is create a class named CustomAuditLogListener which extends AuditLogListener from the plugin and overrides the onPostUpdate() method. Implemetation for this class is:

import org.codehaus.groovy.grails.plugins.orm.auditable.AuditLogListener
import org.hibernate.collection.PersistentCollection
import org.hibernate.engine.CollectionEntry
import org.hibernate.engine.PersistenceContext
import org.hibernate.event.PostUpdateEvent

class CustomAuditLogListener extends AuditLogListener {

    @Override
    void onPostUpdate(final PostUpdateEvent event) {
        if (isAuditableEntity(event)) {
            log.trace "${event.getClass()} onChange handler has been called"
            onChange(event)
        }
    }

    private void onChange(final PostUpdateEvent event) {
        def entity = event.getEntity()
        String entityName = entity.getClass().getName()
        def entityId = event.getId()

        // object arrays representing the old and new state
        def oldState = event.getOldState()
        def newState = event.getState()

        List<String> propertyNames = event.getPersister().getPropertyNames()
        Map oldMap = [:]
        Map newMap = [:]

        if (propertyNames) {
            for (int index = 0; index < newState.length; index++) {
                if (propertyNames[index]) {
                    if (oldState) {
                        populateOldStateMap(oldState, oldMap, propertyNames[index], index)
                    }
                    if (newState) {
                        newMap[propertyNames[index]] = newState[index]
                    }
                }
            }
        }

        if (!significantChange(entity, oldMap, newMap)) {
            return
        }

        // allow user's to over-ride whether you do auditing for them.
        if (!callHandlersOnly(event.getEntity())) {
            logChanges(newMap, oldMap, event, entityId, 'UPDATE', entityName)
        }
         executeHandler(event, 'onChange', oldMap, newMap)
        return
    }

    private populateOldStateMap(def oldState, Map oldMap, String keyName, index) {
        def oldPropertyState = oldState[index]
        if (oldPropertyState instanceof PersistentCollection) {
            PersistentCollection pc = (PersistentCollection) oldPropertyState;
            PersistenceContext context = sessionFactory.getCurrentSession().getPersistenceContext();
            CollectionEntry entry = context.getCollectionEntry(pc);
            Object snapshot = entry.getSnapshot();
            if (pc instanceof List) {
                oldMap[keyName] = Collections.unmodifiableList((List) snapshot);
            }
            else if (pc instanceof Map) {
                oldMap[keyName] = Collections.unmodifiableMap((Map) snapshot);
            }
            else if (pc instanceof Set) {
                //Set snapshot is actually stored as a Map
                Map snapshotMap = (Map) snapshot;
                oldMap[keyName] = Collections.unmodifiableSet(new HashSet(snapshotMap.values()));
            }
            else {
                oldMap[keyName] = pc;
            }
        } else {
            oldMap[keyName] = oldPropertyState
        }
    }
}

Now we need to register CustomAuditLogListener class as implementation for auditLogListener which will be done in resources.groovy. The bean has to be defined in resources.groovy as:

 auditLogListener(CustomAuditLogListener) {
        sessionFactory   = ref('sessionFactory')
        verbose          = application.config?.auditLog?.verbose?:false
        transactional    = application.config?.auditLog?.transactional?:false
        sessionAttribute = application.config?.auditLog?.sessionAttribute?:""
        actorKey         = application.config?.auditLog?.actorKey?:""
    }

Now we will be able to fetch older values for persistent collections in onChange handler as documented in plugin documentation.

Hope you find this helpful.

Ankur Tripathi
ankur@intelligrape.com

  • Share/Bookmark
Posted under Grails, Plugin

Using Git Rebase

Posted by Sachin on January 22nd, 2012

Working on a cool project, doing cool and unusual stuff has its own charms and challenges. For doing cool things, you need cool tools to play with and Git surely is one of the coolest ones around. One of the many powerful features of git is rebase.

While working on a large project, you almost always develop your feature on a new branch, and for a large enough feature/requirement, It could take up to month or more to deliver it.

Lets consider a scenario where you need to begin on a new feature and you create a separate branch,(coolNewStuff) , off your main integration branch, (master).

New Branch from master

While you were working on the stuff, other guys in your team were pushing and integrating their stuff into the master branch. As a result master branch moved ahead and there were loads of commits and other stuff added to it.

Now before pushing your cool stuff into master, you would need to pull in the changes in the master to your current(coolNewStuff) branch. You could easily do that using

git pull origin master

Resolve conflicts. commit changes and merge this branch with master.

Nothing wrong with that actually, except that it creates a lot of intermingled commits in the branch, and it won’t give a clear roll back point.

What you actually want to do is put your work on top of the existing master branch as a separate commit so that you get a clear roll back point in case something goes wrong.

You want your changes of coolNewStuff branch on top of current master head, you don’t want master on top your coolNewStuffBranch.


Enter Rebase.

What rebase allows you to do is rewrite the history of your branch. You can actually pull in the changes from master branch place them above the master branch, you branched out off  (some 30-45 days back) and then place all the stuff you developed (all commits you made since the day you branched off) on top of this new pulled in changes from master. So, this looks like…

All you need to do is on the coolNewStuff branch call

git rebase master

This will start your rebasing process. It will basically collect the changes you made since you branched out of master to another temporary location, merge the old coolNewStuff (which was same as the master at the time you branched off) with the new changes on the master and then places your changes on top of it.

This process rewrites the history of the branch.

If you get conflicts. resolve the conflicts and add the files back

git add fileName

Continue with rebase

git rebase --continue

Do a git log and see that your changes are on top of the latest changes of master branch.

Now You won’t be able to push the changes to coolNewStuff branch as the history of branch has been rewritten.

On doing git status you would get a message saying

Your branch and ‘origin/coolNewStuff’ have diverged

You will need to remove your remote branch

git push origin :coolNewStuff

and push again. Do remember to notify other guys who are working on the coolNewStuff branch to delete their local coolNewStuff branch and fetch the new coolNewStuff branch.

Now when you merge this branch with master you will see that your changes are on top of the recent stuff on master and you can easily roll back the stuff in case something goes wrong.

Hope this helps.

Sachin Anand

email : sachin[at]intelligrape[dot]com

twitter : @sachin__anand

  • Share/Bookmark
Posted under git

My Top 9 Features from Grails 2.0

Posted by Vivek Krishna on January 18th, 2012

The groovy world is abuzz about the latest release from the Grails Stable, Grails 2.0, which packs a lot more punch than its predecessors, which by themselves were productivity enhancers and wonderful to develop our web applications with. The new version brings with itself a lot of changes compared to the previous releases and deserves to be truly called 2.0 instead of 1.4 or 1.5.

I would like to walk you through some of the coolest features from grails 2.0 that I have discovered in the limited time I have spent with the new version and fell in love with.

  1. The Improved Interactive Mode: I love working on the command line and the new interactive mode is a joy to work with. The auto-completions, combined with the quick response times(as a result of not having to load JVM for each command) is a sure shot productivity booster. That I can run normal commands from the grails shell by just prefixing them with a “!” is an added advantage.
  2. Dynamic Domain Class Reloading: One activity that consumed a lot of time with earlier versions of Grails was waiting for the servlet container to restart, once we made even a line’s change in the domain class or src/groovy file. Now, the reloading is dynamic which means that the changes take effect very quickly, this letting us focus on the development without the flow being interrupted by the restart process.
  3. HTML5 scaffolded screens: One of the complaints I had with earlier versions of grails was the not-so-good looking screens that were generated by scaffolding. For most of the admin screens, the scaffolded screens are sufficient and the new HTML5 compatible scaffolded screens are very easy on the eye and provide an excellent user experience. With the new screens however, I can simply change the logo and they make for sufficiently pleasing CRUD screens.
  4. Business Class Citizenship for Testing: Testing has been a first class citizen of the framework right from day 1, but the new testing framework has made life easy for people like me, for whom testing doesn’t come naturally. With scaffolded tests being generated, newbies will find it easier to learn aspects of testing the application. In addition to that, the capability to unit-test criteria queries adds an element which was missing from earlier versions.
  5. Link Generation/Page Renderer APIs: Earlier, generating html from gsp files from non-request bound threads was a pain, especially with mocking the web request. Now, with the PageRenderer API, generating a view in a job or a service is as simple as injecting a groovyPageRenderer bean and calling groovyPageRenderer.render() method just like from within a controller.
  6. GORM Finders with Groovy Collection find/findAll like syntax: If there was one feature I could keep from all the enhancements in 2.0, it would be this. This is also the feature which, I think would go a long way in making GORM queries easier. There couldn’t be a more expressive syntax!
  7. Public methods in controllers as actions which can take arguments: Earlier, it used to be a pain to type-cast the parameters into their respective types(when one felt that command objects are an overhead while working with at most 2-3 params). The new method like syntax lets us define actions as public methods in controllers, which automatically bind data to the method arguments, based on the params. If I have a command object as argument, it works just the way it worked earlier. We talk about thin controllers a lot. This also means that we’ll be more diligent while creating methods in controllers and even if we really must, they have to be private. This just made the controllers thinner!
  8. The New Improved Test Reports: The new test reports are very easy on the eye and even more easier while finding test failures. Though we don’t recommend having println statements in our test cases, the fact that I can see the system outputs on the same page as my test case is a winner.
  9. DB Console: Viewing the contents of the in-memory DB was a pain in the earlier versions. The new dbconsole, which can be accessed only in development mode is a clear winner.

Grails 2.0 comes with its set of wonderful features which makes development with it, a much better experience.

  • Share/Bookmark
Posted under Grails

Custom ‘Share’ button on Facebook wall post

Posted by Vishal Sahu on January 16th, 2012

Hi,
In one of my Grails project, i needed to have Share feature on the messages/post published by our application on facebook wall.
In Facebook, if the message/text published is simple text, then Share link appears on it, but if it contains any link/URL attached to it, then Facebook do not provides Share button on it.


To implement it, i created my own Share button and thought it worth sharing.


Publishing to facebook wall post requires facebook access_token and we have to do a post call to publish it on facebook wall.
I am assuming that you already have the access_token, if not you can find how to get access_token from here


Basic URL to share somthing on facebook wall is as below


    private static final String SHARE_BUTTON_BASIC_URL = "http://www.facebook.com/sharer.php?u="
    private static final String BUTTON_NAME = "Share This" // name to appear on the Share button

To create our own ‘Share’ button, we have to oass the custom button parameters in ‘actions’ attribute of the post call.

Code to publish message/post which contains any link attachment is as :-

      String message=  //Message to be published on facebook wall
      String access_token= // facebook access token
      String attachmentImageUrl= // Url of the image to be published in the wall post
      String attachmentLink= // Link attached with the message

       StringBuilder sb = new StringBuilder("access_token=");
        sb.append(URLEncoder.encode(access_token, "UTF-8"));
        sb.append("&message=");
        sb.append(URLEncoder.encode(message, "UTF-8"));
        sb.append("&picture=");
        sb.append(URLEncoder.encode(attachmentImageUrl, "UTF-8"));
        sb.append("&link=");
        sb.append(URLEncoder.encode(attachmentLink, "UTF-8"));
        sb.append("&actions=")
        sb.append(URLEncoder.encode("[{name: '${BUTTON_NAME}', link: '${SHARE_BUTTON_BASIC_URL}${attachmentLink}' }]", "UTF-8"));

            URL url = new URL('https://graph.facebook.com/feed');
            HttpURLConnection connection
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + sb.toString().length());
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWriter.write(sb.toString());
            outputStreamWriter.flush();
            connection?.disconnect()

So, whatever we provide in the ‘actions’ property of post call, will appear in the wall post with the defined action. Here we are using it as link to Share a facebook wall post.


Sample post with custom ‘Share This’ link on facebook Wall



This worked in my case.
Hope it helps.

Cheers!!!

Vishal Sahu
vishal@intelligrape.com
www.intelligrape.com
http://www.linkedin.com/in/vishalsahu

  • Share/Bookmark
Posted under Grails

Creating GIT Alias

Posted by Hitesh Bhatia on December 30th, 2011

Since Git is awesome. It also provides functionality of making aliases.
Example

git config --global alias.co checkout 

Here we created co as an alias for checkout (All the aliases that are created goes into .gitconfig file under home folder). Now to checkout a branch named testBranch, We can also write

git co testBranch
Switched to branch 'testBranch'

Here are couple of interesting git aliases that we can make

1.git config –global alias.undo ‘reset –hard’

Now if we write “git undo” then any of changes after my last commit will be removed.

2.git config –global alias.cleanup = ! git fsck && git prune && git gc

In this Command we have used exclamation mark (!), this indicates that these commands would be running on terminal.
And in git if I want multiple command to be running one after another we use double ampersand (&&) (We cannot use semicolon as we would usually do in terminal).
This command will run git fsck (file check), git prune (to clean dangling commits/blobs) and git garage collection

Number of git alias that can be made are endless all it needs is little creativity.

_________________________________
Hitesh Bhatia
Mail,LinkedIn,Facebook,Twitter
_________________________________
  • Share/Bookmark
Posted under Grails

GIT Maintenance

Posted by Hitesh Bhatia on December 30th, 2011

Since we use git numerous times a day over and over, hence needs maintenance. There are few commands that will help you to keep our git healthy. If you feel that you git has somewhat slowed down, these would do the trick for you.

Since ours is a pretty big project . I run it once a week to make sure my git is healthy.

1.git fsck

This commands helps to identify any corrupted, unreachable (dangling blobs) objects in your database.
Example

git fsck
dangling commit 652424f02c17b5d881158a625f1a34f6039dc231
dangling commit 7e6510c2663530d949ea9fb67900496dcf5cbc4c
dangling commit 177864469ea87564ade9101106d5aa85cceb0d29
dangling commit 848665007bc412910b68dc3e528e74c23ce1f165
dangling blob dfa6756511b525996946de84fa7f67b6f9a0d32f
dangling blob e7f8f1145c7e739a6ffd8806a6d26d60f0443897
dangling blob f1f905a5eb35724622249f25f6d9ef7c646e4283
dangling blob 221417781e017cf02f90b872aea80f30ed41787c
dangling blob c1356b24fb2a4ea453dba87ed4058e7a48e97dce
dangling blob cb6fe3d5321b7b152a8781541bbc6132c59b9c94
dangling blob 3ce2e76cd54f0c8265ec6167f78d5dfe71c2242d
dangling blob daf073729960c40a44c5291c745092445bb2c3b0

2.git prune
With git fsck, we identified some of dangling commits and blobs, now to remove them we use git prune.
Now After running git prune, If I run git fsck again, my git would be cleaner than before and healthy.

git fsck
dangling commit 177864469ea87564ade9101106d5aa85cceb0d29
dangling commit 848665007bc412910b68dc3e528e74c23ce1f165

But it still has some dangling commits.This is where git’s garbage collection comes in play.

3.git gc (Garbage Collection)
This command will gathers up all the loose objects and places them in packfiles. And removes objects that aren’t reachable from any commit. This command will save some space and speed up many of git commands.
Example

git gc
Counting objects: 121775, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (18239/18239), done.
Writing objects: 100% (121775/121775), done.
Total 121775 (delta 76189), reused 120913 (delta 75659)
Removing duplicate objects: 100% (256/256), done.

Output of this commands tells several things to us , that is compressed 18239 objects for us out of total 121775 objects. And it also removed 256 duplicate objects. This way my git stayed healthy.

_________________________________
Hitesh Bhatia
Mail,LinkedIn,Facebook,Twitter
_________________________________
  • Share/Bookmark
Posted under Grails