Get Cooking with JRuby on Rails

Some of the companies that I interact claim that they will never switch to Ruby on Rails (or just plain ‘ol Ruby) for that matter. But with JRuby reaching 1.0 status (and currently on 1.0.2 with 1.1b1 already released) this changes the situation somewhat. Now it is possible to develop Rails apps and run it on your Java infrastructure that make use of native JDBC connections and a whole bunch more.

Pre-requisites

Since we want to run a Ruby on Rails app on a Java application server, we need to have a Java web container such as Tomcat, Jetty or Glassfish. In my case, I’ll be dropping the app into into a Glassfish domain. I guess that this should work just fine for Tomcat as well, but I have not verified this as yet.You also need a database and I will be using MySQL. If you are going to use another database, you need to make sure that the ActiveRecord-JDBC adapter has been developed for the DB. ActiveRecord is the ORM for Rails apps. Currently, there are ActiveRecord-JDBC adaptors for HypersonicSQL, Derby, MySQL and PostgreSQL. This is true for version 0.6 of ActiveRecord-JDBC. For other adapters, you will need to specify a proper JDBC URL in your application’s database configuration file, config/database.yml. This will make a lot more sense once you finish this exercise.All of the above (except or ActiveRecord, of course) should be stock standard goodies on any self-respecting Java development box. With this place, let’s get cooking.

Install JRuby

Download the JRuby bin distribution from the JRuby downloads page. At the time of writing this, 1.1b1 has been released. I am currently using the 1.02 release. Unzip/untar the file to somewhere convenient, add an environment variable JRUBY_HOME to point to the extracted directory, and add JRUBY_HOME/bin to your path.

	/> cd ~/tools	/> tar xzvf jruby-bin-1.02.tar.gz
	/> export JRUBY_HOME=~/tools/jruby-1.0.2
	/> export PATH=$PATH:$JRUBY_HOME/bin

You can verify your JRuby installation with:

	/> jruby -v
	ruby 1.8.5 (2007-11-01 rev 4810) [i386-jruby1.0.2]

 You will notice two versions being reported. The first tells us that the ruby implementation is version 1.8.5 and the second tells us that it is running on jruby 1.0.2 on i386 platform. If you are new to ruby, then you need to know that there are different implementations of ruby, with the definitive one called MRI (Matz’s Ruby Implementation – Matz is the original author of ruby). JRuby is an attempt at a complete port of MRI to Java, aiming to eliminate all dependencies on C libraries. This is one of the significant points about JRuby: it is pure Java.

Install RubyGems

The closest Java equivalent of RubyGems is Maven or Ant+Ivy. Gems is a library and dependency management tool for ruby. On a native ruby install, you would have to download and install RubyGems, but JRuby already has RubyGems rolled in. Take a peek at JRUBY_HOME/bin and you should see an executable file called gem. So, nothing more to do here. What the heck, let’s verify that RubyGem is working.

	/> jruby -S gem -v
	0.9.4

If $JRUBY_HOME/bin is first in your path, then you can try /> gem -v. The -S tells jruby to run the command that follows from $JRUBY_HOME.For the ruby folk, you should realize that JRuby has rolled in RubyGems version 0.9.4 which is as fresh as it comes.The closest Java equivalent of RubyGems that I can think of is perhaps Maven or ANT+Ivy. But RubyGems takes the prize hands-down for its absolute simplicity. Install rake and Rails below and see what I mean.

Install Rake

 Rake is a really good build tool for ruby (i.e a make for ruby, hence the goofy name). Once you start writing rake build scripts, you will wonder why one earth you thought ANT is nice. Anyway, let’s install rake.

	/> jruby -S gem install rake

Install Rails

Now that you’ve seen the goodness of RubyGems, install Rails and the ActiveRecord for JDBC.

	/> jruby -S gem install rails -v 1.2.6 -y --no-rdoc --no-ri
	/> jruby -S gem install activerecord-jdbcmysql-adapter --include-dependencies

We are deliberately installing Rails version 1.2.6. Rails 2.0.1 was released in early December 2007 and I have not taken 2.0.1 for a drive under jruby yet. So, we’ll stick to version 1.2.6 which is still great.

Get MySQL Ready

 We’re heading for the home straight with all this setup and configuration nonsense. Just a couple of things to do.

  • Copy the MySQL JDBC driver to $JRUBY_HOME/lib.
  • Create a MySQL database called testapp_development. Rails apps require three databases; one for development (suffixed _development), one for unit testing (suffixed _test and is wiped clean with every test run) and one for production (suffixed _production). For this exercise, we will just use the development database with full rights given to the MySQL user root with no pasword.

Create the Rails App

Now the fun starts! Finally!The next command will create a directory with the same name as your application. So, change to a directory that will contain your rails applications. In my case, I keep my applications in ~/projects/jruby.

	/> cd ~/projects/jruby
	/> jruby -S rails testapp

Now you should have a directory called testapp. Let’s see if our app works. Yes, in rails-land, the app can already be fired up!

	/> cd ~/projects/jruby/testapp
	/> jruby script/server

This fires up webrick, a built in http server with ruby support built in. Just point your browser to http://0.0.0.0:3000 and you should see the Rails happy page. Kill webrick by hitting CTRL+C.

Link up to your database

Edit the file config/database.yml and change it as follows. Note that the line socket: /tmp/mysql.sock must be removed.

	development:
  	  adapter: mysql
  	  database: testapp_development
  	  username: root
  	  password:

and

	production:
  	  adapter: mysql
  	  database: testapp_development
  	  username: root
  	  password:

 YML files are files that store configuration using YAML, which is a ” is a straightforward machine parsable data serialization format designed for human readability”.Now, let us inform the Rails app that we are using ActiveRecord-JDBC. Add the following to the file config/environment.rb just before the line Rails::Initializer.run do |config|.

  if RUBY_PLATFORM =~ /java/
    require 'rubygems'
    RAILS_CONNECTION_ADAPTERS = %w(jdbc)
  end

Create a table (the Rails way)

 Sure, we can write a simple SQL script to create the table we want, but for fun, let’s do it using some Rails sugar. You can keep your app running in webrick and still do the this. Just open up another command or shell, switch to your project directory and get going. This is one of the nicest bits of Rails – you can do most things without a restart of your application server.

	/> jruby script/generate migration AddGadgetsTable

This should have created a file db/migrate/001_add_gadgets_table.rb. Open this file and edit it as follows.

	class AddGadgetsTable < ActiveRecord::Migration
	   def self.up
	      create_table :gadgets do |table|
	         table.column :name,  :string, :null => false
	         table.column :color, :string, :null => false
	      end
	   end
	   def self.down
	      drop_table :gadgets
	   end
	end

After saving the file, run the following command to create the table. Actually, we’re migrating our existing database to version 001! Database refactoring is a definite goal of Rails. It may not be perfect, but it is certainly better than maintaining a bunch of SQL files.

	/> jruby -S rake db:migrate

 Even if you’ve never seen ruby before, the above is certainly readable and you can easily understand that we intend to create a table called gadgets with two columns name and color. Actually, there are more than these two columns. Have a look at the table structure and check that a primary key colum id has been added as well.

Generate Scaffolding to maintain the table

I know, I know, I know! Code generation for anything but the most trivial of code can be dramatic for newbies but real code takes a lot more effort. The point here is just to get some Rails code up and running so that we can deploy it in a Java application server. So, please bear with me.

	/> jruby script/generate scaffold gadget

Fire up webrick and visit the URL http://0.0.0.0:3000/gadgets. You should see a page with an empty list of gadgets and CRUD links.

Get ready to WAR

We need a few additional rake tasks to be able to build a WAR for our Rails application. The Goldspike plugin for Rails does just that. Let’s install the Goldspike plugin.

	/> jruby script/plugin install 
		svn://rubyforge.org/var/svn/jruby-extras/trunk/rails-integration/plugins/goldspike

All that’s required is to add the WAR dependency on the MySQL driver. What’s great about Goldspike is that we can declare Maven dependencies. Great combination: RubyGems for Ruby-land and Maven for JRuby-land! Open the file vendor/plugins/goldspike/lib/war_config.rb and add the following line to the list of # default java libraries block.

	add_java_library(maven_library ('mysql', 'mysql-connector-java', '5.0.5'))

Build the WAR

Now build the WAR using rake.

	/> jruby -S rake war:standalone:create

If you look in the root of your application directory, there should be a file testapp.war

Drop it into Glassfish

 Start your Glassfish domain, log in to the Glassfish admin console and click the Deploy Web Application link. Browse to the testapp directory and select the testapp.war file. If the app is not enabled, then select testapp, and click Enable.

See it in action

Point your browser to http://localhost:8080/testapp. You should see the Rails happy page, and http://localhost:8080/testapp/gadgets has the CRUD for our Gadget object.As easy as pie! And just as nice!

The optimistic concurrency gotcha

In my current project, I have a group of about 7 budding young developers none of whom have done any significant web development.  This includes hitching up to a database and using object relational mappers.  The one thing that always gets first-timers is stateless nature of the web.  And the first solution they come up with is session based statefulness which eventually leads to a scalability bottleneck.  The ripple effect of lack of state is that you need to have optimistic concurrency at the data access level.  Now most of us just assume that our OR Mapper will solve that for us.  And, yes, they do offer optimistic concurrency out of the box, be it with a version column or without.  But Mats Helander makes a strong point that optimistic concurrency in most (maybe all) OR Mappers actually kicks for really short durations (milliseconds).  In that case, you might as well be using good old fashioned database transactions.  Mats suggests that a way to solve the problem is to store original values in the view.  Check out Mats’ post and you’ll see why you should be storing, at the very least, your Hibernate version column/property on your view as well.

Not everything has to be Object Oriented

For some time now I have been wondering whether we have become completely obsessed with object oriented analysis and design.  Hence my step into the world of functional programming.  This led me first to Haskell and also Erlang. Interestingly, Niclas Nilsson has posted a thought provoking piece on InfoQ which asks whether Erlang is the next Java.  Also, check out the comment on Scala which is now on my radar as well. Maybe functional languages will be the language for Web 3.0 where semantic interoperability and semantic correctness will be prominent.

Reflections on the JCSE Agile and Architecture Talk

It was really good to be part of a very topical subject at the JCSE Architecture Forum last night.  While these discussion are so valuable, the things that surface can only be glossed over, largely because of time constraints.  I end up feeling a very satisfied and energised but a part of me feels a bit hollow.
So here are some of the things that surfaced at the Forum, and my narrow, unworldly opinion on each (i.e. I’m just trying to fill that hollow feeling).

When we talk about architecture, we need to define what we mean by architecture?

In my talk it was a very simple view of architecture which, thinking back, I should have disclosed very early.  I am now applying from Kent Beck who talks about mutually beneficial relationships.   So I think of architecture as the mutually beneficial relationship between two or more things.  So what is a thing?  It could be  lines code in a method, methods in a class, classes in namespace, namespaces in code base, binaries in an application server, application servers in a cluster, … see where I am going?  Architecture is about creating beneficial relationships, and the 5 things I discussed are based on this view.  If you don’t know anything about the things, then you cannot create beneficial relationships.  From an agile perspective, the beneficial relationship that you create should only be beneficial based on your knowledge right now.  Tomorrow your knowledge changes, so the relationship may not be as beneficial as yesterday.  Time to change.

Building infrastructural architecture independently of functional requirements…

I am not convinced of the benefit of this approach.  In my limited experience, every business need defines the constraints or needs of the infrastructural architecture.  I find it hard to find the point of departure, yet there is a school of thought that suggests that function is orthogonal to the architecture.  Perhaps I just don’t understand this.  However from an agile perspective, I want to release early and there are many constraints on infrastructure from the business (for example, administrative processes like procurement of hardware).  I like to understand what these are early on, reach agreement on what we can release at the earliest and design accordingly.  Perhaps the first release is on lightweight infrastructure and that means we “limit” scalability.  So, I don’t design for beyond what I know is real.

Model Driven Architecture …

My view is more philosophical and abstract.  What is a model?  For me, a model is something intangible.  It is a way we understand something.  But we represent our models in many ways.  Through words in written or spoken conversation, in unstructured pictures, in structured notation like UML, even code is a representation of a model.

What do we mean by driven? I view it as a something that takes an input that produces an output.  In this case, we take an input, the model, and produce an output, an architecture.  So, I take an understanding of problem and use that to derive an architecture.  So, that’s nothing new here.  However, I don’t like to confuse driving out an architecture from a representation of the model.  That’s different.  Now we are going beyond thought processes  into mechanical processes.  Then the challenge is about how to apply the feedback to the representation of the model – and that is what will make you agile.  Too much for my small brain.

Plumbing …

Yup, we do too much hand crafted plumbing!  It’s something that we have been working on for a long, long time.  I think convention over configuration, dependency inversion, meta-programming are all attempts at addressing this problem.  Some early success that I have experienced is on taking a polyglot approach. I am not talking about mixing general purpose languages on one runtime only.  I am also including domain specific languages. I’ve had some early success where using DSL to describe functional intentions and then generating a large portion of the plumbing.  Where I’ve suffered is when I mix concepts from different domains.  There is the domain of plumbing and the domain of the business.  Whenever I’ve mixed the two, it pains later rather than sooner.  Right now, the only way I’ve had some success is with aspect orientation and meta-programming.

@StatelessSessionBean …

Chris Naidoo is right.  That thing called J2EE and subsequent versions is just horribly broken.  It’s broken encapsulation and a whole lot more.  The fact that we now must use an annotation and not implement an interface is immaterial.  Both result in the same pain – mixed concepts (see plumbing above).  Annotations should be specific to the business such as @RecalculateCostsOnRerouteOfCargo can be used as an interception point for injecting a rule on a class or method.

I would go even further and say that the POJO JavaBean specification is also broken.  Why on earth must I have a no-argument constructor and accessors and mutators.

Last thoughts …

I may have missed some of the other discussions but these are the ones that I woke up with this morning. In general, my observation is that we need to be very concrete very early if we want to be agile, even in architecture.