Monday, October 19, 2009

Create ear file of your JRuby on Rails application

For JRuby on Rails project I use warbler to create the war file. To know the details see my previous blog JRuby on Rails building with warbler. Warbler doesn't have support to create ear file but it does a lot to create the war file. Now I will show you how can you create a ear file when you have the war file. I am assuming that you have warbler properly configured so that it can create the war file for you.


Create a new rake file (ear.rake) in RAILS_APP/lib/tasks folder. In this rake file we will define rake tasks to create the ear from the war file. Note that if you define a task in this file you will be able to execute that task from your capistrano capfile. To create the ear we need an application.xml file. We can create the application.xml file externally or we can create the file of our own. I am creating the content of this file using a method create_application_xml. Now in this rake file add the following task that will create the ear file for us:



task 'ear:create' => 'war' do  
  name = "myapp"
  ear_file = "#{name}.ear"
  staging = File.join(RAILS_ROOT,'tmp','ear')
  File.makedirs(staging) if !File.exists?(staging)
  
  puts "Copying war to #{staging}"
  #add the war file to the tmp directory
  File.copy("#{name}.war", staging)
  puts "Making application.xml"
  #create and add application.xml
  File.makedirs(File.join(staging, 'META-INF'))
  ear_file_dir = File.join(staging, 'META-INF')
  application_xml = File.join(staging, 'META-INF', 'application.xml')
  # always create a new override file, regardless of whether one exists
  File.open(application_xml, 'w') { |out| out << create_application_xml(name) }  
  
  puts "Creating the ear ...."  
  sh "jar cf #{ear_file} -C #{staging} ."
end


The method that is called by the above task to create the ear file content:



def create_application_xml(name)
  require 'erb'
  template=<<EOFAPPXML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN" "http://java.sun.com/j2ee/dtds/application_1_2.dtd">
<application id="application_myap">
<display-name>myapp</display-name>
<module id="webmodule_myapp">
<web>
  <web-uri>#{name}.war</web-uri>
  <context-root>/#{name}</context-root>
</web>
</module>
</application>
EOFAPPXML
  erb = ERB.new(template)
  erb.result(binding)
end



To execute the jar command to create the ear file you need to make sure that JAVA_HOME property is properly set.

No comments: