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
To complete this tutorial, you need the following
software.
* 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.
-
Download the FreeTTS 1.2
speech synthesizing libraries
and unzip in a directory of your choice.
-
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.
-
In the Projects window, right-click
the rubyweblog project node and choose
Properties from the pop-up menu.
-
Select Java in the Categories pane, as shown
in the following figure.
Note: The Include Java checkbox has no effect
on the behavior of the IDE. This checkbox will be
removed in future releases.
-
Click Add JAR/Folder.
-
In the Add JAR/Folder dialog box, navigate to the
lib directory under the
folder into which you unzipped the
FreeTTS
1.2 download.
-
Use Ctrl-Click to select all seven JAR files in the
lib folder, as shown in the following figure, and click Open.
The JAR files appear in the Run-time Libraries list
in the Project Properties window, as shown next.
Click OK.
-
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.
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.
-
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.
Open a terminal window.
-
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.
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.
-
Press Alt+Shift+O
(use Ctrl+Shift+O on the Mac) to
open the Go to File dialog box.
-
Type posts_controller.rb in the File Name
text box and click OK to open the file
in the editor.
-
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.
-
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.
-
In the Projects window, expand Configuration and double-click
the routes.rb node to open the file in the editor.
-
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.
-
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.
-
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.
-
Place the cursor on the blank line above
the first link_to statement.
-
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 %>
-
Click the Run Main Project button
to save all
changes, start the server,
and display the main page in a browser window.
-
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