Grails « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ 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 in Database, GORM, Grails

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 in Grails

Writing JSON APIs : Part II – Creating JSON Named Configs to Control What You Render

Posted by Vivek Krishna on December 29th, 2011

In the 1st part of the series, we looked at how to secure our application with Spring Security Basic Authentication and modifying the JSON Marshaller. However, it could often be the case that the same set of fields shouldn’t be returned on every JSON response.

For example, we could very well have a summary JSON for Book, which just returns the id and name of the Book, ignoring the other details like ISBN, genre etc. A real life example would be a Product’s complete details when returning JSON for its show view, while returning just the id, name and price for its view in a shopping cart.

In addition to that, we could choose, not to override the default JSON Marshallers provided by Grails so that the standard rendering method is not tampered.

Grails provides an excellent solution called “Named Configurations” which comes to our aid here. That, combined with some minor modifications on our CustomDomainClassJSONMarshaller can help us achieve this.

1. Add a static Map to the domain class, probably jsonProperties :

This property will hold the group name as key and the list of properties to be included as values.


//Book.groovy

static jsonProperties = [summary:['name']] //summary is the group name

2. Update the CustomDomainClassJSONMarshaller to have a property jsonPropertyGroup :

String jsonPropertyGroup
public CustomDomainClassJSONMarshaller(boolean includeVersion, GrailsApplication application, String jsonPropertyGroup = "") {
      this(includeVersion, new DefaultProxyHandler(), application, jsonPropertyGroup);
}
public CustomDomainClassJSONMarshaller(boolean includeVersion, ProxyHandler proxyHandler, GrailsApplication application, String jsonPropertyGroup) {
      this.includeVersion = includeVersion;
      this.proxyHandler = proxyHandler;
      this.application = application;
      this.jsonPropertyGroup = jsonPropertyGroup
}

3. Update the custom marshaller registrations to create Named Configs :

This method needs updation for two reasons

  • Calling the newly created constructors
  • API changes in grails 2.0

For creating a named config “summary”, we need to write something like


JSON.createNamedConfig(JSONConstants.SUMMARY_JSON_MARSHALLER_GROUP){
     it.registerObjectMarshaller(new CustomDomainClassJSONMarshaller(false, grailsApplication, "summary"), 2)
}

4. Using the newly registered named configs from within the controller:

This is the final step. We can use the named config with a static method JSON.use(), which takes in the configuration’s name and a closure inside which we will call the render <XYZ> as JSON method


JSON.use("summary"){
     render Book.list() as JSON
}

I have updated the example application to grails 2.0 and added an example to this approach.

Grails never ceases to amaze me. :)

  • Share/Bookmark
Posted in Grails

Dbconsole in Grails.

Posted by Sachin on December 25th, 2011

So, Grails 2.0 was released a few days back and I upgraded my application to it as soon as I came to know of its final release and it rocks.!!

Among the many things which are making a lot of noise on grails 2.0, there seems to be a lack of noise over the GUI Database console which grails has provided. Developers can connect to the database from a GUI right inside there application, see the data in tables and execute simple queries. Probably its not polished yet so that could be a reason why there is not much noise over it but it still is a usable feature.

All you need to do is, run your grails 2.0 app navigate to http://localhost:8080/app-name/dbconsole/ and configure your database connection. Just select what database you are using, Select the driver, a couple of entries for username and password and you are good to go.

The query builder isn’t too great, but that is no reason to miss this useful tool. No need to move to any other application or console to see whats in the database. The database is available right in your application, and its available only in development mode, so no worries of this slipping into production. Hope this saves some time for all of us.

Thanks.
Sachin Anand
mail : sachin[at]intelligrape[dot]com
twitter : @sachin__anand

  • Share/Bookmark
Posted in Database, Grails

Grails productivity enhancer. The unsung hero ‘grails interactive mode’

Posted by Mohd Farid on November 30th, 2011

Of late, I have been thinking about the popularity of grails interactive mode amongst developers. I found that though most of us are aware of this mode but we don’t use it as often, as it should be.



Where should I use grails –interactive mode while developing in grails?
The answer may vary from person to person and the level of expertise. For me, I found it amazing while running my tests and creating artifacts.


I shall describe the advantages that I found with interactive mode while running Unit Tests. Let us take an example here:

I have a class called PersonUtil which needs to be unit tested. I write a PersonUtilTests class for testing its functionality. In order to run this particular unit test, I can use the following command:

grails test-app unit: PersonUtilTests

This takes approximately 20 secs on an average to run on my machine with a decent configuration.

Alternatively, We can run it in interactive mode. What we need to do is

 grails --interactive

This shall bring the grails infrastructure up and make it just ready to run commands. It takes around 5 seconds.

Welcome to Grails 1.3.7 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: /opt/grails

Base Directory: /home/farid/grailsApplications/survey-app/ErServices
--------------------------------------------------------
Interactive mode ready. Enter a Grails command or type "exit" to quit interactive mode (hit ENTER to run the last command):

Now, to test the app I can use the following command:

-------------------------------------------------------
Command TestApp completed in 2461ms
--------------------------------------------------------
Interactive mode ready. Enter a Grails command or type "exit" to quit interactive mode (hit ENTER to run the last command):
test-app unit: PersonUtilTests

It took 15 seconds to run this for first time.
For subsequent runs, it took 2-4 seconds. Which is a clear advantage of 16 seconds for every run. These 16 seconds are no less than gem when you are in your “flow-state”( in concentration mode).

While development, we make frequent changes to our code and therefore we need to run our unit tests multiple times. Every time I make a change and re run my unit test it takes 20 seconds through conventional grails test-app whereas it takes 3-4 seconds through interactive mode.

Earlier, I used to get frustrated while waiting for test cases to execute. This waiting time is one of the biggest factor that drives us from doing Test Driven Development.


Just in case you have not tried it. Please give it a shot. Believe me, it’s worth trying, you wont be disappointed!!!


Mohd Farid
farid@intelligrape.com

  • Share/Bookmark
Posted in Grails, Test, Unit Test

Grails:Domain Design Via Intellij Idea’s Diagrams

Posted by Hitesh Bhatia on November 23rd, 2011

Here is an example of how to design Grails domain class with Intellij Idea.For this we need to have blank domain classes. So lets say we created  three Domain Classes Company,Book,Author

  1. To see relationship diagram, Selected Domain Class, and selected tab Domain Class Dependencies.It should look like this
    image
  2. Lets assume the relation that publication has many books. So I drag mouse from Company to Books. Which invokes a popup asking about relationship between the domains and type and name of the field.
    image
  3. On Selecting ok from previous popup. Their relation is defined in domain and in diagram. Similarly, lets define
    1. Book hasMany Authors,
    2. Authors hasMany Books,
    3. Book belongsTo Author
    4. And Diagram looked like this.

    image

  4. Next Step – Lets add fields to Domain Class all by Intellij Idea’s UI. Select package of domain class and pressshft+ctrl+alt+u. It’ll open package diagram of app.
    image
  5. Now lets add field name to domain Author. For that we’ll need to select domain author,right click and select fields. It’ll invoke a popup asking details about field.
    image
    Similarly we add field name to Author and published on to Book.
  6. Now lets add a method to named “publishedBefore” to Book which takes a date and return list of books published before that date.For this we need to right click on domain and select method.And it’ll invoke popup asking details.Select create and its done.
    image

This was a simple and easy way to create structure of grails app in Intellij Idea.

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

Writing JSON APIs : Part I – Creating a secure JSON API with Grails and Spring Security in 3 easy steps

Posted by Vivek Krishna on November 16th, 2011

We had a requirement in a recent project to expose some of the functionality we had via a JSON API. The functionality needed to be secure, as was the initial web interface which exposed the functionality. We were using Spring Security for the security aspect of our application.

The spring security plugin, together with a secured controller and a custom JSON marshaller(which overrides the default functionality of render as JSON method) gave us a very simple, yet elegant and powerful JSON API which was secure. Here are the three steps that we followed

1. Setting up Spring Security Plugin:

The first step is to set up Spring Security Plugin to expose our JSON based controllers to use Basic Authentication, instead of the standard web based authentication. This is done by adding the lines given below in Config.groovy

//Enable Basic Auth Filter
grails.plugins.springsecurity.useBasicAuth = true
grails.plugins.springsecurity.basic.realmName = "JSON API Example"
//Exclude normal controllers from basic auth filter. Just the JSON API is included
grails.plugins.springsecurity.filterChain.chainMap = [
'/json/**': 'JOINED_FILTERS,-exceptionTranslationFilter',
'/**': 'JOINED_FILTERS,-basicAuthenticationFilter,-basicExceptionTranslationFilter'
]

More details about the authentication mechanism can be found here.
2. Adding a Controller with required actions:

Naturally, this is the next step. We added a controller which would expose the functionalities required(another reason why most of our logic should be in our services instead of controllers). A sample controller would look like this.

package jsonapi
import grails.plugins.springsecurity.Secured
import grails.converters.JSON
import com.intelligrape.example.json.Book

@Secured(["ROLE_USER"])
class JsonController {
      def getBooks = {
          render Book.list() as JSON
      }
}

3. Customizing the Marshaller to change the way some properties like enums are rendered:

We had to change the way some of the properties like enums were going to be rendered. We just had to render the property name and the id of the enum. So instead of a json map like


"genre":{"enumType":"com.intelligrape.example.json.Book$Genre","name":"FICTION"}

we needed


"genre":"FICTION"

I sought help from David Bower’s post and created my own custom Domain Class Marshaller for JSON with a modification to just use the Enum value if the property happened to be an enum. This is a very powerful feature because it allows us to customize the way in which we want to render the values when creating a JSON or XML document from our classes. We can even customize it to have an excludes list in our domain class where we can specify the properties to be excluded while constructing our JSON or XML

With this, we had a JSON API ready in very little time. I have extracted the functionality into a small example application, which has been shared on Github.

Yet another example of how simple grails has made it easy for developers.

  • Share/Bookmark
Posted in Grails

Grails Spring Security Plugin: User Switcher

Posted by Himanshu Seth on November 14th, 2011

If you are using Grails Spring Security in your application, one killer functionality that we can easily provide is a simple user switcher
Add this to your admin layout:

<sec:ifAllGranted roles='ROLE_ADMIN'>
    <form action='/j_spring_security_switch_user' method='POST'>
        Switch: <g:select from="${users}" optionKey="username" optionValue="displayInfo"
                          name='j_username'/>&nbsp;<input type='submit' value='Switch'/>
    </form>
</sec:ifAllGranted>
<sec:ifSwitched>
    <a href='${request.contextPath}/j_spring_security_exit_user'>
        Resume as <sec:switchedUserOriginalUsername/>
    </a>
</sec:ifSwitched>

In Config.groovy, add the following:

grails.plugins.springsecurity.useSwitchUserFilter = true

So, in two easy steps we can provide the application admin to impersonate other users. This also checks if the current user is actually an impersonation and if it is, it provides a link to go back to the original user.

Very neat indeed :)

More detailed info available here

Regards
~~Himanshu Seth~~

http://www.IntelliGrape.com

  • Share/Bookmark
Posted in Grails

Groovy : Find Index of Element in Map

Posted by Hitesh Bhatia on November 10th, 2011

Groovier way of finding index of element from Map. It can be obtained with findIndexOf Method, which accepts closure as argument.


Map map=["groovy":1,"grails":2,"index":3,"element":4]
assert 3 == map.findIndexOf{it.key=="element"}
assert 0 == map.findIndexOf{it.value==1}
  • Share/Bookmark
Posted in Groovy

Grails bindData to collections

Posted by Mohd Farid on October 24th, 2011

Recently, I was stuck with a scenario where I was trying to bind a list of objects in my controller. While trying the way as suggested in the grails docs I was getting some weird IndexOutOfBoundException. Luckily I found a good solution on the grails mailing list: http://grails.1312388.n4.nabble.com/Databinding-Collection-of-non-domain-objects-tp3260578p3260856.html
Thanks to mkwhit for asking this and Dana for suggesting this solution.

There is a Car class in my src/groovy. There is a create.gsp that should create n number of cars at a time. The problem is to bind this data to a List of Car objects.

Here is how I got it done:

I ensured in my gsp that the car parameters are passed as car.1.name, car.1.brand, car.2.name, car.2.brand ….. So, when I did a params.car I get a Map like this:

1: [name:'carA', brand:'brand1']
2: [name:'carB', brand:'brand2']
3: [name:'carC', brand:'brand2']
1.name:'carA'
1.brand:'brand1'
2.name:'carB'
2.brand:'brand2'
3.name:'carC'
3.brand:'brand3'
def carParams = params.car.values().findAll {it instanceof GrailsParameterMap}
List<Car> carList = carParams.collect {
   def car = new Car()
   bindData(car, it)
   car
}

So, we have a list of Car objects out from the params.

Hope this helps.

-Mohd Farid-

  • Share/Bookmark
Posted in Grails