Andres Almiray's complete blog can be found at: http://jroller.com/aalmiray
Monday, January 23, 2012
A few days ago I was discussing the topic of builders during a Grails training session. After surveying the usual suspects found in the standard Groovy distribution (MarkupBuilder, SwingBuilder, Antbuilder and ObjectGraphBuilder) we jumped into Grails' DomainBuilder. Once we got familiar with it the team seized the opportunity to refactor an existing application they've been working on for a few weeks. The idea was to remove a very verbose data setup during the bootstrap sequence.
Like many other applications out there, this one requires setting up users and roles to secure access to some areas. The User and Role classes looked like the following ones
Nothing complex really. Now, during bootstrap there were a handful on instances of both classes being created and saved. A few users would share roles which meant keeping a reference to the common role to later use Grails relationship methods. This caused the code to be not so much DRY, and while it's good to be WET from time to time this wasn't the case. Let me show you how the code looked like before we added the builder
We could have saved a few lines by collecting all domain classes in Lists then applying *.save() on the lists, however that would still have left the relationship methods being defined explicitly. This is where DomainBuilder came in. With it we were able to define the domain instances and the relationships at the same time. We ended up with code looking like the following one
DomainBuilder understands perfectly well the relationships between domain class instances. It also makes some assumptions on how the model is setup, but we still need to give it a few hints. In line 7 we can see a classNameResolver set on the builder. By convention the builder will use an strategy to construct fully qualified classnames out of node names. If the classes happen to be defined inside a package then you must define a custom classNameResolver. In our case the classes we're interested in live under the same package so we only need to specify it, the builder will do the rest to figure out the correct class name.
Next, we must set a custom identifierResolver because the id property is of semantic meaning to domain classes. The builder can keep references to all instantiated nodes, it will use the id property by default, assuming that's a synthetic property. This means it will treated in a different way than the rest of properties. Because id is used by domain classes we set a different synthetic property named nodeId. Finally we define a custom factory to serve as the root of the object graph. This custom factory requires additional setup to handle its children, which is why we also register a custom ChildPropertySetter on the builder. These two helper classes can be seen in the following snippets
Basically the code inspects the type of the parent node. If it's a List then we append the child to it, otherwise we let the standard behavior take control. You can read more information on the builders used at FactoryBuilderSupport and ObjectGraphBuilder.
Keep on Groovying!
Monday, October 24, 2011
A common question asked in the Griffon mailing list is: can GORM be used with Griffon? Sadly the answer is no, not yet. However this doesn't mean there's no persistence support for Griffon at all, quite the opposite, there are 17 active plugins at the moment with a few more in the pipeline.
Regardless of where you stand in the SQL/NoSQL debate Griffon has you covered. Let's begin with what could be said is the most familiar type of storage so far: relational databases.
First stop is the Datasource plugin. This little guy enables access to any java.sql.DataSource compatible datastore. An additional configuration file named DataSource.groovy will be added to the configuration directory of your application when you install this plugin. If the name rings a bell with Grails' conventions wait until you see its contents as created by the default template
Quite similar to Grails' own DataSource.groovy -- that happened by design of course. But the good news do not stop there. This plugin injects a new dynamic method to controllers by default; you can opt to inject this method to other artifacts as well, as long as you configure that option
. This method understands the multiple datasource option supported by the plugin. Oh, did I fail to mention this plugin supports more than one DataSource from the get go? Well, it does
Here's how typical invocations look when the method has been injected to a Service
Not bad, not bad at all. Did you know you can rewrite the whole thing in plain Java? Let me show you how it can be done
Definitely more verbose that Groovy but gets the job done as well. This plugin is usually used in tandem with the GSQL plugin as the latter enables a data bootstrap mechanism similar to GORM's. At this point some of you may be thinking "OK, I can make raw SQL calls to any datasource but why would I do that if there are plenty of ORM solutions out there?". And you may be right. Love it or hate it, Hibernate is perhaps the most well known ORM in the Java space. This is the same technology that GORM uses under the covers to do its thing. There's as a matter of fact, an incubating hibernate plugin; we hope we can release it soon. In the meantime you may want to explore other options
- ActiveJDBC - a port of Rails' ActiveRecord. This is a good fit as long as your database is MySQL, Postgresql, Oracle or H2. For all others you're out of luck.
- Ebean - a light, JPA compatible alternative.
- MyBatis - formerly know as iBatis. A long standing option for those that think Hibernate is too big.
- Carbonado - made by Amazon. It can also query BerkeleyDB data stores.
Moving onto NoSQL, we now know that Carbonado may work with BerkeleyDB. If you're thinking there's a high chance that BerkeleyDB could be used separate from Carbonado then you're right. The following list enumerates all NoSQL options currently supported by Griffon via plugins:
The first 7 are Key/Value stores. Neo4j is a Graph based database. The last two are object stores. All of them support multiple datasources, data bootstrap and a Java friendly API similar to the one shown earlier.This is by no means an exhaustive coverage of all NoSQL options that either have a Java or REST based API. We chose those two constraints as they allow us to avoid dealing with platform dependent libraries. If you're aware of other choices that should be in this list then please drop us a message at the mailing lists and we'll see what can be done about it.
Keep on Groovying!
Friday, October 21, 2011
Java Swing developers are well aware of the golden Swing Rule. Given that it's so easy to break it we at Griffon try to make your life easier by sticking to conventions.
As a developer, you'd like to write code like this
The Model is somehow bound bidirectionally to the View, which means every change made to the View is propagated to the Model and vice-versa. The searchInterwebz action is most likely tied to a button, which means it will be invoked in the same thread that dispatched the event; that's right, that would be the EDT. Reading information from the Model is safe as long as it's done in the same thread that updated it (the EDT). Writing back to the model should be done inside the EDT as well. However querying the network and processing the results are tasks that must be performed outside of the EDT or we risk scaring users away as we just broke the Swing Rule.
Since the early days of Griffon we advocated the usage of edt{}, doLater{} and doOutside{} to properly identify blocks of code that must be executed inside a particular thread. The previous code can be rewritten like this
Much better. We've made explicit the fact that querying the network should be done outside of the EDT and that updating the back the model should be done inside the EDT. If the application we're writing requires only a handful of actions then this coding style is good enough. However it can get out of hand and probably tiresome to apply the same mechanics to a bigger set of actions. Considering that most of the actions may react to an UI event and most likely execute a computation that must be run outside of the EDT ... couldn't we figure out a convention that covers most cases? That's precisely what Griffon 0.9.2 did. Since that version, Griffon assumes that all controller actions must be invoked outside of the EDT. It applies some byte code manipulation magic (well, it's just AST manipulation really) to wrap each action with doOutside{}, like so
Good! However there's one slight problem with this approach. We now have to make sure the action explicitly updates the model inside the EDT -- that's why we wrapped the call with edt{}. What now?
Let's trace back to what we know and what Griffon should be aware given that it compiles our code. The enabled property of the model is bound to an UI component, probably in the this wayOK, so Griffon knows the particulars of that binding. It knows that the button's enabled state will change whenever the Model's enabled property is updated. Couldn't it figure out a way to transparently update the UI inside the EDT as well? It turns out now it can.
Griffon 0.9.4 was just released today. It includes Groovy 1.8.2 containing a new feature described by GROOVY-4962. Basically what this feature does is figure out the correct thread to use when updating a binding depending on the type of beans used in the binding. You're now able to rewrite the Controller code in this way
- the action will be invoked outside of the EDT automatically, as if wrapped by doOutside{}.
- model updates will be sent in the same thread as the caller (a non-EDT thread), however for listeners that have ties to UI elements (like the binding) the notification will be sent inside the EDT.
How's that for code clarity and brevity? In the case these conventions get in your way know that you can disable or configure them to your needs.
Keep on Groovying!
Saturday, September 10, 2011
During the last year the framework has received plenty of feedback from many sources. The team welcomed two new members that injected new life and new perspectives. The code itself has grown and shrunk a couple of times, and yet we keep adding interesting features to it. The plugin community is also building up. In particular I'd like to thank Nick Zhu for his heoric efforts in porting Grails' validation API into a Spring-free plugin. He did it mainly because he needed the behavior for an application he was working on. We're so glad he decided to open source the plugin immediately, as feedback flows in both directions without barriers (one of the major advantages of open source
).These days the team is getting ready for two big overhauls that should result in better performance during buildtime and a faster/smarter build for the framework itself (we switched to Gradle a year ago but we haven't really tapped into it, yet). In the meantime you can enjoy interesting features like
- Building a 98% Java based Griffon application. Say what? Aha! You thought that because Griffon is based in Grails this means that applications must be written in Groovy? Well, not really. You can write any artifact in Java (you can even use Scala or Mirah if you're feeling adventurous). This is possible because every single Griffon artifact is backed by an specific type (an interface) and a default implementation. These things are weaved during compilation (weaved is a misnomer; in Groovy terms we apply AST transformations). Want to give it a try? Just type the following command.
griffon create-app sample -fileType=java
Now you have an application with the initial MVC written in Java. Look into the lifecycle directory. You'll see that the scripts have been replaced by Java classes too. Hey, even the global event handler (Events.groovy) can be written in Java, leaving only the basic configuration files in Groovy source. - While we're on the topic of Java, have you ever wanted to apply Groovy-like AST transformations to Java code? Look no further, Project Lombok is your choice. It so happens that Griffon has a Lombok plugin that allows you to apply @Bindable to Java source code for example. Neat, huh?
- Application archetypes. This feature has the potential to change how an application is bootstrapped in the first place. You can catch a glimpse of it when using the included jumpstart archetype, like this
griffon create-app sample -archetype=jumpstart
Go ahead, give it a try. Also, why don't you append -fileType=java to it. That's right. You get a full Java application boostrapped using the jumpstart archetype. - We may not be ready with GORM but we have persistence ready plugins like GSQL, ActiveJDBC, EBean, MyBatis, Db4o, Carbonado, Neodatis, and may other popular NoSQL alternatives
Here's to the first 3 years of development of the most exciting piece of code I've been involved. Looking forward to the following years

Keep on Groovying!
Monday, August 15, 2011
This release comes with plenty of new features and bug fixes. The following is by no means a complete breakdown of all the things you'll find. Refer to the Release Notes to get the full list of items and issues fixed.
Let's start with the update that many were expecting to happen: the jump to Groovy 1.8. this particular version of Groovy comes packed with lots of improvements, as it can be observed in the release notes for 1.8.0 and 1.8.1. New AST transformations like @Log and @Canonical are now at your disposal; stop writing boiler-plate code when you can let the compiler do the heavy lifting

Next is the fully revamped Java support. For example, it's now possible to write a Griffon application with 98% Java code. All artifacts, lifecycle and event handlers can be written in Java source (or Scala, Mirah and/or Clojure for that matter). It's also possible to write a plugin/addon in Java as well. Even the jumpstart archetype has received a facelift. You can create a Java based application with this archetype using the following command
If you look closely at the generated files you'll discover that every single one of the source files is Java based, except of the configuration files found in griffon-app/conf (though the general events handler is Java (Events.java)).
If you're keen of using an IDE for your Groovy development activities you may be aware that both IDEA and Eclipse have a feature that enables code suggestion for dynamic code. This feature is called GDSL and DSLD respectively. Griffon includes DSL descriptors for both technologies, allowing you to invoke code completion in View scripts and AST injected methods.
In terms of packaging, the application's manifest entries are fully customizable. You can define new entries and even rewrite standard ones. Single jar packaging had a problem when duplicate file paths were encountered. Most often than not the new file would be discarded and the old one kept. Well not anymore. You can specify a merging strategy per path using regular expressions. There are plenty of options to choose from.
Looking at the runtime enhancements, there's been a lot of work to make the size of the runtime library as small as possible. Griffon 0.9.3 is approximately 25% smaller and it even includes new features! For example there's a logging appender that translates logging events into application events, useful for routing a logging statement into a status console or display an error dialog when an error is logged. Building MVC groups is the bread and butter of a medium to complex application. Some of those groups are intended to be used in a short period of time and then be discarded. While doing so it's important to remember the lifecycle of a group. That or just use the new set of withMVCGroup() methods that relieve you of the burden of keeping tabs on the group's state. Here's one example, assuming that the group display is a Dialog based groupIn case you're wondering how this code would look in Java Byte code injection via AST transformations has become a staple of Griffon. All AST transformations have been relocated to package griffon.transform to keep them aligned with the transformations found in Groovy 1.8 (most of them living under groovy.transform). There are two transformations new to this set:
- @ThreadingAware - injects the griffon.core.ThreadingHandler interface. Pretty much makes the class aware of Griffon's threading facilities.
- @MVCAware - injects the griffon.core.MVCHandler interface. Allows the enhanced class to work with MVC groups as if it were a Griffon artifact itself.
OK on to the last bits of release goodness. There are new plugins as well as updates to existing ones. Here's a quick summary:
- Actions - automatic action management, complete with i18n customizations.
- Lombok - apply AST transformations to Java code.
- Datasource - multiple datasource support.
- ActiveJdbc - lite ORM inspired in RoR's ActiveRecord.
- Ebean - another lightweight ORM solution, supports JPA.
- MyBatis - yet another lite ORM solution.
- Carbonado - what?! another ORM solution? you betcha

- Weld - enables addons to contribute beans to the BeanManager.
- GSQL - leverages the Datasource plugin to provide multiple datasource access.

Keep on Groovying!

