Sep
15
Posted by Jozef Dransfield
So we all should know how we can write our own custom controllers, and how to instaniate them inside interface builder, so this post is about how to split the interface up into different nib files.
Why do we care about splitting our app over multiple?
- Memory Management of interface objects is handled for us by the nib infrastructure
- Faster loading nibs- the less we have in any single nib the quicker it can load
- Lazy loading, the objects in a nib are all created when that nib is loaded, so splitting our interface over multiple nibs means we can enjoy lazy loading of a lot of our application
When we tell XCode to add a new interface nib file, regardless of the type of nib we always get one instance of an object called the "File's Owner". If you look at the properties for this object it will tell you that it is a special type of object called a Proxy Object.

We can tell this object that it is an instance of one of our own custom controllers, then we can wire its properties to our visual elements.
Here is the important part, telling Interface builder that your File's Owner is an instance of your custom controller will not instantiate that class for you! Meaning if you tried to load this nib from somewhere only the static non instance methods would be called!
So how to we solve this?
At the point where you want to replace the content of a view (for example a tab in a tab bar controller) you click on Interface builder's representation of the view and input your nib name.
The display will change to indicate the contents of this view will be loaded from another nib.

Then you need to head over to the class definition and tell Interface builder this view which will be loaded from nib x is an instance of your custom controller.

This is then where your object is instantiated, and pushed into the File's Owner proxy object of the nib to be loaded.
Aug
30
Posted by Jozef Dransfield
Grails provides built in support for doing REST APIs.
By modifying the URLMappings.groovy file you can map the different HTTP methods to different methods.
"/remote/message/$id?" (controller: "message") {
action = [GET: "show", POST: "save",
DELETE: "delete", PUT: "update"]
}
Then we can use Groovy's support for renderers to return our XML/JSON data
def messages = Message.
list() }
If you want custom XML its best to use either a builder or custom code.
Now we might want to send a PUT/POST request, and in grails its very easy we can use its built in functionality to pre parse our incomming XML.
Given this XML
<message>
<subject>Hi</subject>
<body>How are you?</body>
</message>
We can do this:
}
The final component is HTTP Basic Authentication, this seems to be the standard way to indentify the current user. So how can we do it in Grails?
Well I am using JSecurity so all my authentication realms etc are already established, but to secure the /remote/* url with Basic Auth we need to edit
the Config.groovy file, and add this new property "jsecurity.filter.config"
jsecurity.filter.config = """
[filters]
authcBasic = BasicHttpAuthenticationFilter
authcBasic.applicationName = grassr library
[urls]
/remote/** = authcBasic
"""
We define a new filter called authcBasic which is assigned to the jsecurity BasicHttpAuthenticationFilter and we give it an application name to use for a prompt in the browser (in the case of a REST API this isnt really important).
Finally we says that the authcBasic filter will take care of any url which begins with remote/**
Aug
27
Posted by Jozef Dransfield
Why do they need a garbage collector in Yorkshire?
Because they keep calling "init"!
Aug
02
Posted by Jozef Dransfield
Im pretty sure there is some discrimination against us poor Java/Grails developers coming from the facebook world. Its all php this, ruby that, and they discontinue their java framework.
Well thanks facebook, thanks.
So anyway whats left: well some guys have taken over the official library and moved it over to google code. You can get it here: http://code.google.com/p/facebook-java-api/. I used the facebook-java-api and facebook-util.Just drop the jars in your app root/lib folder.
Still it proved pretty difficult to find any kind of example code, so i thought i might try and help anyone else trying to develop some facebook apps in the java world.
The First controller
def facebook =
new Facebook
(request, response, apiKey, secretKey
);
facebook.requireFrame()
facebook.requireLogin("http://www.grassr.com/Library/facebook")
def user = facebook.
get_loggedin_user() }
the Facebook class is a helper class provided by the facebook-util jar, it is useful because it very closesly resembles the PHP library, meaning very often the best way to work out how to do something in your groovy code is to look at the extensive list of PHP examples.
So what does this code do? Well firstly we are creating the facebook helper class with our request, response and the two keys provided to us by facebook. This lets us talk to facebook and get the information we might need and also provides the api for doing things like posting a short storey to an account.
Next we say we require a frame to draw our stuff into then requireLogin. The require login is probably the most important, as it this call that opens us our session with facebook. When a user first visits, this call makes sure they are logged in and then prompts them to give permission to this application to access their information.
The url parameter is the url to call once the login and permission is granted.
Finally we ask for the current user.
Now we just add a index.gsp page which we can put regular html (as long as it is supported by facebook) and any fbml we might require.
Of note: when you are defining a tab for the new style facebook the facebook.get_loggedin_user() infact returns the owner of the tab being viewed, not the current user!
Aug
02
Posted by Jozef Dransfield
Small one today, I finally found out how to discover the Locale grails was using to resolve the messages.properties and how to set it programmatically. (Thanks to the lovely folks on the grails mailing list)
def key =
"org.springframework.web.servlet.DispatcherServlet.LOCALE_RESOLVER" def localeResolver = request.
getAttribute(key
)
To set the locale:
localeResolver.setLocale(request, response, locale)
To get the locale:
def locale = localeResolver.
resolveLocale(request
)
Jul
25
Posted by Jozef Dransfield
PHP and other languages support editing the code on the server, which makes writing facebook apps a lot easyer, but unfortunately your lovelly groovy code is typically trapped inside a war file on your server.
So what i did was used a dynamic dns service DynDNS to establish a URL that corresponds to my Mac.
To keep this upto date i am using DynDNS Updater for mac http://www.dyndns.com/support/clients/mac.html
Then in the setting for facebook i set the callback URL to my new dyndns host name.

And added :8080/app_context
Now i hit refresh on my facebook app and it connects to my local development environment for live refreshing!
Jul
07
Posted by Jozef Dransfield
I saw a post on dzone (but i dont know the address) a while ago showing how to do a many to many relationship in grails, using a relationship class. People seemed a bit critical of this post because grails can do many to many automagically.
However i have had to use a lot of relationship classes all over grassr, because i need additional information about the relationship. Usually this involves the date that this relationship was created but there can be other data you might want to store.
So quick recap on using Grails style Many to Many relationships and then a relationship class.
The Grails Way; The User class
....
}
The Item class
.....
}
and now using a relationship class method.
}
The relationship class
static belongsTo =
[user: User, item: Item
] }
The Item class
}
Jun
22
Posted by Jozef Dransfield
So this next look into grails development is meant to help people get to grips with webflows; to explain how to go from a conceptual diagram to real groovy code.
So lets begin with a little introduction of the different types of state grails provides us with to build our webflows.
View State
A state of the webflow which just displays a page to the end user.
Action State
An action state has no view but performs some kind of action, effectively it is a code block that gets executed.
Action/View State
Somewhere in between the previously mentioned 2 is the action view state, which renders a view, but can also execute an action prior to moving onto the next state. This will be explained in greater detail below.
So using these types of state we are going to build this state diagram in groovy

Our diagram begins with an "init" action that puts us into the Form state; where we display the form to the end user.
init {
action {
flow.referer = request.getHeader("Referer")
}
on ("success").to "form"
.....
}
So far we have declared our new webflow by defining a closure in our controller that ends with the word Flow "def createItemFlow = {" then by convention the first block will be our initial webflow step. This step is of the Action type, Grails will not look for a view to render for this action because we define an action closure inside. All the action does, is saves the address of the page which sent us here into the flow scope "flow.referer...."
Our action closure will execute and return a message to our webflow step, by default if we do not return an explicit value or throw an exception the "success" message is sent. This mechanism allows us to navigate according to the result of our action block
The final line states that upon successfully executing the defined action we should navigate to the Form step.
form {
on("done") { ItemCommand itemCmd ->
flow.itemCmd = itemCmd
if (flow.
itemCmd.
hasErrors()) }.to "confirm"
on("cancel").to "end"
}
Here we have an action view state, we know its not an action state because there is no action block defined so normally it would be a View state except that there is a code block following the on("done") this means we have an Action/View state.
Upon navigation to the form step from the init step, grails will search for a template with the name #controller_name#/createItem/form.gsp which it will render to the user. If grails receives a "done" message from the user the code block following on("done") will be executed prior to navigating to "confirm". In this case we are using the code block to interrupt the flow and return to the current state if the form input does not validate correctly!
If we receive a "cancel" message then we simply navigate to the end state and the webflow is done.
confirm {
on("yes").to "save"
on("cancel").to "end"
}
The confirm step is simply a View state and renders a view found in #controller_name#/createItem/confirm.gsp If the "yes" message is received we navigate to the save state otherwise if "cancel" is received we go to the "end" state.
save {
action {
Item item =
new Item
(flow.
itemCmd) item.save()
}
on("success").to "end"
}
Save is a simple Action state with no view, which actually saves our item to the database, and finally:
end()
We provide our terminal state "end", which is a view state but provides no options to navigate to any other state (hence it being empty)
So lets put it all together
init {
action {
flow.referer = request.getHeader("Referer")
}
on ("success").to "form"
}
form {
on("done") { ItemCommand itemCmd ->
flow.itemCmd = itemCmd
if (flow.
itemCmd.
hasErrors()) }.to "confirm"
on("cancel").to "end"
}
confirm {
on("yes").to "save"
on("cancel").to "end"
}
save {
action {
Item item =
new Item
(flow.
itemCmd) item.save()
}
on("success").to "end"
}
end()
}
As always I'd love to hear feedback and suggestions on this code.
Jun
09
Posted by Jozef Dransfield
I am pretty new to this grails malarky and ive been impressed with the quality of the official documentation, but i have always measured documentation beyond that officialy supplied. The measure of the quality of documentation often comes from all the little howtos and tutorials one finds on google.
So here is my small contribution, a few of the things i had some trouble with in grails and how i solved them. I would love to hear of better solutions or why the code is the way it is, and maybe some of it has been fixed since i came across them.
Pageflows names have to be unique
You sort of get used to giving actions on controllers nice simple short names like create, edit and list. What you are performing these actions upon should be obvious from the controller name, so when developing grassr i came across an annoying stumbling block that was pageflow names have to be unique. Its not a huge deal but i find myself with situations like these
class ItemController {
def createItemFlow = {
.....
}
}
For a normal action i would have wanted to use the name create but if i used the name createFlow i ran into naming conflicts with any other controller in the application that also had a createflow.
So watch out and give your pageflow unique names, you can always map them to a nicer url using the URLMapping configuration.
In pageflow actions you must use a transaction to perform a delete operation
Loan.withTransaction {tx ->
flow.loan.delete()
}
I dont really know why you have to do this, it seems strange, if you dont wrap delete operations in a transaction you are told the current traction is read only, and yet i can do as many save operations as i like.
So just wrap any calls to delete in a transaction.
XML Library Problems
I have come across problems with java libraries that use xml parsers. Specifically i was unable to get the Amazon web service library to work. I found the solution on a forum out there on google somewhere but it took a long time to find. So i cant see any harm in repeating it here.
My solution was to replace the packaged xml-apis.jar and xercesImpl.jar in the <grails_dist>/lib directory and then clean out my whole project and rebuild.
The Hibernate Context
I had a lot of problems initially with storing user data somewhere like i would in a session object in java. The majior problem i was having is the security framework i was using (acegi) was loading the object in a different context to that of my main application. Which meant when i tried to load collections of a user which desirably would be lazy loaded i was recieving exceptions from hibernate.
My solution was to just store the username as the principal in the session object and rely on the hibernate caching mechanism to stop this from hitting the database every time.
As i said id love to hear if people have fixes for any of this stuff, and i hope it might help someone else starting out with grails.