Showing posts with label grails. Show all posts
Showing posts with label grails. Show all posts

Wednesday, May 06, 2009

When Class.forName() Can't Find The Domain Class

I was trying to use reflection to create a domain class:

try {
def clazz = Class.forName(domainClassName)
def obj = clazz.newInstance()
}
catch (ClassNotFoundException ex) {
...
}


To my surprise, I caught ClassNotFoundException at line 2. After searching for a while, I found an explanation in this thread. Burt Beckwith explained that classes loaded without a ClassLoader will not resolve dynamically added classes such as the domain classes. He suggested to use the other variant:

try {
def clazz = Class.forName(domainClassName, true, Thread.currentThread().contextClassLoader)
obj = clazz.newInstance()
}
catch (ClassNotFoundException ex) {
...
}

Thanks for the tips, Burt.

Monday, April 20, 2009

Grails Quick Reference

I have just finished version 1.1.0 of Grails Quick Reference. For your download convenience, here's the zip file containing the latest source of the quick reference: http://bitbucket.org/sjtai/grailsqr/get/tip.zip. The PDF can be downloaded from here.

Creative Commons License
Grails Quick Reference by Tai Siew Joon is licensed under a Creative Commons Attribution 2.5 Malaysia License.

Saturday, April 04, 2009

Testing Controllers That Are Protected By JSecurity Plugin

It can be a challenge to write a test case to test an action that depends on the current user. For example, the list action only returns the records that is accessible by the current user.

If you use the JSecurity Plugin, chances are you will use SecurityUtils.getSubject() to refer to the current user. If the user logs in through the login form provided by the plugin, the user name is stored as SecurityUtils.getSubject().principal. What we want to do is to find a way to inject the "current" user name during the test.

This is how I did it. In FooController, I define getSubject and list like this:

class FooController {

def getSubject = {
return SecurityUtils.getSubject()
}

def list = {
def subject = getSubject()

// Restrict results in listing
...
[fooInstanceList: results, fooInstanceListTotal: total]
}
}

and the test:

void testList() {
FooController.metaClass.getSubject = { return [principal: 'user1'] }
def ctrl = new FooController()
ctrl.list()
...
}

In line 1, just before the FooController instance is created, the getSubject closure is modified to return a map that contains principal as the key. When the list action is invoked, the getSubject() method will return the map. That way, the listing will be restricted to the records which are accessible by the user user1.

Wednesday, April 01, 2009

How to rollback a transaction in a service

The Grails Framework Reference Documentation only mentions that a method in a service class can be set as transactional. However, it fails to mention how one should rollback a transaction.

It is actually easier than I thought. If the method throws an exception, the transaction will rollback. Although you can perform multi-table updates in a controller, it is good practice to do it in a service method.

Difference between findAll and findAllBy

You may have already known the obvious difference between the domain class findAll() and findAllByXXX() method. findAll() expects a query as the first parameter, followed by the parameter list and the pagination parameters whereas findAllByXXX() expects variable list of objects, ending with an optional map for pagination purpose.

There is a small difference, and I got caught once by it.

As findAll allows you to write the query anyway you want, which may include the "order by ... desc" fragment. Therefore, findAll() ignores the "sort" and "order" entry in the pagination map. This won't return a list of countries in descending order:

def list = Country.findAll("from Country c where c.continent = ?",
[ continent ],
[sort: 'name', order: 'desc']);

To make it work, I did the following:
def sort = params.sort ?: 'name'
def order = params.order ?: 'asc'
def q = "from Country c where c.continent = ? order by ${sort} ${order}"
def list = Country.findAll(q, [ continent ], params)

The params is still passed in to the function because the max and offset parameters are used.

If the query is simple enough like the query above, it is better to write:
def list = Country.findAllByContinent(continent, params)

Saturday, March 21, 2009

Integration test of Grails controller

The general pattern to test a controller is:

void testBar() {
def ctrl = new FooController()
def testParams = ...
ctrl.params.putAll(testParams)
ctrl.bar()
...
}


Different outcomes are expected from the call to the action:

Redirection


If redirection is expected, the redirected URL can be obtained from ctrl.response.redirectedUrl. Keep in mind that unless GRAILS-4270 is resolved, you will have to make sure that the controller name is specified in the parameter list of redirect(). For example,

def index = {
redirect(action: 'list', params: params)
}

won't work. You need to change it to:

def index = {
redirect(controller: 'foo', action: 'list', params: params)
}


A View Is Rendered


If a view is expected, the parameters passed to render() is actually stored in Spring's ModelAndView object. E.g. if you have the following statement in your controller:

render(view: 'show', model: [ fooInstance: foo ])

You can access foo via:

def foo = ctrl.modelAndView.model.fooInstance


Text Is Rendered Directly


If the action renders some texts directly, the texts can be accessed by

def text = ctrl.response.contentAsString


A Map Is Returned


If a map is returned, as is the case for the scaffolded list action, you can access the map like this:

def map = ctrl.list()

Monday, January 12, 2009

How to access config or metdata outside Grails controller?

grailsApplication is injected in controllers and service classes only. To access config and metadata from other classes, use ConfigurationHolder and ApplicationHolder respectively.

Reference: http://jira.codehaus.org/browse/GRAILS-2545

Monday, December 22, 2008

View the source of compiled GSP

While grails is running in development mode, you can view the source of the compiled GSP by appending showSource to the URL. E.g.

http://localhost:8080/myapp/mycontroller/action?showSource


This trick is mentioned in http://www.piragua.com/2008/03/15/viewing-the-source-of-a-compiled-gsp-in-grails/ and was requested as an improvement in JIRA http://jira.codehaus.org/browse/GRAILS-2729.

I wonder how many more of these tricks are in grails.

Monday, May 12, 2008

SQL Keywords As Column Names

Once in a while, I got caught by my own mistake by using SQL keywords as column names. For example, this looks pretty harmless (but it fails in GORM):

class Person {
String userName
String password
String group
}

There are 2 problems:

  1. password is a keyword in MySQL.

  2. group is an SQL keyword.


Although it usually doesn't take me too long to realize my mistake, it is a nuisance that I'd rather live without. There is a more systematic way to detect such problem.

Saturday, October 27, 2007

Do you use Grails in your project?

As an experiment, I recently converted a web application that I wrote 2 years ago from Struts to Grails.

Some of the immediate rewards:
  1. Code size is reduced significantly, especially codes that populate the beans with request parameters. Less code means easier to debug and read.
  2. I can specify all the constraints in the entity class and don't have to create another XML file for validation purpose.
  3. Taglib is very easy to write in Grails. I practically got rid of 80% of the Java scriptlets by using taglibs. My JSPs (GSPs actually) are much easier to read now.
  4. It runs on standard web container. I have tested it on JBoss, Geronimo and Glassfish. No problem.
Are you using Grails in your project? If yes, what makes you decide on it? If no, what are the concerns?