FeaturesPluginsDocs & SupportCommunityPartners

Using Java Libraries in Rails Applications

Contributed by Brian Leonard and Chris Kutler
July 2008
[Revision number: 6.1-1]

This tutorial demonstrates how to use the Java API in Rails applications. In this tutorial, you use the FreeTTS speech synthesis Java libraries to enable users to listen to blog posts.

Contents

Content on this page applies to NetBeans IDE 6.1

To complete this tutorial, you need the following software.

Software or Resource Version Required
NetBeans IDE with Ruby and Rails support Version 6.1
MySQL database server Version 5.0 *
FreeTTS binary distribution freetts-1.2.1-bin.zip
Rails Framework 2**

* The NetBeans IDE 6.1 with GlassFish and MySQL Bundle download provides you with the complete software package required for this tutorial.

** The NetBeans IDE 6.1 downloads with Ruby and Rails support include the Rails 2.0.2 framework.

This tutorial builds on the Creating a Ruby Weblog in 10 Minutes tutorial. You must first complete that tutorial before proceeding with this tutorial. If you completed the Building Relationships Between Rails Models tutorial, you can use that project as well. Ensure that the project uses the JRuby platform.

Alternatively, you can use your own JRuby Rails project, and modify the steps to use the appropriate controller, model, and column names.

Adding Java Libraries to the JRuby Class Path

You use the project's Properties window to make Java JAR files available to the Rails server.

  1. Download the FreeTTS 1.2 speech synthesizing libraries and unzip in a directory of your choice.
  2. If the rubyweblog project is not already opened, open the project by choosing File > Open Project from the main menu. Browse to and select the rubyweblog project, then click Open Project.
  3. In the Projects window, right-click the rubyweblog project node and choose Properties from the pop-up menu.

  4. Select Java in the Categories pane, as shown in the following figure.

    Java Project Properties

    Note: The Include Java checkbox has no effect on the behavior of the IDE. This checkbox will be removed in future releases.

  5. Click Add JAR/Folder.

  6. In the Add JAR/Folder dialog box, navigate to the lib directory under the folder into which you unzipped the FreeTTS 1.2 download.

  7. Use Ctrl-Click to select all seven JAR files in the lib folder, as shown in the following figure, and click Open.

    Selecting FreeTTS jar files

    The JAR files appear in the Run-time Libraries list in the Project Properties window, as shown next.

    JAR files in run-time libraries list
  8. Click OK.

  9. Click the X button that appears in the lower right corner of the IDE, which is shown in the following figure, to stop the WEBrick server. The JVM needs to be restarted to include the FreeTTS libraries.

    Server stop button

    You can also stop the server by expanding Servers in the Services window, expanding the WEBrick node, right-clicking the server instance's node, and choosing Stop from the pop-up menu.

  10. Look at the lower right corner of the IDE. If the WEBrick status still appears and it shows that the server is running, you might have encountered Issue 131628 - WEBrick fails to stop. To resolve this problem, restart the IDE or complete the following steps.

    1. Open a terminal window.

    2. Execute the command java-bin-path/jps -l.

      You should see three Java processes: one is JPS, one is the NetBeans process, and the third is WEBrick (org.jruby.Main), which was started by the IDE.

      Server stop button
    3. Execute the command kill -9 process id. For the previous example, the command would be kill -9 16554.

Using Java Classes in a Controller Action

Next, you add an action to the controller to speak the title and body of the blog entry that is passed in the :id.

  1. Press Alt+Shift+O (use Ctrl+Shift+O on the Mac) to open the Go to File dialog box.

  2. Type posts_controller.rb in the File Name text box and click OK to open the file in the editor.

  3. Add to the top of the file the include statement and the two import statements that are shown in bold in the following code sample.

    include Java
    import com.sun.speech.freetts.Voice
    import com.sun.speech.freetts.VoiceManager
    
    class PostsController < ApplicationController
      # GET /posts
      # GET /posts.xml
    
    ...
    

    When you reference classes and packages from top-level packages other than com, org, java, and javax, you must either put the name in quotes, such as "mypkg.util.Init", or prepend Java::, such as Java::mypkg.util.Init.

  4. Copy the constant assignment and the speak action that are shown in bold in the following code sample and paste them into the class definition.

    include Java
    import com.sun.speech.freetts.Voice
    import com.sun.speech.freetts.VoiceManager
    
    class PostsController < ApplicationController
    
    
      SPOKEN_FIELDS = [:title, :body]
      def speak
        voice = VoiceManager.instance.get_voice('kevin16')
        voice.allocate
        # Get the text to speak
        # Note that #find_by_id returns nil
        # where #find throws an exception
        post = Post.find_by_id(params[:id])
        speak_these_items = []
        if post then
          speak_these_items = SPOKEN_FIELDS.map {
            |field| post.send(field)}
          sanitizer = HTML::FullSanitizer.new
          speak_these_items = speak_these_items.map {
            |s| sanitizer.sanitize(s) }
        else
          # No post was found so let the user know
          speak_these_items << 'No post was found'
        end
        # Speak the text
        speak_these_items.each { |s| voice.speak(s) }
        redirect_to :back
      end
    
    ...
            

Adding a Route for the Speak Action

Next, you edit the routing file to add a route for the speak action.

  1. In the Projects window, expand Configuration and double-click the routes.rb node to open the file in the editor.
  2. Look for the line that begins with map.resources :posts.

    If you completed the Building Relationships Between Rails Models tutorial, the line will be map.resources :posts, :has_many=> :comments.

  3. Add the following code to the end of the line.

    , :member => {:speak => :get}
              

    This code adds a member hash to the post resource. The hash is composed of action-HTTP verb pairs. The :speak => :get pair creates a route named speak_post. The URL for this route is posts/:post_id/speak.

Testing the Action

You use the link_to method to create a link tag that maps to the controller's speak action.

  1. To open the show.html.erb file, right-click any line in the show action (the method that starts with def show) and choose Navigate > Go to Rails Action or View from the pop-up menu.

  2. Place the cursor on the blank line above the first link_to statement.

  3. Type liai then press Tab to expand the LInk Action Index template. Set the arguments to "Speak", speak_post_path(@post), then add the | separator character, as shown in bold in the following code sample.

    <%= link_to "Speak", speak_post_path(@post) %> |
    <%= link_to 'Edit', edit_post_path(@post) %> |
    <%= link_to 'Back', posts_path %>
            
  4. Click the Run Main Project button to save all changes, start the server, and display the main page in a browser window.

  5. Click the permalink link for any blog post to show the post's detail page, then click the Speak link to hear the post's title and text.

    If you get the error message cannot load Java class com.sun.speech.freetts.Voice, you might not have successfully stopped the WEBrick server. See Step 9 in the Adding Java Libraries to the JRuby Class Path section. This step explains how to manually stop the server. Alternatively, stop and restart the IDE. The server must be restarted for the Java classes to be included.

Next Steps

>> More NetBeans Ruby Documentation


Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by