Posts Tagged: groovy

Oct 09

Java multiple class loaders issue

I was facing a rather subtle bug building a decision engine using Drools. Not to get into details of drools here, but the following mostly applies to many rules engines. The basic architecture of the decisions engine is that rules are written using a drools-based rule DSL. These rules are then applied to “facts”, which in the context of java, are just POJOs. These POJOs can be defined using standard java classes, or using Drools declare facilities which allow you to declare fact types in the actual rules file and then query it using JavaBean like helper utilities in the java application. In our decisions engine, we allow to define types either using drools declare and/or using groovy to define the fact object, which is then parsed, defined, and linked by GroovyClassLoader at runtime, making it available to the working memory of the drools engine as well as its rule parser.

Everything seemed like it was working using Drools defined facts using declare. I was able to dynamically create and query the fact types using reflection. This was great, as we can inject different rules and deploy functionality on the fly. I then created a groovy class, parsed it and injected into the drools package builder as well as its working memory.

Code I used to test the rule inference on the fact type.

def domainClass = '''
  package com.buycentives.types
  import com.buycentives.incengine.*
  class Input {
    String name
    int age
    boolean valid
Class inputClass = new GroovyClassLoader().parseClass(domainClass)
def input = inputClass.newInstance() = "Ilya"
input.age = 25

/// Here we inject the fact and fire the rules, see the following java code snippet

// This code was originally failing
assertEquals input.valid, true

Here is the code I used to assemble the working memory. This code is more modularized in my code and I tried to compile it into a snippet, though I might of missed something and some object instantiations are not shown.

ClassLoader loader = new GroovyClassLoader()
PackageBuilderConfiguration config = new PackageBuilderConfiguration();

KnowledgeBuilder kBldr = KnowledgeBuilderFactory.newKnowledgeBuilder(config);
kBldr.add(ruleResource, ResourceType.DRL);

if (kBldr.hasErrors())
  throw new RuntimeException("Unable to compile rules. " + kBldr.getErrors().toString());

KnowledgeBase kb = KnowledgeBaseFactory.newKnowledgeBase(new RuleBaseConfiguration(loader));
StatelessKnowledgeSession kSession = kBase.newStatelessKnowledgeSession();

The rule that was being asserted

package com.buycentives.incengine.rules

import java.util.Date
import com.buycentives.types.Input

rule "Assert for age"
    $input: Input( age >= 20, age < 30 )

To make the story short, the rule never fired, although I verified that the Input object instance was injected into the working memory, though never changing the fact’s valid property. I beat my head against the wall over and over and over and finally I realized what was going on. It’s java’s class loader caveat. It’s not really a bug, rather a feature I guess. It’s not really documented in the javadocs, but I’ve seen references to this caveat before.

When you load the same class using two different class loaders, inside the jvm, they are considered two different classes, although logically they are the same, therefore failing the Class.isAssignableFrom and instanceof conditional test.

So the following test would fail…

def domain = "class Test {}"

GroovyClassLoader loader1 = new GroovyClassLoader()
Class clazz1 = loader1.parseClass(domain)

GroovyClassLoader loader2 = new GroovyClassLoader()
Class clazz2 = loader2.parseClass(domain)

assertTrue clazz1.isAssignableFrom(clazz2)

So the lesson here, beware of injecting class loaders, especially when you’re comparing classes that were loaded with a different class loader than the class loader of the thread that’s inferring equality.

Also, beware of GroovyClassLoader.parseClass method. It parses, defines, and links the class, but if you then use it again on the same class, the resulting classes are different.

The following test fails…

GroovyClassLoader loader = new GroovyClassLoader()
Class clazz1 = loader.parseClass(domain)
Class clazz2 = loader.parseClass(domain)

assertTrue clazz1.isAssignableFrom(clazz2)

Also, this link from “Java Specialist Newsletter” is a good source of some interesting class loader information.

Sep 09

Grails 1.2 dependency management

Grails 1.2 comes with a great dependency management. You no longer have to manually manage the dependencies and don’t have to resort to using maven for this task. Grails uses Apache Ivy under the hood for transitive dependency management. Ivy allows to set up multiple resolvers and resolution patterns though allowing you to adapt to maven repositories and many other, even custom repository schemes. Grails takes it a step further and allows you to do this with a pretty nice looking DSL.

Application dependencies are configured in BuildConfig.groovy file and they look something like this…

grails.project.dependency.resolution = {
  inherits "global" // inherit Grails' default dependencies
  log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
  repositories {

    mavenRepo ""
    mavenRepo "
  dependencies {
    // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
    runtime 'com.mysql:mysql-connector-java:5.1.5'

By default, grails pulls dependencies from your grails installation library. You can also uncomment (as you see above), the mavenCentral() repository. These are the defaults and don’t require any more configuration. You can also specify a custom maven-compatible repo URL using mavenRepo.

There is also a flat dir resolver, allowing you to resolve dependencies to some local directory. You can do this as:

flatDir name: ‘localRepo’, dirs:’/some/path/to/repo’

So I naively tried using flatDir to resolve a local maven repo, which of course didn’t work, since it’s not defined with the maven artifact resolution pattern. In order for that to work, you have to define your own resolver for now. I just submitted a patch to add a mavenLocal() resolver. Should make it to HEAD shortly.

So, for now, you can do

  private org.apache.ivy.plugins.resolver.DependencyResolver createLocalMavenResolver() {
    def localMavenResolver = new FileSystemResolver();
    localMavenResolver.local = true = "localMavenResolver"
    localMavenResolver.m2compatible = true
    localMavenResolver.addArtifactPattern "${userHome}/.m2/repository/[organisation]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
    def ivySettings = new IvySettings()
    localMavenResolver.settings = ivySettings
    return localMavenResolver

Then use this method as…

resolver createLocalMavenResolver()

resolver method basically allows you to specify your own Ivy resolver. But that seems like too much work for something as common as local maven repo, especially since anyone who’s going to use maven dependency artifacts, probably will install some locally.

So once the patch makes it in, you can just uncomment…


By default this resolver will resolve dependencies in home_dir/.m2/repository, but you can also specify your own path to the repository by just passing it as an argument…


Grails 1.2 is beginning to look very exciting.

Sep 09

Grails multi-control property editor implementation

Data binding using current frameworks, Spring, Grails, etc… usually provide a way to marshal/unmarshal input control data into data types. The frameworks usually transparently handle the most common datatypes and allow you to configure/implement others. That process is pretty straightforward and in many cases trivial. When using Spring MVC, for example, one would extend java.beans.PropertyEditorSupport and implement the setAsText and maybe getAsText methods.

I think this handles a large portion of data bindings in web applications, but there wasn’t (at least in frameworks I worked with), a straightforward/reusable way of binding multiple html fields to one data type. I’ve always either had to roll my own custom solution and/or rely on a command (transfer) objects to have a one to one representation of form fields, which I would then bind to the domain object inside a controller action. Some use cases can really benefit from command objects and its decoupling from the domain, but I try to bind directly to domain objects as much as I can, reducing the amount of noise that transfer objects generate. Another solution which I’ve personally never implemented because I thought it was too ugly and leaked too much domain binding implementation into the view layer, was to use a hidden field and then format the multi-field controls into a single text value representation during a submit event, though allowing you to still have a one to one binding between the hidden control and the domain object field.

Today I discovered Grails StructuredPropertyEditor, and after figuring out how to implement it, I was on my way to reducing a bunch of binding boilerplate. This solution is not documented, as many other grails related intricacies, though it does seem like a stable/supported API. After digging through the source code, I figured it out and wanted to share it. So here it is…

I have a form which collects date and time information. The date uses a custom datepicker control and the time uses a custom time control. So two controls, that I need to marshal into one DateTime field in my domain class.

We start off by implementing a custom property editor, which extends PropertyEditorSupport and implements a grails specific StructuredPropertyEditor interface. I decided to use an excellent DateTime implementation class which comes with Joda Time library to store the date/time information. You can easily use any other type of your liking, including the java.lang.Date class.

  public class DateTimePropertyEditor extends PropertyEditorSupport implements StructuredPropertyEditor {

    DateTimeFormatter dateTimeFormat;

    public DateTimePropertyEditor(String format) {
      this.dateTimeFormat = DateTimeFormat.forPattern(format);

    public List getRequiredFields() {
      List requiredFields = new ArrayList();
      return requiredFields;

    public List getOptionalFields() {
      List optionalFields = new ArrayList();
      return optionalFields;

    public Object assemble(Class type, Map fieldValues) throws IllegalArgumentException {
      if (!fieldValues.containsKey("date")) {
        throw new IllegalArgumentException("Can't populate a date without a year");

      String date = (String) fieldValues.get("date");

      try {
        if (StringUtils.isBlank(date)) {
          throw new IllegalArgumentException("Can't populate date/time without a date");
        String time = (String) fieldValues.get("time");
        if (StringUtils.isBlank(time)) time = "00:00 AM";
        String dateTime = date + " " + time;

        return dateTimeFormat.parseDateTime(dateTime);
      catch (Exception nfe) {
        throw new IllegalArgumentException("Unable to parse structured DateTime from request for date.");


Now that we have the property editor defined, we should create a registrar to register it with the application.

  public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

      public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(DateTime.class, new DateTimePropertyEditor("MM/dd/yyyy hh:mm a"));

Now that we have both the property editor and its registrar, we have to declare the registrar bean in the spring beans resources file /grails-app/conf/spring/resources.groovy

  beans = {

    // .... other beans ....

That’s it, we’re done. The only thing left to do is actually create the html controls. There are a few conventions that must be followed in order for the StructuredPropertyEditor to grab the right fields.

  1. You must have a hidden field that’s there pretty much to declare the name of the field you’re binding to and also to state that it’s a ‘struct’ field, which means it’s a structured control made up of various other controls.
  2. The second rule, is that the names of the sub-fields that you are using in StructuredPropertyEditor, in our case ‘date’ and ‘time’, have to be prepended with the field name. So if the field name is ‘myField’, the sub-fields would be prepended with ‘myField_’. In our case, the html inputs should be named ‘myField_date’ and ‘myField_time’.

Here is a GSP snippet…

  <g:hiddenField name="startTime" value="struct" />
  <g:textField name="startTime_date"/>
  <g:textField name="startTime_time"/>

Notice how the field we’re binding is ‘startTime’ and the sub-fields that make up the whole, are ‘startTime_date’ and ‘startTime_time’ linked to ‘date’ and ‘time’ fields used in the assembly of the final field.

Now, all you have to do in the controller, is bind as you usually would, in my case…

bindData(domainObj, params)

That’s it, quick and simple and you have reusable marshaling of multi-control data types.

Jul 09

Choosing a web development framework/toolkit

I’m sure I’m not the only lunatic that spends many hours well into the night thinking about web frameworks, but then again, maybe I am. This is all exacerbated by the fact that I work for startups, so requirements are much different that say someone working for an established corporation that has various standards and practices in place. I left the corporate world 4 years ago and haven’t looked back. I love the dynamics of the startup environments and my personality fits very well with its culture and pace.

So some of the questions I battle with are, which framework should I use for this new project, or am I using the right framework for my current project? Is the framework and language it’s written in supports writing applications in a powerful, flexible, fast, scalable way? A lot of the criteria I just listed are not as much framework as design and architecture of your applications and infrastructure, but frameworks can make it easier or harder to achieve such a desirable architecture.

The issue is not as pronounced for other non-web applications, mostly due to the fact that most Turing-complete languages are capable of performing the same job as any other, the only question is the programmers preference, proficiency, and the availability of some framework/abstraction to make your life a bit easier. In some languages, writing these abstractions is a breeze or in some instances they are not explicitly available because some or lost of boilerplate is reduced through various language idioms.

But web development is so complex these days, that simple abstractions are not enough. Anyone that thinks either hasn’t created a serious web application or posses some information that I’d be willing to pay to have:-) Sure, with the knowledge of HTTP and some gateway protocol, whether its CGI, Java Servlets, WSGI, etc…, one can do almost anything that’s possible on the web, but that’s a pretty bad criteria to have in the age of ever so complex applications/features. One doesn’t want to rewrite something from scratch. Authentications/Authorization for example, although many applications have a pretty custom authn/authz scheme, 80%+ of what’s needed is boilerplate that I nor any experienced application developer cares to reinvent. I’d rather be doing more challenging things, not sure about you.

So many frameworks conceal some amount of boilerplate from the developer through abstractions. Right now, there seems to be two kinds of web framework camp schools of thought:

  1. I’ve done this many times before, trust me, you don’t need anything else. I’ve extracted this, not made this up. The 20 applications that I’ve developed with this framework and extracted all of its generic concepts is all you’ll ever need. Here is my convention down your throat. You think you need XYZ? No dumb ass, you just have no clue and your brain has all the baggage of a previous framework. Come on, open your mind, do you really need XYZ? You do? Well #$%@ you, go use someone else’s framework.

  2. We don’t know what the developer wants, he might want bar or foo or barfoo or foobar or foobarbarfoobarbar, or what ever they wake up and desire that day. We’ll come up with abstractions that can be extended by other abstractions. But wait, what if the developer wants to extend those other abstractions, oh, well we must allow them to do so, so here are some more abstractions. Before you get started, here are 50 different things you must do, with xml or code bootstrapping.

The second camps sound nicer, more sane in some instances, and you’re overwhelmed with the flexibility that makes you believe that nothing is impossible. But that’s further from the truth.

I’ve mostly used the #2 frameworks, as with many years of development, I’ve developed quite a convention of my own. No, it’s not that I’m not open minded old timer that is scared of change, actually I love change so much that I find spending many unproductive nights hacking something in a completely different language/frameworks, exploring the ever so unpopular technologies, etc… But my conventions have grown empirically, though I’m not easily swayed to go back 10 years ago when I had no experience and relearn from the same mistakes I’ve already made to just come to most likely the same conclusions. People do this all the time, in every field and I don’t have grant money nor a big corporation blindly investing in my useless use of time.

I’m pretty big on DDD and OO and all the abstractions that come with it and I need a framework that allows me to do so, without forcing me to mix relational and OO concepts by forcing me to use a weak ORM, or no ORM, or an ORM that they choose for me. I also am more than capable of deciding whether I need a Repository data layer and not just a plain simple DAO layer. I know what I’m talking about, at least I think I do, so I don’t need any 20 year old telling me that using recordsets that masquerade as domain objects is just fine. Maybe for you, but I have a different opinion. It’s possible that your todo list will do just fine, but not my software that might start off with 10 domain objects concepts and grow larger as functionality is added. Ok, enough with my discontent with the 20 year old programmers, there are many of them that are brilliant, they’ll just have to learn (or not) as the time goes on.

Now with all that’s mentioned above, I also am very aware of over-engineering and aren’t we all so good at it. So, when I’m not in the mood to over-engineer something, I’d like a simple way of accomplishing a task. Without all the enterprise application pattern abstractions, etc… Sometimes I just want to create a quick prototype, start off simple, then grow it if needed into a production ready piece of software. Eventually through constant refactoring, I’ll add the necessary patterns/abstractions as my requirements grow or change.

With all the above rant, I’m yet to find a framework that can do this. Rails maybe comes close, only one problem. ActiveRecord is very limited and sucks. Besides the mapping limitations, you also bind your domain objects to the relational model and are constrained into modeling your domain in a unnatural way. This might be fine if you’re building a small app in its isolation, but it’s a huge technical debt if you’re building a service model on top of a persistence model that might be used/reused by other domains or services, etc… I want to have a consistent, coherent domain which is available as a service to other services, like webapps, background processes, etc… Good luck doing this with Rails. It is true that when I’m first starting my app this might not be a requirement, but like any other startup company, we have a vision and if that vision is realized, we’d rather not have that much technical debt to pay before we can move forward.

So after all the rant above, what is it that I want? Here is a list. It’s not comprehensive, just things I can think of at this time. I’ll update it as I think of anything else.

  1. Support for MVC (most frameworks have pretty decent support for that now)
  2. Extensible MVC (need to be able to extend the way controllers and views operate. Some frameworks do it by convention and limit you to a set of popular conventions.)
  3. Allows you to build your domain in isolation. (I want my domain model to be completely decoupled from any web technologies, persistence, etc… Just a plain OO domain model)
  4. Gives you very flexible persistence options. (I might decide to use a fully featured ORM (ActiveRecord is not fully featured), or I might want to use SQL, or heck, I might want to do both for efficiency or to scratch a morning itch, who cares about the reason, please let me choose. Oh, and one more thing, what if I don’t want to use a SQL database at all? I want to use a native XML store or better yet a key/value store. Even if it’s just to piss someone off, I want to do this and one should be able to accomplish that pretty easily. I’m not asking for a mapper for these stores, simply just don’t make your framework bound to some relational store though making the work of turning this dependency off a 5 hour chore.)
  5. Supports AJAX (I should be able to easily render JSON or XML views, without much plumbing or lots of mappings and annotations. The authentications and forms support should also expose some form of ajax compliant interfaces, so that forms and authentication can be done using ajax if I choose so. Be able to easily parse submitted data into some data structure and validate/synchronize it with the domain model.)
  6. Bindings (All frameworks have some sort of bindings. Some of them are limiting. I don’t want to create command objects to just simply bind the data and than synch with my domain model. If I have domain object graph(s), I should be able to bind it in the view layer. Bindings should be customizable. In Spring MVC for example, you can only bind one input control to a field or set of fields in the command object, but what if I want to bind 3 input fields that collectively represent one field in the domain object, I’m out of luck, unless I use javascript to first serialize those input fields into one field. That really sucks.)
  7. Support RESTful, stateless, and other web concepts in a straightforward way. (I want to be able to configure every part of HTTP and the web and make the application work, look, interact in my way that’s compatible with the web, not your way. Some component based frameworks make that harder that it should be, like the fact that they are inherently stateful by default. Some make it hard to support RESTful or custom URI schemes, because they transfer state through URL rewriting. All of these problems don’t exist in some frameworks, like Rails, Spring MVC, Grails, etc…, so I know it’s possible.)
  8. Validations (Most have fully fledged validation support, but I can’t say that it can’t be made a bit easier. I do like Spring’s flexible validation support.)
  9. Forms (This is a big one. Can you provide a flexible way of creating forms and layouts. I mean seriously, we’re developing forms today the same way we’ve developed forms 15 years ago. Every other aspect of development has moved on, but we’re still doing bullshit html form controls. XForms is a way out, but no browser support and pretty hard to integrate support from vendors like Orbeon and Chiba makes the standard useless. Can we either embrace it or come up with something else. Am I the only one that gets an anxiety attack every time I think about creating yet another interactive form that doesn’t do anything much differently than the form I created 4 months ago for a different project, though I either have to copy and paste all the cruft or start from the absolute scratch. Wow, that’s sad IMO.)
  10. Scalability. I know this one again is not up to the framework, but as I mentioned before, the framework can make it easier or harder to achieve. For example, inherently stateful frameworks that require either session affinity or replication of session state, make it very hard to horizontally scale. Yes, I know you can scale with replications tools available out there, but any synchronous replications is not linearly scalable. So any such frameworks makes it harder. There are many other criteria that can make a framework more scalable than others, but in general, statelessness, stability, and speed makes it viable for faster scalability tunes.)

Ok, that’s it for now, I need to vent before my brain allows me to think of other things I’ve encountered of my never ending framework journey. I’d really love for someone to just say, hey you’re wrong, there is such a tool(s), here it is. I’d be eternally grateful. Many will say that it’s useless to complain, if I see a need, help create the framework or functionality that you think is needed. I wish I had more time, until then, I’ll continue to grunt and develop my own inner frameworks to make things easier. One day, if I have time, maybe I’ll devote some time into making some existing open source framework better. I’ve had more time years ago and contributed to quite a few open source projects that I’m truly starting to miss it now. I still occasionally submit a patch or two to a framework I’m working on after fixing an issue or adding some feature, but at times I’m in such a hurry to move on to the next task, I don’t have the time to package or generalize it enough to make it useful for everyone else.

Right now, I’m working with Grails after starting a project in Spring MVC and not being able to deliver functionality as quickly as I wanted. I’ll have to live with some issues I found with Grails when I was using it about 4 months ago, like the fact that you must use hibernate or gorm, crappy groovy stack traces, etc… Hey, there is always something one might not like, but I really like Grails and am hoping that now that it’s in the hands of SpringSource, they’ll spruce up the documentation to be more like Spring’s awesome documentation and clean it up a bit.

Update: I wanted to reiterate a bit on the Grails in regards to isolated domain model. Grails does allow you to create and isolate your domain model and its persistence, unfortunately you have to twist it’s arm if it’s anything outside of GORM. You don’t have to add classes to domain directory, but wtf is it there for? Also, it would be nice if the grails team provided a way to specify which classes in the domain directory are persistent or not. I mean, a domain model != persistent entities. So transient classes and other domain artifacts should also be grouped together. Putting them into src/groovy sucks personally, because I have to navigate two directories now to look at what’s supposed to be a coherent domain model.

Jul 09

Groovy SQL Builder

I’m currently working on a project which requires some pretty heavy SQL to OO stuff. JPA of course can’t handle the full load, so my Repository pattern abstractions abstract away JPA as well as raw JDBC stuff. This architectures actually works out pretty well, except when it comes time to build queries. Java’s string interpolation/comprehension is not present and even if it was there, who wants to build queries using strings. I used to do it years ago, now that I had to come back to doing it (for non-trivial large queries), I definitely think it’s a big design smell. Even abstracting it away behind some sort of a sql variant, it’s just not as nice as I’m used to programming with DDD.

I also had to question simple sql variant implementation which I had. SQLVariant is nice when you know that you’ll always have only one query per operation (in each db you have to support) and building queries is pretty straightforward, not requiring a lot of logic.

So I added this concept of a SQLExecutor, which returned anonymous inner classes that represented query or update operations interface. The client can then execute this (psudo-closure) to perform the operation. And all query stuff is complete abstracted away in the returned closure’s execution logic. Worked great, but I’m still stuck with building queries. Java just sucks when it comes to this, ah, but what about groovy?

So I realized that I can use java and groovy interchangeably in the absolute same code base. Both are compiled into JVM bytecode and IntelliJ supports both file types rather nicely, allowing for cross compilation and all the other IDE goodies.

So why not build a sql builder in groovy? Groovy’s metaprogramming facilities allow for that level of dynamic logic way more than java. So in the last 2 hours I put together something very simple, which currently allows me to at least support my query building tasks in a cleaner fashion. Groovy’s FactoryBuilderSupport is a rather nice abstraction that allows to build builder DSLs on top of. Mind, this is 2 hours of work, many features I need (besides inserts and updates as well) are not yet there. I need to add column validation (to not allow to select or have included in the predicates columns and/or tables that were not defined as a part of the query or joins). There are numerous other things I’ll add with time, but thought someone might be interested in at least how easy it is to build a simple groovy DSL.

If I ever get it to the point of where I feel it will be helpful to anyone other than me, I’ll release it in some near future. Right now, I’m just glad that I can write simple DSLs and get rid of the SQL building crud.

Here is a small use case for a select statement (that’s all I can build at this point).

  void buildSelectSql() {
    def sql = new SqlBuilder();
    Select select = ("table1") {
      join("table2", type: "INNER") {
        using(table1: "col1", table2: "col1")
      join("table3", type: "OUTER") {
        using(table1: "col2", table2: "col2")
        using(table1: "col3", table2: "col3")
      where("table1.col1 = 'test'")
      groupBy(table1: "col1", table2: "col1")
      orderBy(table1: "col1", table2: "col1")
    assertNotNull select, "Select object should not be null"
    println "SELECT: " + select.getSql()
    assertNotNull select.getSql(), "Generated SQL SELECT expression should not be null"
    assertFalse select.getSql().trim() == "", "Generated SQL SELECT expression should not be empty"

Here is the code:

 * SqlBuilder is a DSL to build portable SQL using groovy internal DSL facilities.  It allows you to specify
 * SQL queries using groovy expressions vs. string concatenation/interpolation as it's usually done.
 * @author Ilya Sterin
public class SqlBuilder extends FactoryBuilderSupport {

  // Register expression factories
    registerFactory('select', new SelectFactory())
    registerFactory('join', new JoinFactory())
    registerFactory('using', new UsingFactory())
    registerFactory('where', new WhereFactory())
    registerFactory('groupBy', new GroupAndOrderFactory())
    registerFactory('orderBy', new GroupAndOrderFactory())

 * Select class encapsulates the select clause node of the SQL query
 * and acts as a parent node to all select queries.
private class Select {

  def table,        // Name of the main select table
      tables  = [], // All tables join tables and select table
      joins   = [], // Collection of all joins
      where,        // Where clause
      groupBy = [], // Collection of group by columns
      orderBy = []  // Collection of order by columns

   * Builds and returns the SQL query based on the DSL expressions
  String getSql() {
    def sql = "SELECT * FROM $table"
    joins.each {Join join ->
      sql += " ${join.type} JOIN ${join.table} ON"
      join.using.eachWithIndex {Using using, idx ->
        if (idx > 0) sql += " AND"
        sql += " ${using.lhs} ${using.op} ${using.rhs}"
    where.eachWithIndex {Where where, i ->
      if (i == 0) sql += " WHERE ";
      sql += "${where.clause}"
    if (groupBy) sql += " GROUP BY ${groupBy.join(', ')}";
    if (orderBy) sql += " ORDER BY ${orderBy.join(', ')}";
    return sql


///////// Private classes to support the builder functionality /////////////

private class Join {
  def table
  def type = "INNER"
  def using = []

private class Using {
  def lhs, rhs, op = "="

  def methodMissing(String name, args) {
    println "Looking for ${name}"

private class Where {
  def clause

///////// Factories that construct the appropriate objects based on the DSL expressions //////////////

private class SelectFactory extends AbstractFactory {

  public Object newInstance(FactoryBuilderSupport factoryBuilderSupport, name, value, Map map) {
    return new Select(table: value, tables: [value])

  public void setChild(FactoryBuilderSupport factoryBuilderSupport, Object parent, Object child) {
    println "Child ${child}"
    if (child instanceof Join) {
      println "Adding a join"
      parent.joins << child
    if (child instanceof Where) {
      println "Adding a where"
      parent.where = child

private class JoinFactory extends AbstractFactory {

  public Object newInstance(FactoryBuilderSupport factoryBuilderSupport, name, value, Map map) {
    Join join = new Join(table: value)
    return join

  public void setChild(FactoryBuilderSupport factoryBuilderSupport, Object parent, Object child) {
    super.setChild(factoryBuilderSupport, parent, child)
    if (child instanceof Using) {
      parent.using << child

  public void setParent(FactoryBuilderSupport factoryBuilderSupport, Object parent, Object child) {
    super.setParent(factoryBuilderSupport, parent, child);
    parent.tables << child.table

private class UsingFactory extends AbstractFactory {

  public Object newInstance(FactoryBuilderSupport factoryBuilderSupport, name, op, Map map) {
    Using using = new Using()
    if (op) using.op = op
    map.each {k, v ->
      if (!using.lhs) {
        using.lhs = "${k}.${v}"
      else if (!using.rhs) {
        using.rhs = "${k}.${v}"
    return using

  public boolean onHandleNodeAttributes(FactoryBuilderSupport factoryBuilderSupport, Object o, Map map) {
    return true;

  public boolean isLeaf() {
    return true;

private class WhereFactory extends AbstractFactory {

  public Object newInstance(FactoryBuilderSupport factoryBuilderSupport, name, value, Map map) {
    return new Where(clause: value)

  public boolean isLeaf() {
    return true;

private class GroupAndOrderFactory extends AbstractFactory {

  public Object newInstance(FactoryBuilderSupport factoryBuilderSupport, name, value, Map map) {
    def fqCols = [];
    map.each {k, v ->
      fqCols << "${k}.${v}"
    return [name: name, cols: fqCols];

  public void setParent(FactoryBuilderSupport factoryBuilderSupport, Object parent, Object child) {
    super.setParent(factoryBuilderSupport, parent, child);
    if ( == "groupBy") {
      parent.groupBy += child.cols
    if ( == "orderBy") {
      parent.orderBy += child.cols

  public boolean onHandleNodeAttributes(FactoryBuilderSupport factoryBuilderSupport, Object o, Map map) {
    return true;

  public boolean isLeaf() {
    return true;