Before you start
About this tutorial
Ruby on Rails (rails) is a full-stack WEB application framework written in Ruby, and Ruby is a rich, free, extensible, portable, object-oriented scripting language. Rails is very popular among WEB application developers. With it, you can quickly and efficiently develop Web applications and deploy them to any web container, such as IBM? Websphere? or Apache Tomcat.
Prior to the advent of Rails and similar web application development frameworks, the standard tools for Web application development are the Java language, because the Java language is platform-independent and has a complete set of APIs. Many Java Web applications are still running, which results in a lot of useful, well-written Java code (referred to as legacy code in this tutorial) for good usability. Legacy Java code is usually packaged in a set of JAR files.
If you change the WEB application development platform to Rails, you can reuse legacy Java code. Ruby Java Bridge (RJB) is a toolkit that enables you to load JAR files into your Rails application and access the methods and variables in your Rail application. This tutorial explains how to configure and use RJB in a Rails application.
Goal
In this tutorial, you will learn how to:
- Download, compile, and install RJB
- Set up RJB to access the shared Java library
- Load Legacy Java code into a Rails application and access
This tutorial does not delve into the features of Rails. One of the advantages of Rails, compared to other Web frameworks, is that the number and quality of documents used for the platform are high (see Resources).
Prerequisites
This tutorial assumes that the reader is basically familiar with the Java language, Ruby, and Ruby on Rails.
System Requirements
This tutorial assumes that you are using Linux? System (however, in Windows?) The steps on the are basically the same). This tutorial assumes that you have a working Ruby on Rails. If not, find links to related documentation in the Resources section to help you install and configure Rails on your own system.
RJB requires that the Java SDK be installed on the system. If you need a Java SDK, you can download the latest Java SE SDK for your platform and install it right away.
RJB Installation and Setup
This section takes you through the download, installation, compilation, and setup of RJB.
Download RJB
RJB can be downloaded in the form of a standard Ruby Gem package or its own compiled source code archive. For the demo, I recommend downloading the source code archive, so I'll use this approach. With less gossip, download the RJB 1.1.3 source. zip file (the latest RJB version is available at the time of this tutorial).
Be sure to set or update the following environment variables, which are required to install RJB:
- Java_home must point to the Java SDK installation directory.
- PATH must include $JAVA _home/bin.
For example, in Bash (Linux only), assuming that the Java SDK has been installed to/USR/LOCAL/JDK60, execute the following command:
[root@san]# export java_home=/usr/local/jdk60
[root@san]# export path= $PATH: $JAVA _home/bin
Compiling and installing RJB
The next step is to compile and install RJB by executing the following command:
[root@san]# unzip Rjb-1.1.3.zip
[root@san]# cd rjb-1.1.3
[root@san]# Ruby setup.rb config
[root@san]# Ruby SETUP.RB setup
[root@san]# Ruby setup.rb Install
Confirm Installation Success
To confirm the success of the RJB installation, first invoke the Ruby Interactive console IRB:
Then enter require ' RJB ':
IRB (main):001:0> require ' RJB '
=> true
IRB (main): 002:0>exit
If the Require ' RJB ' command returns TRUE, it means the Ruby installation recognizes the newly installed RJB library. You can now start using RJB in your application.
Using legacy code through RJB
In this section, you will load and Access legacy Java code in the Rails application.
Sample Project
The Java Tar package from ICE Engineering is a good toolkit written in the Java language for working with archive files. It provides a local Java implementation of the TAR Archive utility, which can process. tar.gz files when combined with the Java.util.zip package. It also leverages the platform independence of the Java language and can be done without modification in all UNIX? Variants and running on Windows. As an exercise, you will use it to extract the contents of a sample tar file. In a similar way, you can use any legacy Java code in a Ruby on Rails application.
The goal of the exercise is to:
- Load the Tar.jar file into a Rails application.
- Load the required classes of the JAR file into the application.
- Extract the contents of the sample Test.tar file that uses these classes.
Entry
Sample files obtained
First, you need to get the sample tar file (Test.tar) and the Java tar package for the system:
- Download and save the Test.tar to a convenient location.
- Download and save javatar-2.5.tar.gz.
- Extract the contents of the javatar-2.5.tar.gz to a convenient location. In this exercise, the only file in this package that needs to be used is Tar.jar, which is in the jars directory.
Access shared libraries
RJB uses the Java Native Interface (JNI) to implement its functionality. Therefore, it needs to access some of the shared object files (shared libraries) that are included with the JDK installation. You must add the location of these files to the LD_LIBRARY_PATH environment variable by using the following command:
[root@san]# export java_home=/usr/local/jdk60
[root@san]# export ld_library_path= $LD _library_path: $JAVA _home/ jre/lib/i386
[root@san]# export ld_library_path= $LD _library_path: $JAVA _home/jre/lib/i386/client
If you plan to use RJB in a standalone Ruby script, you simply set these environment variables in the shell you are working on. For your Ruby on Rails application, you must also set these variables in the Rails application's environment.rb file.
Mount RJB to the Rails application
To Mount RJB to a Rails application and set it to invoke Java classes, you need to perform two steps:
- Tell Ruby to include the RJB library in your code.
- Loads the JVM, setting the classpath and other optional JVM parameters.
First, use the following command to initialize the RJB:
Next, add all the legacy. jar files that you want to use in the Rails application-in this case tar.jar-to the CLASSPATH variable:
Rjb::load (Classpath = '.:/ Path/to/tar.jar ', jvmargs=[])
You can leave the Jvmargs blank unless you want to specify additional parameters for the JVM.
You can now import the Java classes you intend to use into Ruby, instantiate them, and invoke the methods that you want.
Import Java classes into Ruby and instantiate
The Ruby code in Listing 1 imports the Java class you need from the Tar.jar package and creates a Ruby object from the imported class:
Listing 1. Import Java classes into Ruby and instantiate
tararchive = Rjb::import('com.ice.tar.TarArchive')
fileinputstream = Rjb::import('java.io.FileInputStream')
file = Rjb::import('java.io.File')
file_instance = file.new_with_sig('Ljava.lang.String;','.')
fileinputstream_instance =
fileinputstream.new_with_sig('Ljava.lang.String;','test.tar')
tararchive_instance =
tararchive.new_with_sig('Ljava.io.InputStream;',fileinputstream_instance)
p "Let's verify that the objects created are indeed of the classes we
wanted..."
p "------------------------------"
p "For the File instance...."
p "Expecting: java.io.File , it is: " + file_instance._classname
p "------------------------------"
p "For the FileInputStream instance...."
p "Expecting: java.io.FileInputStream , it is: " +
fileinputstream_instance._classname
p "------------------------------"
p "For the TarArchive instance...."
p "Expecting: com.ice.tar.TarArchive , it is: " +
tararchive_instance._classname
Importing Java Classes
The first three lines in Listing 1 call the RJB Import method to import the required classes into the Ruby variable tararchive, FileInputStream, and file respectively. You must specify the full package path for the class-for example, the Tararchive class is com.ice.tar.TarArchive, and the FileInputStream class is java.io.fileinputstream-as if you were running the application with a Java command.
Instantiate an imported class
Next, Listing 1 creates an object that imports the class. You can create a class by calling the new method of each class, just as you would create any Ruby object (for example, tararchive.new). But doing so calls the default constructor of the Tararchive class (without parameters), which you do not want to do.
When you overload the constructor of a class, you need to make some modifications to the object creation method above. In this case, you must create the object in the following manner:
Object = Classname.new_with_sig (' signature ', Parameter[,more parameters])
The first parameter defines the signature type of the parameter required by the constructor. It tells RJB to call its input parameter to match the constructor of the specified signature.
The 4th and 5th statements in Listing 1 create objects for both the file and FileInputStream classes, which call the corresponding constructor, and the parameter type is String.
In the 6th statement in Listing 1, one of the constructors of the Tararchive class accepts objects of type InputStream as arguments. The signature type of the statement is a separate inputstream input parameter. The details of these type signatures are well described in the Java SDK documentation for the GetName API (see Resources). The second parameter is the InputStream type object that is created.
Verify object Creation
The remainder of Listing 1 verifies that the object created by RJB is an object of the specified class by invoking the _classname method that is added to each object. For example, calling Tararchive_instance._classname will return com.ice.tar.TarArchive, which means that the class is loaded correctly and the object of the class is created successfully.
calling methods and capturing results
After you load a class into Ruby and create an object from it, the next step is to call the method you want and view the results. For example, you want to use the Extractcontents method of the Tararchive class to extract the contents of the sample file (Test.tar) into the current directory.
As with constructors, methods can be invoked in two ways. One way is to call the method directly, for example:
Tararchive_instance.extractcontents (file_instance)
After the method overload, use _invoke to call the type signature of each parameter of the specified method:
Tararchive_instance._invoke (' extractcontents ', ' Ljava.io.File; ', file_instance)
This step enables RJB to know which methods should be called when the method overloads.
As with normal Ruby code, you will capture the results (if any) returned by the object method, and use the results in your own application. The result returned by the method call is automatically converted to the appropriate object type. You simply call the method directly within the object.
The functionality implemented in the Java Tararchive class is now available for your Ruby code. By using the same approach, any functionality that has been implemented in Java code can be reused in your Ruby and Rails applications without modification.
The complete code
Listing 2 shows the complete Ruby code for the Tutorial sample (also available for download):
Listing 2. Complete sample Ruby Code
# Include 'rjb' library into your application
require 'rjb'
# Load the JVM specifying the jar files to include and any other optional JVM arguments
Rjb::load(classpath = '.:/path/to/tar.jar', jvmargs=[])
# Import the classes you want to use into a Ruby variable
# specify the full package path to the classes.
tararchive = Rjb::import('com.ice.tar.TarArchive')
fileinputstream = Rjb::import('java.io.FileInputStream')
file = Rjb::import('java.io.File')
# Create objects of the classes. Use the new method directly or use
# the 'new_with_sig' call to invoke overloaded constructors with arguments
# Directory you want to extract the files in this case, the current directory
file_instance = file.new_with_sig('Ljava.lang.String;','.')
# inputstream instance of the file to extract
fileinputstream_instance = fileinputstream.new_with_sig('Ljava.lang.String;','test.tar')
# tararchive instance of the file to be extracted.
tararchive_instance = tararchive.new_with_sig('Ljava.io.InputStream;'\
,fileinputstream_instance)
# Invoke the method from the class and capture the results.
# Use either the direct call of the method,
# or the '_invoke' call to invoke overloaded methods.
p 'Extracting file.....'
tararchive_instance.extractContents(file_instance)
p 'Done...'
Try the code, save the code in Listing 2 to a file, and the extension is. RB (or use the rjb-javatar.rb in the download) and run in the Ruby interpreter.
Conclusion
Reusing legacy Java code in a new Rails application is actually very simple, in the following ways:
- Install the Java SDK and RJB.
- Export the Java_home and LD_LIBRARY_PATH environment variables to the environment.rb file of your Rails application.
- Include the RJB library in your application.
- Mount the RJB and JVM by specifying the JAR file you want to use.
- Import the class into the Ruby variable from the JAR file you want to use and create the object for the class.
- Start using the class you just created in your Rails application, just as you would with any Ruby object.
If you want to reuse business logic that has already been implemented using Java code in a Rails application, RJB is useful and does not need to be implemented using Ruby. It also provides the benefits of Ruby on Rails and Java programming.
consider alternative methods
You can also use an alternative method called JRuby, which can achieve the same goal as RJB. JRuby is a complete ruby package implemented in the Java language that enables Ruby to run on top of the JVM (see Resources). With JRuby, you have access to all Java libraries. JRuby requires JRuby Ruby Gems to be installed because normal ruby Gems for non-Java Ruby is not compatible with JRuby.
RJB and JRuby each have their advantages and disadvantages. For Jruby,ruby to run all over the JVM, each Ruby call will go through the JVM, which will make execution very slow. Similarly, if you have a Rails application set up, you need to start from scratch to JRuby access to Java code. As a native Ruby package, RJB is easy to install and can be used in existing Rails settings. If you need to quickly invoke some Java code snippets in your Rails application, then RJB is the best choice.
Overall, the ability to reuse legacy Java code in a Rails application is useful. The design and writing that are implemented in the Java language are very good business logic is not shelved, instead, you can continue to play useful functions in new WEB applications.