corner imagecorner image
FeaturesPluginsDocs & SupportCommunityPartners

Mixing Java and Ruby Applications

This article shows how to combine Ruby and Java applications using the NetBeans IDE.

Contents

Content on this page applies to NetBeans IDE 6.0
Article Requirements
Create the Java Project
Edit the Java Project
Write the Rails Application

Article Requirements


This article shows how to combine Java applications with Ruby applications. Along the way, it demonstrates some of the latest Ruby capabilities in the NetBeans IDE 6.0.

This article requires the following:

  • A basic knowledge of programming with the Ruby technologies
  • NetBeans IDE 6.0 with Ruby (download) on your computer

Set Up Instructions

There are several set-up tasks, principally involving database set up and including TopLink JAR files. Here is how to add the required currency data to a database table. When you set up the Rails project, you will add the necessary TopLink JAR files.

You need to configure a database as follows:

  • Create a table named CURRENCY.
  • Create three string (or VARCHAR) columns in the CURRENCY table: Country, Currency, and Name.
  • Populate the table with some data. For example, you might add these three currencies plus any others you want: "USA", "Dollar", "USD"; "Czech Republic", "Koruna", "CZK"; "Norway", "Krone", "NOK".

You also must set up NetBeans so that it can access the database table. That is, if need be, configure a JDBC driver for the database and add a data source in the Services window.

For example, the following SQL creates a CURRENCY table in a Derby database called SAMPLE (with a username and password combination of APP/APP). If you want to use the same SAMPLE database, you can execute this SQL from within the IDE (after connecting to the SAMPLE database) and create the table. Feel free to create your own Derby database, too, using the Tools->Java DB Database->Create Database action. The SQL to create the same table on a different database system may differ from this example.

drop table "APP"."CURRENCY";
  create table "APP"."CURRENCY" (
country VARCHAR(20), currency VARCHAR(20), name VARCHAR (20),
id INTEGER GENERATED always AS IDENTITY);

 alter table CURRENCY add constraint currencyPK PRIMARY KEY (id);
  INSERT INTO CURRENCY VALUES ('USA', 'Dollar', 'USD',DEFAULT);
  INSERT INTO CURRENCY VALUES ('Czech Republic', 'Koruna', 'CZK',DEFAULT);
  INSERT INTO CURRENCY VALUES ('Norway', 'Krone', 'NOK',DEFAULT);
      INSERT INTO CURRENCY VALUES ('France', 'Euro', 'EU',DEFAULT);

Create the Java Project

Once you have completed the setup tasks, you can create your project. Begin by creating a Java Desktop application, which is really a Swing application, and choose the option for database binding. The wizard takes you through the steps to connect the project, which we call Money, to the datasource, which in our case is the CURRENCY table on the Derby sample database. In a few button clicks you have a fully functional database CRUD application.

Figure 1: Create a Desktop Database Application Called Money

Create database application

Click to enlarge

Figure 2: Connect the Project to the Datasource

Connect project to datasource

Click to enlarge

Run the Money application (right click the project and select Run) and you should see a screen something like the following. (Use Ctrl+Q to quit the application.)

Figure 3: Money Application

Money Applicaton

Edit the Java Project

Start by examining the generated Java classes; in particular, the Currency.java class. Here are some tips for viewing the pieces of the project.

From the Projects window, expand the project's Source Packages->money node and double-click Currency.java to open the file in the Source editor. The Editor window displays the entire class and its code.

Class Members

Press Ctrl+F12 to see a list of the members of the Currency class. You can use the Members dialog to move around quickly within the class.

Figure 4: Currency.java Class Members

Class members

For example, to see the class definition, enter Cur in the Filter field.

Figure 5: Currency Class Definition

Curency Class definition

Note: Be sure that the generated Currency.java code correctly declares the ID identifier field. You may have to add a line to the Java file that indicates that the identifier is generated and unique. The correct code for the identifier field follows. Note, too, adding the line for the generation type (@GeneratedValue (strategy=GenerationType.IDENTITY)) will probably result in a missing imports error and the line will be underlined in red. You can fix easily fix this by clicking the error and pressing Alt+Enter.

 @Id
 @GeneratedValue (strategy=GenerationType.IDENTITY)
 @Column(name = "ID", nullable = false)
      private Integer id; 

Task List

The IDE automatically maintains a task list showing compilation errors, warnings, and so forth. You can open and view the Task List at any time by pressing Ctrl+6.

Figure 6: Task List

Task List display

Examine the Currency source code. Notice that it contains Java Persistence API annotations. These annotations indicate the binding to the database columns and are marked with an at sign (@). For example, the bindings to the database columns are marked with @Column, followed by the column name and the Java variable, such as: @Column(name="COUNTRY") private String country;

Create a Java Class to Access Database Columns

You need to create a new Java class, which you call CurrencyLookup, that accesses these Java Persistence entities, the database columns. Later, your Rails application calls this CurrencyLookup class to get the list of currencies from the database. The IDE Source editor code completion and template features help you with this task.

In the CurrencyLookup class, write a getAll method to return the list of currencies. The completed method will look as follows. Note that the persistence unit, samplePU, matches the name of the SAMPLE database that we used; your persistence unit may be different.

public List<Currency> getAll() {
   EntityManager em = Persistence.createEntityManagerFactory("samplePU").createEntityManager();
   Query query = em.createQuery("select c from Currency c");
   return query.getResultList();
      }; 
  1. Right click the money node in Source Packages and select New->Java Class.
  2. Enter CurrencyLookup for the Class Name field in the New Java Class dialog. (Be sure that the dialog indicates that the location is Source Packages and the package name is money. If not, set those fields accordingly.) The IDE creates a CurrencyLookup.java class and places it within the Source Packages->money node.
  3. Write the method to return a list of all currencies. The IDE functions (such as code completion, fix imports, and so forth) can help. Start by typing in pu (for public) somewhere within the CurrencyLookup class, then press Ctrl+Space. Notice that the IDE completes the text for you. (Note that the short cut key combinations shown here are for a Windows platform and may be different on other platforms. You should refer to the Help->Keyboard Shortcuts file for the exact key combination for your environment.)

    Figure 7: Code Completion

    Code completion
  4. Type in List<Cu, followed by the key combination Ctrl+K to complete the Currency class name. The IDE completes the name as CurrencyLookup, so be sure to delete Lookup.

    Figure 8: Class Name Completion

    Code completion
  5. Continue to enter the method name and the rest of the code for the method.

More Source Code Editing Tips

Here are some other source code editing tips:

  • Use the Editor window's context menu Fix Imports function to import any missing classes.
  • Press Alt+Enter to see a tip regarding missing components from a method.
  • When editing a method body, pressing Return inserts the matching right brace (}).
  • You can replace a word quickly by placing the cursor on that word, then pressing Ctrl+R and entering the new text.

When you complete the CurrencyLookup query class, you can test it if you want. Use the Tools->Create JUnit Test function, or use the shortcut key combination Ctrl+Shift+U. This generates a skeleton CurrencyLookupTest class. You can delete the dummy code and add an assertFalse line for testing. For example, you might add the following line to test that a line of data returned from the database is not empty: assertFalse("contains data", new CurrencyLookup().getAll().isEmpty());. Then, use Shift+F6 to run the test.

Write the Rails Application

Now create the Rails application that will access the Java code in the Money application. You first have to do some minor set-up work, including building the Money project and adding some Java JAR files to the Rails project.

Create and Set-Up the Rails Project

  1. First, be sure that the Money Java desktop application is built. Select the project's context menu Clean and Build function, or press Shift+F11.
  2. Create a new Ruby->Ruby on Rails project. Accept the wizard's defaults and the IDE generates the Rails project. (If you have installed native C Ruby, then you are asked to choose a Ruby interpreter. You should choose the bundled JRuby interpreter.)

    Figure 9: Create the Rails Project

    Create Rails project

    Click to enlarge

  3. Next, set up some Java properties for the Rails project. Specifically, you need to add the TopLink JAR files for the Java Persistence API, plus the JAR file for the Money Java desktop application. (The Money.jar file is in the Money project's /dist directory.) Right click the Rails project node and select Properties. Select the Java category, then the Add JAR/Folder button. Navigate to the three JAR files and include them. Be sure to include the toplink-essentials-agent.jar and toplink-essentials.jar, both of which can be found in your NetBeans installation's java1/modules/ext/toplink/ directory. It's not necessary to edit the Rails' config/database.yml file in this project since the Rails application uses Java code for its database lookup operations.

    Figure 10: Include the JAR Files

    Include JAR files

Add Currency Lookup to Rails Project

Here you modify the generated Rails project to use the currency lookup code from the Money Java project.

  1. First, run the Rails project to bring up the default, empty Rails page in the browser. Edit the default URL to set it to the application. For example, you should see a URL something like http://localhost:3001/ to which you append /money/list. The browser displays a routing error message. When you complete your coding--you will be adding an action to respond to this URL--then the application will run correctly in the browser.
  2. Use the Rails code generator to create a money controller and a list view. From the Rails project context menu, select Generate. In the Rails Generator dialog, select controller in the Generate field, and type money in the Name field and list in the View field. Click OK.

Figure 11: Generate Money Controller

Generate mondey controller

The generated money controller opens in the Editor window. Add code to the controller to enable the application to access Java code (require 'java') and include the CurrencyLookup Java class (include_class 'money.CurrencyLookup'). Once you've done that, you can call the Money project CurrencyLookup Java class just like any other class. Keep in mind, too, that the IDE has Ruby and Rails-specific code completion available; press Ctrl+K and Ctrl+Space for help completing method names and so forth.

Here's the complete code for the MoneyController class:

class MoneyController < ApplicationController
  def list
    require 'java'
    include_class 'money.CurrencyLookup'
    lookup = CurrencyLookup.new
    @list = lookup.get_all
      end
end

Set Up the View

Here's how to produce a nicely formatted table showing the three columns from the database. We also show you some of the IDE Ruby shortcuts.

  1. Open the list view generated for the MoneyController class. Use the Navigate->Goto Rails Action/View function, or Ctrl+Shift+A. The list.rhtml file, or Money#list view, opens in the Editor window.
  2. Insert a table skeleton in the list view. To do this quickly, type table and press the Tab key. The IDE adds the HTML for the table rows and cells.
  3. Figure 12: Using Tab Shortcut

    Using Tab shortcut

     

  4. Select the table row (<tr>) block and press Alt+Enter. Since you want the code to iterate over the list of currencies, you want to surround the table rows with a for loop. The Alt+Enter shortcut displays a quick fix option, which appears with a lightbulb icon. Choose the option Surround with for, then press Enter.
  5. Figure 13: Using Alt+Enter Shortcut

    Using Alt+Enter shortcut
  6. Now, change the parameters of the for loop to match the currency data. Use the Tab key to move through these parameters. Call the loop variable c instead of f and change @field to @list. Use the code completion shortcut to add additional table cell tags (<td></td>) within the row tag (<tr></tr>).
  7. Figure 14: Using Code Completion to Add HTML Tags

    Using code completion to add HTML tags
  8. Insert a code template for a Ruby expression within the table cell tags. Type re then press the Tab key. The IDE inserts the Ruby expression <%= %>.
  9. Figure 15: Inserting Ruby Expressions

    Inserting Ruby expressions
  10. Set up three such table cell blocks, each containing the <%= %> Ruby expression. Insert the currency column names (c.country, c.code, and c.name) within the <%= %> blocks. When you're done, the code should look as follows:
  11. <h1>Money#list</h1>
      <p>Find me in app/views/money/list.rhtml</p>
      <table border="1">
    <% for c in @list %>
    <tr>
      <td>
         <%= c.country %>
      </td>
      <td>
         <%= c.currency %>
      </td>
      <td>
         <%= c.name %>
      </td>
    </tr>
    <%end%>
             </table>
  12. Press Shift+F6 to view the table in the browser. You should see something like the following, depending on the currencies you have added to the database:

Figure 16: Displaying the Ruby Currency Table

Displaying the currency table via Ruby project

Summary

This article demonstrated how you can combine a Ruby on Rails application with a Java desktop application. The Java desktop application contained code to access a database table and the Ruby application called the Java database table access code to retrieve and display the data.

The article also illustrated a number of the keyboard shortcuts available when developing Java and Ruby applications.


Next Steps




>> More NetBeans Ruby Documentation

Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   GlassFish Community: an Open Source Application Server   Open Solaris  Open JDK: an Open SourceJDK   Mobile & Embedded Community     Sponsored by 
Sponsored by Sun Microsystems