Monthly Archive for July, 2008

CF Groovy w/ Hibernate Sample App

I want to put together a little sample app leveraging CF Groovy and it's Hibernate integration, but I don't know what. From a high level, the architecture will look like this:

  • CFML for the view layer (the HTML templates)
  • CFML for the web controller (probably FB3Lite)
  • CFML and Groovy for the service layer (ColdSpring-managed CFC's with Groovy delegation where appropriate)
  • Groovy w/ Hibernate for the data layer

The question is what the application should do. The default choice of a simple blog engine is, well, boring. I considered implementing the BlogCFC API as a drop-in replacement for BlogCFC backed by Hibernate, but that means mapping the legacy schema, which I don't really want to get into for a simple demo.

My next choice is a simple survey application, since that at least has the potential to be real-world useful. It's also sufficiently simple and would provide appropriate illustration of the concepts I need to demo. The data model for survey construction is simple, but it gets a bit nastier with response storage, and I'd like to avoid too much nasty.

I've implemented a basic timeclock as a sample app a few times (CFML, Spring+Hibernate, Grails) as well, but there's a lot of "application" in there, compared to the amount of persistence, which is what I want to be highlighting.

So, my all-knowing readers, what simple app do you want me to implement? Preferably something that will be useful to people, either as it is, or as a starting point for building a richer version of what I produce. I've just about got the Hibernate APIs nailed down, but I've got a couple more hours on that task.  I'm thinking that Wednesday night I'll pick something and start coding, so speak up (in the comments) with what you want to see.

Fun with Classloading in Java

With my CF Groovy project, I've been doing a lot of Java coding of late. It's all been written in CFML, but it's mostly Java code in CFML syntax. As an aside, doing that sucks. CFML is horrible for writing anything more than the simplest Java code. But on to the topic at hand….

To this point in my career, basically all of the Java code I've written has been application code. Most of the CFML, JavaScript, and ActionScript I write is also application code, but I've contributed significantly to Fusebox and built a number of micro-frameworks in all three languages. However, none of that touches on the stuff I've done in the past couple weeks. The primary source of my issues getting Groovy and Hibernate to play together was classloading.

Unlike Grails (GORM, really), any of the various examples on the web, and I'm guessing Joe Rinehart's Hiberailooving project, three of the inviolate framework objectives were zero dependency on an IDE beyond text editing, no manual compilation, and no container restarts. Obviously, Hibernate provides a set of IDE tooling that can be brought to bear, but I'm talking about just the CF integration portion. I want to be productive with emacs and a web browser.

This presented a number of issues with classloading, because Groovy can only be loaded by the GroovyClassLoader (and subclasses). Basically this forced my hand to using compiled Groovy code, and ensuring it and Hibernate are loaded by the same ClassLoader. No GroovyClassLoader at all.

Now all that's well and good, but you have to be a bit careful, because two of the goals where no manual compilation and no container restarts. Doing compilation from CF is fairly simple (instantiate FileSystemCompiler and call 'main' with the right args), though again, getting all the right stuff on the classpath in the right order proved a nightmare. This is further complicated by the while JEE classloader situation, which isn't straightforward at all.

The details of this intricate dance completely escaped me for a week and a half. Then one night, while lying in bed, it all clicked together (thank you, Heather, for going to England). The solutions seem fairly obvious now, but they took a lot of fussing and fighting to deduce. I'd never even instantiated a ClassLoader before, aside from a couple one-off URLClassLoaders in CFML to lazy-load some JARs. Now I've got stacks of ClassLoaders, in some places two or three deep.

After my initial post-epiphany implementation was complete, I realized I can do some streamlining, but that's for after the release. I think I can even remove the need to drop the Groovy JAR in your /WEB-INF/lib folder, without adding any code complexity or runtime overhead, which would a nice bonus for ease of deployment. I.e., unzip the engine, write an entity, save it to the DB. No JARs, no restart the container, nothing.

It's been a very interesting (and pleasurable) experience, since it's so different from my day job of banging out boring little presentation apps all day. I've learned a lot, and even just the past few days of thinking about how other Java apps/frameworks work, I've realized how applicable that knowledge really is.

CF Groovy Redux

I just got through significantly revamping CF Groovy so that it's CFC based, instead of all in the custom tags.  The custom tags remain, but now you can create and manage a CF Groovy runtime instance manually, rather than letting the tags do it for you.  This will greatly assist in production performance as the tag-based version recreated everything each request.  It's also a prerequisite for Hibernate support, as Hibernate spinup is non-trivial and needs to be avoided unless needed, even in development.

These changes are still in the Hibernate branch in Subversion, not the main trunk.  I don't plan on moving the new code back to the trunk until the Hibernate integration is complete.

CF Groovy Takes a Nap

After close to two weeks of struggling, I finally managed to deploy pure source to a CFML runtime (Railo, in this case), and get Groovy entities in and out of the database with Hibernate.  No compliation, no IDE, no development-mode server, just my Groovy source along with a hacked up CF Groovy.  This is very exciting for me, because while Groovy is cool and all, CF's dynamic nature has become a must have.

I don't have source to download yet, just a horribly hacky proof of concept, but here's what the user of the "framework" does.  First, create your entity:

package com.barneyb
import javax.persistence.*

@Entity
class Person {

  @Id
  @GeneratedValue
  Long id
  Long version
  String name
  Date dob

  def getAgeInSeconds() {
    (new Date().getTime() - dob.getTime()) / 1000
  }

  def getAgeInDays() {
    ageInSeconds / 86400
  }

  def getAgeInYears() {
    ageInDays / 365.249
  }

  String toString() {
    "$name is $ageInYears years ($ageInDays days) old"
  }

}

That's the same class as my initial CF Groovy demo used, except with the of JPA annotations added.  Because I'm binding to Hibernate, you can use any Hibernate-supported annotations, but I opted to stick with vanilla JPA.  Now we need our hibernate.cfg.xml, which is totally stock:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

  <session-factory>

    <property name="current_session_context_class">thread</property>
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="show_sql">true</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbname</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.hbm2ddl.auto">update</property>

    <mapping class="com.barneyb.Person" />

  </session-factory>

</hibernate-configuration>

You could also map your classes manually with XML, if you wanted, but for the sake of simplicitly, I've done it all with annotations.  You'll also notice the database connection information embedded directly in the file. This is far from ideal.  I'm hoping to extract it from a CFML DSN, but that might only be possible on Adobe ColdFusion (via the Admin API).  The last thing is the test script:

<g:script>
  import java.text.SimpleDateFormat

  import org.hibernate.*
  import org.hibernate.cfg.*

  import com.barneyb.Person

  sdf = new java.text.SimpleDateFormat("yyy/MM/dd")
  sdf.lenient = true

  def sf = new AnnotationConfiguration()
      .configure().buildSessionFactory()
  def sess = sf.openSession()
  def tx  = sess.beginTransaction()
  sess.createQuery("delete Person").executeUpdate()
  sess.save(new Person(
    name: attributes.name ?: "Barney",
    dob: sdf.parse(attributes.dob ?: "1980/06/10")
  ))
  tx.commit()
  sess.close()
  sf.close()
</g:script>

No need to compile anything, no need to drop JARs all over your server, nothing.  Write, refresh, persist.  That includes adding new entities, new properties to existing entities, etc.

It's not ready for public consumption at the moment, but that's my top "free time" priority.  For the incredibly impatient, there's a branch in my SVN repository with the current source.  Don't expect anything pretty.  ;)