Grails FilterPane Plugin Review

9th January 2010 by jt 1 Comment

Yesterday I started using the FilterPane plugin.  So far, I am very impressed with the plugin. I have a number of screens in my application that I needed to provide some basic search functionality for.  I had previously looked at the Criteria plugin and found it so so.

It probably took me an hour or so to research the documentation and example of the FilterPane plugin, my actual development time was under 15 minutes to get things up an running in my project.  I found the documentation very thorough and the example project helpful.

To get the plugin working, started with a basic list.gsp view generated from the default Grails scaffolding.  Following the plugin’s directions, I modified the list view with several new tags & I had to modify some of the existing tags.  The view controller gets a new ‘filterService’ service and one new method.

The only thing that tripped me up was I had to use the fully qualified name of the domain object.  Initially, I did not include the package name of the domain object, and things did not work.

I added the filter to my Purchase Order domain, which is probably one of my more complex domain classes.  The default setup from the directions, gives you a ‘filter’ button at the bottom of the list view.

picture-5-06-47-30

Clicking the filter button shows the filter dialog in a nice Web 2.0 fashion.  If you include scriptaculous in your page, you’ll get a nice fade in / out affect.  Here is an example of the filter dialog.  Note, this is all generated by the plugin.  The code I wrote to provide this is:

<filterpane:filterPane domainBean="org.whserat.PurchaseOrder" />

picture-7

In this example, I asked for PO’s where the PO number contained ‘3′.  Here is the result:

picture-8

I like the message provided showing the criteria applied.  This is a nice, user friendly feature.

Overall, I’m impressed with this plugin.  I really like the capabilities it adds to my application.  I’m considering adding this into by default scaffolding views.

Share/Save/Bookmark

Grails WebFlows, Services, and Rants

6th January 2010 by jt No Comments

I’m building an application that will receive inventory against a PO.  This is far more complex than the typical CRUD model seen in many Grails examples.  Naturally, I chose to put all the business logic for this transaction into a service.  In a nutshell, my service takes the PO number, item number, and quantity, and then updates the receipt quantity on the PO, creates an inventory record, creates a history record of the inventory creation, generates a receipt transaction for the host system, and so on… This is all something I want to occur in a transaction. If any step fails, I want to roll it all back.  A half baked transaction here, would be a bad thing.

A Grails service seemed perfect for this.  By default services are created as singletons, and the Spring framework is used to manage transactions.  A runtime exception anywhere in the method will rollback the transaction.  I like this concept because it leaves the service loosely coupled.  I can call it from anything.  A web form via a controller, or maybe have another service for processing messages off a JMS queue.

So I built my service as describe above.  Like a good Grails developer it was complete with unit tests and integration tests.  Everything was working well with the my service to receive inventory against a PO.

I hadn’t worked with WebFlows before, but they seemed like the ideal candidate for my web application.  My application is for a mobile device for a person on the warehouse floor to receive inventory against a PO.  They will need to enter their location, then the PO, then the item to receive.  From here I want to show them a description of the item, and allow entry of the quantity, status, and license plate (A unique id for a pallet or carton).  After receiving an item, go back and enter another item number for another receipt on the current PO.

It was a piece of cake to wire up my application flow using Grails webflows.  Under the covers Grails is using Spring’s webflows.  The Grails DSL makes things very easy.

And then my headaches started.  Every time my webflow touched a domain object, I’d get serialization errors.  This really threw me for a loop, because I was not trying to store any of the domain objects into the flow scope.  It would have made sense to me if I was trying to store the domain object into the flow scope.  Ugh.  I really did not want to go back and make ALL of my domain objects serializable to work around this ‘feature’.  Plus, if you are using custom validations in your domains (as I found by accident), you cannot serialize the domain object.  Groovy objects with closures (aka custom validator), cannot be serialized.

To make a long story short, I stumbled across a post by Ian Roberts explaining the Hibernate cache for your session is serialized in the Spring webflow. As a solution, Ian recommended to call the .discard() method on any domain object you worked with.  The problem I ran into, is when you invoked a service, the service could leave objects in the Hibernate cache.  Now being the lazy developer that I am, I really did not want to modify all my services to make sure every domain object was either serializable or had the discard method called.  Plus that solution is just plan ugly.  I just saw a future of headaches, because someone forgot to call the discard method.

Actually, there is an easy solution for this.  In your service you just need to get a hold of your hibernate session, and call the clear method on it.  Do this as the last step in your webflow, and all is good.

Now, onto the next problem.  Web Flows will also want to serialize your service.  According to the Grails documentation, you need to set the scope of your service to ‘flow’, and manually manage your own transactions.  Grumble.  This is not what I want.  I do not want a tight coupling between my Web Flow controller and my service.  My service should be, well a Service!

Transient is your friend.  My workaround here was to mark the service property in the Web Flow controller as transient. Now, this property will not be serialized. So far, this seems to be working well for me.  Although, I still want to test rollbacks further.

Here is a quick example of my work arounds:

class FooController {
 
    def transient myService
 
    def transient sessionFactory
 
    def someFlow {
       on "someEvent"  {
 
       myService.someMethod()
       . . .
       sessionFactory.currentSession.clear()
    }.to  "nextState"

You can see myService and sessionFactory are marked as transient. At run time these will be injected for you by Spring (as is normally done in Grails).  Via the sessionFactory object, we can get our current Hibernate session and clear the cache.  Now, all will be happy.

Share/Save/Bookmark

Using bindData Method in a Grails Service

5th January 2010 by jt 2 Comments

Grails controllers get a method called bindData which allows you to take the parameters map and bind the values to the properties of a domain object.  The method works nicely because it handles a lot of the type conversions for you.  This method works similar in fashion to the properties method, but it offers you more control.  Using bindData, you can include or exclude properties.   Here is the complete documentation for the bindData method.

I have a service which parses xml to domain objects.  I originally was walking the xml, casting the name value pairs to a map, and then using the properties method.  This was working well for me, until I needed the control offered by the bindData method.  When I tired to switch, I ran into a small gotcha.  Grails was throwing a method not found error.  Turns out bindData is a dynamic method that the Grails framework adds to controllers for you, but not services.

After a little digging through the Grails source code, I found the class used for the bindData dynamic method.  To add it to your services you will need to import the following:

import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod

I’m not going to get too fancy for a one off usage.  I just need to create an instance and call the invoke method. The method signature of invoke is Object, string, Object[]. I originally wrote my call as follows:

        BindDynamicMethod bind = new BindDynamicMethod()
 
        def args =  [ po, params, [exclude:['supplierAddress', 'shipToAddress', 'billToAddress', 'purchaseOrderDetail' ]] ]
 
        bind.invoke( po, 'bind', args)

But this was not happy in crossing the Goovy/Java barrier.  Groovy was treating my ‘args’ object as an ArrayList, not an array of Objects.  ANd Java was not happy about this.  Easy enough to fix with a cast.

        bind.invoke( po, 'bind', (Object[])args)

Looking at the source code of BindDynamicMethod, it seems that the first two parameters are just along for the ride.  All the program logic is applied to the third parameter, the Object array.  The object array is pretty much the call you would have done in a controller to the actual bindData() dynamic method.

So far this seems to be working ok for me.  Hopefully, this post gets someone over a little speed bump in the future.

Share/Save/Bookmark

Tweaking Grails Scaffolding

31st December 2009 by jt 2 Comments

One of the really cool things about Grails is its ability to auto-magically create CRUD screens.  This can be very handy for proto-typing and learning. Typically, you’ll change the generated screens as the application grows.   I’m building a large enterprise type application in Grails.  For the small look-up type tables, the default scaffolding  is just fine.

I’ve come across a situation, where I keep changing the same thing over and over in the generated views.  Being the lazy developer that I am, its given me the motivation to fix it.  One handy feature of Grails is if you add Date properties ‘lastUpdated’ and ‘dateCreated’ to any domain class, the GORM framework will automatically populate these for you.  Now of course it would be pointless to update these via a web form. Actually it probably would be rather undesirable to do this.  I googled this issue, and did not find a solution.  I did find a Jira ticket for it though.

The solution is easy enough though.  We just need to make a minor change to the default scaffolding.  Its just a matter of installing the templates and making a few edits.

Lets walk through a quick example. Continue reading…

Share/Save/Bookmark

Grails – The Cure for Annotation Hell

25th November 2009 by jt No Comments

Last night I attended a meeting with the Sarasota Java Users group. It was an interesting presentation on client side technologies for J2EE developers.  The presenter took the typical Hibernate/Spring stack and demonstrated how to apply RESTful web services with dojo to create a Web 2.0 application.

We reviewed a simple Hibernate data model which used JPA annotations.  After using GORM for the last few months, the JPA entity class was painful to look at.  I forgot how ugly all those annotations are! Yuk.  The presenter commented that annotations are so much easy to work with than than XML and were the way of the future.

The first part I certainly agree with.  I remember trying Hibernate 2.0 and entering the world of XML hell.  Being fluent in SQL, I quickly got frustrated with all the configuration I had to do with Hibernate.  My productivity was dying in XML hell.  It was easier just to use a well formed DAO layer and straight JDBC.  I walked away from Hibernate 2.0 feeling it was a tool for Java developers that didn’t know SQL.

Enter Java 5, annotations, and JPA.  Compared to the XML Hell of Hibernate 2.0, this was a breath of fresh air.  It is far easier to work with annotations than it is to work with a separate XML file.  I used to feel annotations were a wonderful solution to XML Hell.  But now that I’ve been working with Grails, I need to ask are we just replacing XML Hell with Annotation Hell?  Are we just moving from something that was really awful, to something that is not as awful?

Annotations, annotations, annotations.  Annotations everywhere!  Seeing the JPA entity class showed me how spoiled I am becoming with GORM.  The Java class was all cluttered up with annotations.  Like any good modern Java developer, the presenter leveraged the Spring validation framework.  Certainly a modern best practice, but again, there is another Java class littered with annotations. In GORM, this class would not even exist.  Validations are cooked right into the domain class.  The Spring validation is still there.  But in GORM it’s wired in with Groovy magic.  As a developer in GORM, I am left with a much cleaner representation of an entity.  The definition of my entity is scattered across multiple class files, it is in one.

The presenter then turned to creating RESTful web services.  This was fairly interesting, because he leveraged the Jersey framework.  Prior to last night, I was unfamiliar with Jersey.  But again, we have another Java class littered with annotations.  Jersey is using configuration instead of convention, while Grails gracefully uses convention over configuration.  In Jersey, you use the @Path annotation to define the url path.  Contrasted to Grails, by convention you automatically get controller name / method name for use in the URL path.  No need to configure it via an annotation.  Of course, if I need to override this, I can.  But 95% of the time, the Grails convention will be fine.

Annotations are certainly in vogue right now.  Its a new toy in the Java community.  After using the common sense approach in Grails, I ponder if the current adoption of annotations is bordering on abuse.  Are annotations just a band aid approach to serving a need that  dynamically typed languages such as Groovy fulfill?  2 or 3 years from now, will the Java community be reminiscing about the days of annotations?

Share/Save/Bookmark

Log4Ora Grails UI Source

14th October 2009 by jt No Comments

For those following the Grails series, I just uploaded the source code to the Log4Ora repository. See this link:  http://code.google.com/p/log4ora/source/browse/#svn/log4OraUI

Share/Save/Bookmark

Getting Started with Grails & IntelliJ Part 4

13th October 2009 by jt 1 Comment

One of the things really cool about Grails is the ability of dynamic scaffolding.  This enables Grails to create a basic CRUD application over your domain model.  I doubt if you would use this for a real production application, but it is a great way to knock out small prototypes.  And it will work fine for my Log4Ora project.  I only have a few tables to maintain.  My goal here was to provide a nice UI for users to maintain the tables.   Of course if I ever want to enhance the UI created here, I can.  Grails is fully capable of generating just about any html you can dream of.  You are not limited to using the dynamic scaffolding.

To get started we will need to add controller classes.  To do this from IntelliJ, right click on the controllers folder, and select New/Grails/Grails Controller.

picture-17

For our project, we will be creating a controller over the following domain classes:  Module, ModuleLevel, and ModuleLevelMethod.

IntelliJ will create a stub of the controller for you.

class ModuleController {
 
    def index = { }
}

To enable dynamic scaffolding, we need to change the controller class as follows:

class ModuleController {
     def scaffold = true
}

That’s all we need to do. Grails will take it from here. Continue reading…

Share/Save/Bookmark

Getting Started with Grails & IntelliJ Part 3

13th October 2009 by jt No Comments

One of the things that is baked right into Grails is the support for testing.  Most importantly, it is not cooked in as an after thought.  No, it is very much in the core philosophy behind Grails.  Which is important.  In this series, you’ve seen some of the cool stuff that you can do with the dynamic nature of Groovy.  You gain a lot of flexibility, but it is a knife that can cut both ways.  Because Groovy is a dynamically typed language, the compiler cannot do all the checks that it can on a statically typed language, like Java, C#, or C++.   This leaves you more prone to run time errors.

Out of the box, Grails supports 3 different environments – development, test, and production.  All are configured to use HSQLDB.  Development and test use an in-memory database, while production will persist the data to disk.  No worries if you want to use a different database, its just a matter of editing the JDBC configuration in a properties file.

What is interesting behind the approach is development and test are setup as in memory databases.  Meaning when you bounce the application server, they’re gone.  You start fresh each time.  Which is a blessing to me.  I’ve seen too many shops depending on database refreshes from production so they could ‘test’.  I’ve never bought into this argument.  Its down right dangerous and irresponsible to develop software like this.  The ‘need’ for to copy data from production typically is rooted in poor work habits.

Just to recap, Grails will automatically build your data model from your domain classes.  Tables, indexes, constraints, etc – will all be built automatically for you.  For simplicity, I am going to keep focus on the HSQL in memory database for this series.  If you’re working in an enterprise, no worries.  There are tools available to assist with migrations. And that is a topic for another day.

Typically, an empty data structure is not going to do you much good.  Just about any application will need some seed data in the database.  In Grails, this is a very easy problem to solve.  Grails offers a ‘BootStrap’ class that will run at start-up.  You can easily add code which will run to populate your baseline data.  One important note about the BootStrap class, it will be called on startup, and when running integration tests.  It will *not* be called for running unit tests.

Continue reading…

Share/Save/Bookmark

Getting Started with Grails and IntelliJ – Part 2

12th October 2009 by jt No Comments

At the very heart of Grails, are Domain Classes.  These are used to define the model of your application.  Via a few simple commands Grails can auotmagically create web screens over your domain classes to support basic CRUD (Create, Read, Update, Delete) operations.  This allows you to rapidly prototype applications.  As this series progresses, you will be amazed, at how little code you will need to write in order to build a functional web application.

I played with Hibernate back in its 2.x days.  Quite frankly, it sucked. It was a combination of verbose classes and XML hell.  To me, working with Hibernate was a bigger pain in the neck than it was worth.  I became convinced that Hibernate was for Java developers that didn’t understand SQL. Later, with the advent of JPA and annotations, we were able to say adios to much of that XML hell.  The developer experience was much improved.  But things still felt a bit clunky.

Grails brings us GORM – which is Grails/Groovy over the Hibernate 3 ORM engine.  Goodbye XML, goodbye annotations. And hello dynamic methods and finders.  So far, working with GORM is the most positive experience I have had using any ORM.  The more I work with it, the more things just make sense.  It doesn’t feel like you are working with some kludge to mask the database.

Continue reading…

Share/Save/Bookmark

Getting Started with Grails and IntelliJ – Part 1

12th October 2009 by jt No Comments

For the last few months, I’ve been dabbling with Groovy & Grails in IntelliJ.  Jet Brains has added outstanding support for these languages.  On my Log4Ora open source project, I thought it might be nice to provide some type of web based UI to maintain the database settings.

One of my goals for Log4Ora was to allow you to change log levels on the fly.  I did this by storing the settings for each module in a table. (a module being defined as a package, procedure, function, or trigger)  The initial design I had for this works, but really is awful.  Its not flexible, and violates basic normalization rules.  Its something I’ve been thinking about refactoring.  You can see my original table design here.

Let’s go ahead and refactor this, but we’ll use Grails to help us out.  But before we dive in, you might be wondering why Grails?  Good question.  In a nutshell, Grails gives us a OS and database agnostic web application framework which is designed for rapid application development.  Some people say Grails is just Ruby on Rails, but for Java.  Not exactly.  There are a lot of similarities, but this is not just a Java flavor of ROR.  Grails combines battle proven technologies from Groovy, Spring, Hibernate, and Sitemesh into a comprehensive web application framework.  The dynamic language capabilities of Groovy allows for for things just not possible under pure Java.  Groovy still compiles down to Java byte code, and at the end of the day, you still still produce a standard WAR file which can be deployed to your favorite Java app server.

Ok, enough about Grails, lets get started.  I admit I’m biased to the IntelliJ IDE.  Its a great product & Jet Brains customer support is second to none.  For this series, I will be using examples from IntelliJ.  The first thing we need to do is start a project.  Before you start, I’m assuming that you have Java, IntelliJ, and Grails installed.  If not, please install these before proceeding.

Create Project

Select the option to create a project from scratch, then click next.

Continue reading…

Share/Save/Bookmark