October 2009

Grails hip tip: exporting schema DDLs

If you utilize Grails out-of-the-box and don’t change any of the connection profiles, your hip application will be bound to an in memory instance of HSQLDB — this is fine and dandy for developmental purposes, but oftentimes, you’ll want to run Grails on top of a more permanent data store (keep in mind that you can operate in such a manner with HSQLDB’s file based persistence). For example, if it’s your bag, you might want to eventually deploy to an instance of MySQL, once your data model stabilizes somewhat — in that case, you’ll have to create a database in your MySQL instance.

In previous versions of Grails, this was challenging; however, in more recent versions, you can quickly understand the underlying schema definition via the schema-export command. What’s more, with this command, you can create a new instance of a schema in your target database environment provided you take care to set the proper Hibernate dialect.

The schema-export command works quite copacetically; indeed, it’ll generate a valid DDL file for HSQLDB — that is, even if you change your DataSource.groovy file to point to MySQL, the DDL file will still be specific to HSQLDB, which, of course, can cause issues with MySQL. For instance, the SQL DDL

id bigint generated by default as identity (start with 1)

isn’t valid within MySQL; in fact, the same statement in MySQL parlance would be:

id bigint not null auto_increment

Thus, to force the schema-export command to generate a dialect (i.e. specific database DDL), you must set the dialect property inside the top datasource section of your DataSource.groovy file like so:

dialect=org.hibernate.dialect.MySQLDialect.class

In the case above, I’ve forced the dialect to be specific to MySQL; accordingly, when I execute the schema-export command (i.e. %>grails schema-export) I’ll have a DDL generated that is valid for MySQL (as opposed to HSQLDB). Of course, you can do the same for Oracle, DB2, etc. Can you dig it, man?

Anonymous classes are Groovy’s bag, once more

As I elaborated previously, Groovy

does not formally support the creation of anonymous inner classes.

Yet, as I demonstrated, you can coerce a hip Map into an interface type rather easily. Map coercion, however, isn’t the only way to mimic an anonymous class in Groovy. You can also coerce a closure into an interface type. This is easiest when the method you wish to implement only has one method.

For example, imagine a simple interface, defined in Java no less, called Filterable:

public interface Filterable {
 boolean filter(String value);
}

One way to anonymously implement this type is by defining a closure that implements your desired behavior. Inside the closure, you code the intended behavior of the interface method (like filter, in my case) and then, after the body of the closure, you cast the closure to the interface type.

For example, as the easyb story demonstrates below, I can implement the Filterable interface, leverage it later and even prove that the resulting variable is of type Filterable.

scenario "a closure in Groovy can act as an anonymous class using the 'as' keyword",{

 given "a closure cast via 'as' to an interface with a single method",{
  palindrome = {
    return (it.reverse() == it)
  } as Filterable
 }

 then "the resulting object behaves like the implemented interface", {
  palindrome.filter("kayak").shouldBe true
  palindrome.filter("Andrew").shouldBe false
 }

 and "the object's type is the implemented interface", {
  (palindrome instanceof Filterable).shouldBe true
 }
}

In the case of casting closures, as opposed to Map coercion, it becomes less readable if the implementing interface has more than one method as Groovy, under the covers, invokes the closure for each method on the interface. In that case, Map coercion is much more read-able, baby!

Groovy hip tip: to use or not to use setters and getters

In Groovy, if you define a hip object with properties, you can access them directly; that is, you don’t have to define the bogue old-style setters and getters that we were all taught to do back in the day with Java. For example, imagine a simple object defined in Groovy like so:

class Loan {
 def balance
 def term
 def rate
}

If you’d like to directly set the value of balance, for example, you could write

def loan = new Loan()
loan.balance = 30000

Note how the property was accessed directly as if it were public, but in fact, it’s private as the following copacetic test demonstrates:

import java.lang.reflect.Modifier
import groovy.util.GroovyTestCase

class LoanTest extends GroovyTestCase{
 void testLoanBalanceModifier(){
  def loan = new Loan()
  loan.balance = 30000
  assertEquals(30000, loan.balance)

  def field = Loan.class.getDeclaredField("balance")
  assertEquals(true, Modifier.isPrivate(field.modifiers))
 }
}

What’s more, even if you do define a setter, you don’t actually have to call it — Groovy will do that for you. For example, I can add the following setter method to the Loan object like so:

class Loan {
 def balance
 def term
 def rate

 void setRate(rate){
  if(rate > 0.99){
   this.rate = rate/100
  }else{
   this.rate = rate
  }
 }
}

And the following tests prove that under the covers, Groovy leveraged the setter properly, even though I don’t actually call the setter directly:

import groovy.util.GroovyTestCase

class AnotherLoanTest extends GroovyTestCase{
 void testLoanRate(){
  def loan = new Loan()
  loan.rate = 3
  assertEquals(0.03, loan.rate)
 }

 void testLoanRateAgain(){
  def loan = new Loan()
  loan.rate = 0.03
  assertEquals(0.03, loan.rate)
 }
}

This handy no-setter (or no-getter) syntax also works with plain old Java objects; that is, if you have a Java object that has private properties and setters and getters for accessing them, you can still directly access them Groovy-style. For instance, here is the same Loan object defined in Java:

import java.math.BigDecimal;

public class Loan {
 private BigDecimal balance;
 private int term;
 private float rate;

 public BigDecimal getBalance() {
  return balance;
 }
 public void setBalance(BigDecimal balance) {
  this.balance = balance;
 }
 //...all other setters and getters left out of example
}

As the below test shows, when using this Java object in Groovy, you can omit invoking setBalance for example:

void testLoan(){
 def loan = new org.disco.Loan() //java object
 loan.balance = 30000
 assertEquals(30000, loan.balance)
}

In fact, like before with the Groovy defined Loan, Groovy will invoke the getter or setter for that property defined in the Java class.

Clearly, the ability to seemingly access properties cuts down on the amount of code one must write; plus, the perceived safety and encapsulation that these methods provide is still present. Not bad, eh baby?

easyb now has an Eclipse plug-in!

The easyb team is excited to report that a hip Eclipse plug-in is in the works and an initial version is already available due to the copacetic work of both Darran White and Robert Hjertmann! The plug-in works with Eclipse 3.4 and 3.5 and currently supports running behaviors (both stories and scenarios) via the a run configuration. That is, when you right click on a story, for example, and then select the Run As option, you’ll have the choice to run the story via an easyb run configuration, which then pipes the output to the Eclipse console. Plus, the plug-in supports an Outline view, which essentially displays your behaviors without code — what’s more, you can click on an item in the outline and you’ll be taken to that spot in the actual behavior in your editor.

This is an evolving project, so please take a few moments to provide feedback either via the easyb mailing list or even by creating feature requests or defect reports via the easyb issue tracking system.

Installing the plug-in is simple too as the update site literally points to the latest version of the plug-in’s assets in our repository; consequently, the update and install URL is http://easyb.googlecode.com/svn/trunk/eclipse-plugins/org.easyb.eclipse.updatesite/ — of course as the plug-in evolves and official versions are released, the versioned plug-ins’ URLs will change (as the current URL points to the trunk of SVN).

So what are you Eclipse users waiting for? Install the easyb Eclipse plug-in and experience the fun of executable, yet readable, documentation, man.

You can borrow EC2 too

development 2.0The aspects of Development 2.0 aren’t really new– but they are each increasingly becoming a reality for businesses across the board. In essence, both open-source and borrowed infrastructures are hear to stay; thus, companies must start to ask themselves whether or not they’ll take advantage of them. For instance, by using Amazon’s EC2 an IT company can lower the overall cost of purchasing an infrastructure to run needed applications; plus deploy those applications quicker as the myriad cross cutting concerns associated with application deployment and management are already taken into account and thus provided for (and most likely in a superior manner).

This second installment of DeveloperWorks’ series “Java development 2.0″, dubbed “You can borrow EC2 too“, gives you a hands-on introduction to developing for and deploying on the Amazon Elastic Compute Cloud (EC2). Learn how EC2 differs from Google App Engine, and leverage an Eclipse plug-in and the concise Groovy language to get a simple Web application up and running quickly on EC2.

So what are you waiting for, man? Give “You can borrow EC2 too” a read and jump into the clouds with EC2!