57
Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server Learn how XML can improve the efficiency of your JRuby on Rails and Ajax development Skill Level: Intermediate Tyler Anderson ([email protected]) Freelance writer Backstop Media 27 May 2008 The Ruby on Rails framework has handy XML features that will make developing with and serving database data in XML format to your JavaScript applications easier than ever. JavaScript also has built-in XML parsing capabilities that make it a snap to receive and parse data in XML format. But what if you now want to hook into Java™ applications without having to deploy another server? That's where JRuby comes in. JRuby on Rails is the Java implementation of the Ruby on Rails framework, bringing the benefits of Rails to Java programming by allowing deployment of Ruby apps to Java application servers. In this tutorial, you'll develop a JRuby on Rails application deployable to a Java application server that will serve database data in XML format to an Ajax client that you'll build for film lovers to manage their online films database. You'll also deploy a couple of Java Server Pages pages on the same Java application server to assist the Ajax client in adding and updating films. Section 1. Before you start This tutorial is recommended for XML developers interested in using JRuby on Rails, Java technology, and a database. It's also for those XML developers who wish to reduce their development time as they leverage the JRuby on Rails framework to use scaffolding without having to sacrifice the option of also using Java code. Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 57

Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

  • Upload
    others

  • View
    18

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Use JRuby on Rails and XML to supercharge Ajaxwith a Java Application ServerLearn how XML can improve the efficiency of your JRuby onRails and Ajax development

Skill Level: Intermediate

Tyler Anderson ([email protected])Freelance writerBackstop Media

27 May 2008

The Ruby on Rails framework has handy XML features that will make developing withand serving database data in XML format to your JavaScript applications easier thanever. JavaScript also has built-in XML parsing capabilities that make it a snap toreceive and parse data in XML format. But what if you now want to hook into Java™applications without having to deploy another server? That's where JRuby comes in.JRuby on Rails is the Java implementation of the Ruby on Rails framework, bringingthe benefits of Rails to Java programming by allowing deployment of Ruby apps toJava application servers. In this tutorial, you'll develop a JRuby on Rails applicationdeployable to a Java application server that will serve database data in XML formatto an Ajax client that you'll build for film lovers to manage their online films database.You'll also deploy a couple of Java Server Pages pages on the same Javaapplication server to assist the Ajax client in adding and updating films.

Section 1. Before you start

This tutorial is recommended for XML developers interested in using JRuby on Rails,Java technology, and a database. It's also for those XML developers who wish toreduce their development time as they leverage the JRuby on Rails framework touse scaffolding without having to sacrifice the option of also using Java code.

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 57

Page 2: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

About this tutorial

This tutorial shows how to develop Ajax applications more efficiently with the help ofJRuby on Rails and Java Server Pages (JSP) technologies hosted on a Javaapplication server, IBM® WebSphere® Application Server Express. You'll use theframework set up by JRuby on Rails to give simple access, through XML, to yourdatabase of films, and you'll use JSP technology to add new films to and editexisting films in the database. In all, you'll learn to do the following:

• Install WebSphere Application Server Express

• Install and set up your first JRuby project

• Install the Goldspike plugin to your JRuby project for deployment toWebSphere Application Server Express

• Set up your JRuby project to use Derby as the database

• Get a working JRuby on Rails 2.0.2 project to properly send XMLrequests to the Ajax client

• Develop JSP files to handle adding and editing film entries by utilizingXML requests made by the Ajax client

• Develop an all-Ajax client to manage your films

• Deploy and test on WebSphere Application Server Express

To accomplish the above, you'll develop an example application for the online filmindustry where lovers of film will be able to manage, tag, and be redirected to theirlibrary of online videos. The Ajax application will receive communications in XMLformat from JRuby on Rails and send XML communications to JSP applicationsrunning a single Java application server instance.

Prerequisites

For this tutorial you'll need the following downloads:

• WebSphere Application Server Express —Get a trial version ofWebSphere Application Server Express from IBM (this tutorial uses V6.1).You'll use WebSphere Application Server as a full featured Javaapplication server to host your JRuby on Rails Web application. However,please note that you can use any application server, such as ApacheTomcat or Apache Geronimo.

• JRuby —JRuby is a Java-based interpreter for Ruby, allowing deployment

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 2 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

to Java application servers through the Goldspike plugin with fullintegration with Java libraries. This tutorial uses JRuby version 1.1.1, andRails version 2.0.2. Rails will be downloaded and installed by RubyGem,which is part of the JRuby package.

• Database—The example application requires a database to store andretrieve film entries. This tutorial uses the version of Derby that comeswith WebSphere Application Server Express, though you can use anyversion. Derby is nice because it's free and lightweight.

Knowledge of JSP and Rails technology is useful for this tutorial, but not required.

Section 2. Introduction

This section gives an overview of how to leverage the XML features of JRuby onRails, JSP and Ajax technology, and how WebSphere Application Server Expressbrings them all together.

XML, Rails, Java and Ajax technologies

Frequently used acronyms

• Ajax: Asynchronous JavaScript and XML

• DOM: Document Object Model

• XML: Extensible Markup Language

With built-in XML features of JRuby on Rails, you can access to database data inXML format with little effort, and with JRuby's greater Java compatibility you bring ahost of other Java features into your arsenal. Thus in a single Ajax application, asyou'll build in this tutorial, your Ajax application will reference both JRuby on Railsand JSP code to combine the strengths of both programming languages in a singleWeb application. These strengths include the easily used Ruby on Rails framework,and the power of Java programming in a JSP page.

Next you'll see how WebSphere Application Server Express fits in.

How WebSphere Application Server Express brings them alltogether

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 57

Page 4: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

WebSphere Application Server Express is a Java Servlet container, and thanks toJRuby and the Goldspike plugin, you can now deploy JRuby on Rails applications toJava application servers as packaged WAR files. It doesn't stop there, either. Youcan deploy JSP files within the Ruby application, to have them work alongside yourRuby files.

In Figure 1 is a sneak peek into the application that you'll develop.

Figure 1. Showcase of the example application

You'll code the film management application in Ajax complete with the ability to addnew films, and view, edit, and delete each individually.

Before the fun begins, however, first you'll do a quick installation and setup ofWebSphere Application Server Express and JRuby.

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 4 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Section 3. Quick WebSphere Application Server Expressinstallation guide

Installing WebSphere Application Server Express is pretty simple. Simply followalong and you shouldn't run into any problems.

Installing WebSphere Application Server Express

To begin the installation, unzip the file you downloaded, navigate to the WebSphereApplication Server directory, and open the install.exe file. This should bring you tothe welcome page (Figure 2).

Figure 2. Welcome page

Click Next to view the license agreement (Figure 3).

Figure 3. Accept the license agreement

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 57

Page 6: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Select the I accept both the IBM and the non-IBM terms radio button to accept thelicense agreement. Click Next to open the Install Sample applications page (Figure4).

Figure 4. Installing sample apps

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 6 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Check the Install the sample applications box and click Next. This brings you tothe installation location page (Figure 5).

Figure 5. Choose installation location

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 57

Page 8: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Choose your destination, and click Next to open the page where you'll set upadministrative security (Figure 6).

Figure 6. Enabling admin and samples security

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 8 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Choose any username and password you wish. For this tutorial, username andpassword, respectively, were chosen. Click Next to open the installation summarypage (Figure 7).

Figure 7. Installation summary

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 57

Page 10: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

If everything looks correct, click Next. After installation completes, you see theinstallation results page (Figure 8).

Figure 8. Installation success

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 10 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Click Finish to complete the installation.

You can play with the First steps console if you wish, but you don't have to worryabout it for now. To start the server, simply click Start > Programs > IBMWebSphere > Application Server - Express V6.1 > Profiles > AppSrv01 > Startthe server.

And installing WebSphere Application Server Express is as simple as that! Nextyou'll install JRuby.

Section 4. Quick JRuby installation and first projectsetup guide

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 57

Page 12: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Installing JRuby is simple enough as well, but involves a few more command linedetails. In this section you install JRuby, and all necessary add-ons including Rails.To finish off the section, you create your first JRuby project complete with theGoldspike plugin, and set up your project for deployment to WebSphere ApplicationServer Express for testing.

Installing JRuby

Remember the jruby-bin-1.1.1.zip file you downloaded earlier? To install JRuby, youunzip this folder to your applications directory (C:\apps\ on the test machine). Next,add the JRuby\bin and WebSphere\AppServer\java\bin directories to your path.

With that set, you're ready to install Rails, ActiveRecord-JDBC, and other requiredgems using RubyGem, a package management tool that comes with JRuby. Enterthe commands in Listing 1.

Listing 1. Installing Rails and the JDBC adapter

gem install -y --no-rdoc --no-ri railsgem install -y --no-rdoc --no-ri activerecord-jdbc-adapter

The first of these two commands downloads and installs Rails. The seconddownloads and installs the JDBC adapter that you'll use to connect to the Derbydatabase later in the tutorial.

Your first JRuby project

Now you'll use JRuby on Rails to create your film project. Enter the two commandsin Listing 2. Note that each of these two JRuby commands should be on a singleline.

Listing 2. Creating the film project with the Goldspike plugin

jruby -S rails filmcd filmjruby script\plugin install http://jruby-extras.rubyforge.org/svn/trunk/

rails-integration/plugins/goldspike

The first command creates the project and accessory files. The second opens theright directory, while the third installs the Goldspike plugin into your film project. It'sthe Goldspike plugin that makes it possible to create a WAR file for deployment tothe application server, so you'll need that before you go too much further.

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 12 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Now you need to update several files to finalize the configuration and ensure properfunctioning of the project.

First up is the database.yml file. Edit it to point to the proper development database(see Listing 3).

Listing 3. Updating config/database.yml

development:adapter: jdbcdriver: org.apache.derby.jdbc.EmbeddedDriverurl: jdbc:derby:c:\apps\rubyapps\film\db\development;create=true

test:adapter: jdbcdriver: org.apache.derby.jdbc.EmbeddedDriverurl: jdbc:derby:c:\apps\rubyapps\film\db\test;create=true

production:adapter: jdbcdriver: org.apache.derby.jdbc.EmbeddedDriverurl: jdbc:derby:c:\apps\rubyapps\film\db\production;create=true

Note you simply defined three databases, one for each of the three environments:development, test, and production. In this tutorial you only need to worry about thedevelopment database, which is a Derby database in this case.

Now you'll update the war.rb file with some prerequisites for the final application (seeListing 4).

Listing 4. Updating config/war.rb

...#maven_library 'mysql', 'mysql-connector-java', '5.0.4'

# Add the Derby library to the WARinclude_library 'derby', '10.1.3';

# Add the ActiveDirectory-JDBC adapter to the WARadd_gem 'activerecord-jdbc-adapter', '0.8';@result.rails_env= 'development';

In this file you add a few lines to tell Goldspike to include the Derby WAR file, theJAR file for the activerecord-jdbc-adapter plugin, and to tell WebSphere to deploythe application in development mode. Finally, you need to update the routes.rb file(see Listing 5).

Listing 5. Updating config/routes.rb

ActionController::Routing::Routes.draw do |map|map.resources :filmsmap.update 'films/:id/update', :controller => 'films',

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 57

Page 14: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

:action => 'update'...

You'll see how this information comes into place later in this section, but for nowunderstand that you're adding a couple of new routes to make sure things runsmoothly. Now you're ready to generate the scaffolding for your films database (seeListing 6). Note the command shown is meant to be entered on a single line.

Listing 6. Generating scaffolding, model and views for the films database

jruby script\generate scaffold films title:string url:string tags:stringvibe:integer dateadded:date notes:text

Rails 2.0 is quite different from previous Rails versions in that rather than load thedatabase first, then generate the scaffolding, you can generate the scaffolding, andthe model and controller will be built for you, accordingly. (You'll create the databasefrom these parameters in a moment.) Note that you specify the fields (columns) ofthe films table as:

• Title as string

• Url as string

• Tags as string (keywords defining the video)

• Vibe as integer (number between 1 and 10 that specifies how much youlike the video)

• Dateadded as date

• Notes as text

Before going into the generated scaffolding code, you'll need to update theapplication.rb file (see Listing 7).

Listing 7. Updating app/controllers/application.rb

...# Uncomment the :secret if you're not using the cookie session storeprotect_from_forgery :secret => 'f0acb4610baa60661ff5208183e85263'

end...

This is required by the Rails application for it to work properly, since by default onthis project, the cookie session store is not being used.

Next, you need to do a few more thing to get the Rails scaffolding files created into afunctional state.

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 14 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Finalizing the JRuby on Rails application

The Rails scaffolder quickly creates several files. First, you need to edit theindex.html.erb file (see Listing 8).

Listing 8. Updating app/views/films/index.html.erb

...<td><%=h films.notes %></td><td><%= link_to 'Show', :action => 'show',

:id => films %></td><td><%= link_to 'Edit', :action => 'edit',

:id => films %></td><td><a onclick="return confirm('Are you sure?');"

href="films/destroy/<%= films.id%>">Destroy</a></td>

</tr><% end %>...<br />

<%= link_to 'New Film', :action => 'new' %>

Next you'll update edit.html.erb (see Listing 9).

Listing 9. Updating app/views/films/edit.html.erb

...<%= error_messages_for :films %>

<% form_for(:films, :url => update_url(:id => @films.id)) do |f| %><p>

<b>Title</b><br />...<% end %>

<%= link_to 'Show', :action => 'show', :id => @films %> |<%= link_to 'Back', :action => 'index' %>

As shown in Listing 9, use the new route you added back in Listing 5 (update_url).This correctly creates the URL for the edit form to submit to. Lastly, update the twolinks at the bottom as you did in Listing 9. The same goes for the show.html.erb file(see Listing 10).

Listing 10. Updating app/views/films/show.html.erb

...</p>

<%= link_to 'Edit', :action => 'edit', :id => @films %> |<%= link_to 'Back', :action => 'index' %>

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 57

Page 16: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

And again, update the new.html.erb file (see Listing 11).

Listing 11. Updating app/views/films/new.html.erb

...<% end %>

<%= link_to 'Back', :action => 'index' %>

With all of the links and files ready to roll, the last file that you need to update is thefilms_controller.rb file (see Listing 12).

Listing 12. Updating app/controllers/films_controller.rb

...def index

@films = Films.find(:all)

respond_to do |format|format.html # index.html.erbformat.xml { render :xml => @films }

endend

...def create

@films = Films.new(params[:films])

respond_to do |format|if @films.save

flash[:notice] = 'Films was successfully created.'format.html { redirect_to(films_url) }

...def update

@films = Films.find(params[:id])

respond_to do |format|if @films.update_attributes(params[:films])

flash[:notice] = 'Films was successfully updated.'format.html { redirect_to(films_url) }

...

The first required update is to the index action. You need to update this action sothat it displays XML properly. It previously didn't have the format rules to displayXML, and with this update you are ready. The last two updates require changes tothe redirect_to statements in the create and update actions: Replace @filmswith films_url.

Lastly, you'll need to create and initialize the database, as in Listing 13.

Listing 13. Initializing the database

mkdir lib\javacp "c:\Program Files (x86)\IBM\WebSphere\AppServer\derby\lib\derby.jar"

lib\java\derby-10.1.3.jarjruby -S rake db:migrate

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 16 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Note that the copy command (cp) should be all on one line. The first two commandscreate and add the Derby JAR to your project. The last command creates thedatabase based on the auto-generated db/migrate/001_create_films.rb (theauto-generated migration based on parameters that are passed to the scaffolder, asyou've done here, is a cool new JRuby on Rails feature).

That completes the JRuby on Rails project. Next you'll deploy and test it onWebSphere Application Server Express.

Deploy to WebSphere Application Server Express

Once you deploy your JRuby on Rails project to WebSphere Application ServerExpress, you can test it and initialize the database with test data. To deploy theapplication, you need to create a WAR file. Rake lets you to do that easily with thefollowing command: jruby -S rake war standalone: create.

Now to actually deploy the WAR file, point your browser to:http://localhost:9061/admin and log in to the WebSphere ApplicationServer admin console.

Use the username and password you entered previously (see Figure 7). Oncelogged in, expand the Applications heading on the left side, and click on Install NewApplication. This should bring you to the page in Figure 9.

Figure 9. Installing the film Web application

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 57

Page 18: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Fill the form out as seen in Figure 9, then click Next four times to proceed. Finally,click Finish. The application then installs, as noted in Figure 10.

Figure 10. Installation successful

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 18 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

To save the configuration and start the film application, click Save. You've nowdeployed the film Web application using the WebSphere Application Serveradministration console.

To easily redeploy the application, you can create a JACL script to automate theprocess of creating and deploying the WAR file. The first step is to create JACLscript to help with redeploying the films Web application to WebSphere ApplicationServer Express (see Listing 14).

Listing 14. A JACL redeploy script for the JRuby on Rails Web application(redeploy.jacl)

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 57

Page 20: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

> $AdminApp uninstall film_war> $AdminConfig save

> $AdminApp install "<path_to_ruby_film_project>/film.war"{-appname film_war -node <nodename> -cell <cellname>-server <servername> -contextroot /film -usedefaultbindings}

> $AdminConfig save

> set applicationManager [$AdminControl queryNames cell=<cellname>,node=<nodename>,type=ApplicationManager,process=<servername>,*]

> $AdminControl invoke $applicationManager "startApplication" film_war> $AdminConfig save

You will need to fill in everything between <...> with data pertaining to your ownsystem. To find out your <cellname>, look in the<websphere_install_dir>\profiles\AppSrv01\config\cells directory. You can find thecorresponding <nodename> in the<websphere_install_dir>\profiles\AppSrv01\config\cells\<cellname>\nodes directory.Lastly, to find your <servername>, look in the<websphere_install_dir>\profiles\AppSrv01\config\cells\<cellname>\nodes\<nodename>\serversdirectory.

Note that the greater than (>) characters in the redeploy.jacl script in Listing 14should not go in the file (see the redeploy.jacl in the source code package as anexample). Simply put, each line beginning with > specifies a single command andshould remain on a single line.

Next, create another script for Web deployment of the JSP pages you'll create later(see Listing 15).

Listing 15. A JACL redeploy script for the JSP pages (redeployJSP.jacl)

> $AdminApp uninstall jsp_war> $AdminConfig save

> $AdminApp install "C:/apps/rubyapps/jsp/jsp.war"{-appname jsp_war -node tandersonNode02 -cell tandersonNode02Cell-server server1 -contextroot /jsp -usedefaultbindings}

> $AdminConfig save

> set applicationManager [$AdminControl queryNamescell=tandersonNode02Cell,node=tandersonNode02,type=ApplicationManager,process=server1,*]> $AdminControl invoke $applicationManager "startApplication" jsp_war> $AdminConfig save

The same notes that applied to the JACL script in Listing 14 apply here in Listing 15.

When you're ready, execute these scripts with the two commands in Listing 16 (noteeach is on its own line).

Listing 16. Deploying the film Web application

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 20 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

jruby -S rake war:standalone:createcd c:\<path_to_WAS>\binwsadmin.bat -f c:\apps\rubyapps\redeployROR.jacl -user username -password password

The first command creates the WAR file, and the second deploys it to WebSphereApplication Server. Excellent! Your application will be ready for testing as soon asyou initialize the database.

Initializing the database

Now, before you test and make sure your application's XML features work correctly,initialize the database with some test data.

Point your browser to http://localhost:9081/film/films/new, and create a new film asshown in Figure 11.

Figure 11. Adding a new film through JRuby on Rails

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 57

Page 22: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 22 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Fill it in with any film data you wish, and click Create. You should then see the listpage (Figure 12).

Figure 12. New film successfully created and listed

Great! The new video is alive and well inside the database, and you should be ableto see it.

Next, test the built-in XML features of JRuby on Rails!

Testing the XML features of JRuby on Rails

JRuby on Rails has some cool features that allow you to get all the film entries fromthe database in XML format. This will work wonders later for the Ajax client that youwill build. To test, point your browser to the URL in Figure 13, and you'll also see theXML listing shown therein.

Figure 13. XML listing of films, care of JRuby on Rails

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 57

Page 24: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Next you'll learn how to access film entries individually. Point your browser to thefollowing URL: http://localhost:9081/film/films/<id>.xml, and replace <id> with the IDof the film entry that you just added (likely 1 if it was your first film entry, or you cansee it in the XML that you pulled up in your browser back in Figure 12). Figure 14shows the XML that will subsequently come up.

Figure 14. XML listing of a single film, care of JRuby on Rails

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 24 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

You'll use this functionality to access individual films in the Ajax client that you'reabout to build.

Next you'll work on creating JSP pages to capture XML data send from the Ajaxclient to update film entries, and to also create new ones.

Section 5. Developing the server side JSP pages

In a production environment, you'll want the most robust an environment possible toadd and edit information in the database. In all likelihood, this will mean Javaservlets, possibly using SpringMVC and Hibernate, to enhance security andreliability. You'll also want to use a Java parser, rather than manually examine thetext of the request.

All of that is beyond the scope of this tutorial. To simply demonstrate the connectionbetween the XML received and the database commands executed you'll create two

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 57

Page 26: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

simple JSP pages, one to add new films, and another to edit existing ones.

Adding new films

Here you create a new JSP page that your Ajax client will call and send XML data to,in order to add new film entries to the database.

Create a new file, new.jsp, and place it in the public/ directory of your film JRuby onRails application. Now define it, as in Listing 17.

Listing 17. Creating public/new.jsp

<%@ page import='java.io.*' %><%@ page import='java.util.*' %><%@ page import='java.sql.*' %><%@ page import='java.sql.Date' %><%@ page import='org.apache.derby.jdbc.EmbeddedDriver' %><%

if(request.getMethod().equals("POST")){

String result = "";try {

// try1 read the raw dataServletInputStream poststrm = request.getInputStream();

// get data from inputstreamint count;byte[] s = new byte[100];try {// try2

while ((count = poststrm.readLine(s, 0, 100)) > 0){

byte[] s2 = new byte[count];int k;for (k = 0; k < count; k++) {

s2[k] = s[k];}result = result + new String(s2);

}} catch (java.io.IOException e) {

out.print("Exception during processing of "+"raw POST data: ");

e.printStackTrace();}

} catch (java.io.IOException e) {out.print("Exception during attempt to read http"+

" input stream: ");e.printStackTrace();

}

String title =result.substring(result.indexOf("<title>")+7,result.indexOf("</title>"));

String url = result.substring(result.indexOf("<url>")+5,result.indexOf("</url>"));

String tags = result.substring(result.indexOf("<tags>")+6,result.indexOf("</tags>"));

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 26 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

String vibe = result.substring(result.indexOf("<vibe>")+6,result.indexOf("</vibe>"));

String dateadded = result.substring(result.indexOf("<dateadded>")+11,

result.indexOf("</dateadded>"));Date dadded = Date.valueOf(dateadded);

String notes =result.substring(result.indexOf("<notes>")+7,result.indexOf("</notes>"));

Driver driver = null;try {// try3

driver = (Driver)(EmbeddedDriver.class).newInstance();

} catch(Exception e) {out.println("Unable to load, " +

"instantiate, or register driver " + driver +": "+e.getMessage());

}

try {// try4

Connection conn = driver.connect("jdbc:derby:c:\\apps\\rubyapps\\"+

"film\\db\\development;",new Properties());

String sql = "insert into films "+"(title, url, tags, vibe, dateadded,

notes)"+"values (?, ?, ?, ?, ?, ?)";

PreparedStatement statement =conn.prepareStatement(sql);

statement.setString(1, title);statement.setString(2, url);statement.setString(3, tags);statement.setInt(4, Integer.parseInt(vibe));statement.setDate(5, dadded);statement.setString(6, notes);

statement.execute();

} catch(Throwable e) {e.printStackTrace();out.println(e.getMessage());out.println("Error executing query");out.write("error");

}

out.write("Success!");

}

%>

Note that this file won't do anything unless it gets a POST request. The next twonested try statements retrieve the RAW POST data, as sent from the Ajax client andconvert it to a Java string. The following six blocks of code parse the XML usingJava code to extract the new film data you need to create a new film entry in the

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 57

Page 28: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

database. The third try statement then grabs an instance of the Embedded Derbydriver, which you use to connect to the development version of the Derby databasein the fourth try statement. Here you also set up an INSERT INTOPreparedStatement, set each of the six variables, respectively, and execute."Success!" is then returned to the caller, in this case the Ajax client.

You'll test this code later when you add new films through the Ajax client.

Editing films

Now you'll create a new JSP file that you'll use to send XML data to through the Ajaxclient. This JSP file will then extract the relevant data and update the correspondingfilm entry in the database.

Create a new file, edit.jsp, and add it to the public/ directory in your JRuby on Railsapplication. Now define it, as in Listing 18.

Listing 18. Creating public/edit.jsp

...out.print("Exception during attempt to read http "+

"input stream: ");e.printStackTrace();

}

String id = result.substring(result.indexOf("<id>")+4,result.indexOf("</id>"));

String notes = result.substring(result.indexOf("<notes>")+7,result.indexOf("</notes>"));

String tags = result.substring(result.indexOf("<tags>")+6,result.indexOf("</tags>"));

String vibe = result.substring(result.indexOf("<vibe>")+6,result.indexOf("</vibe>"));

Driver driver = null;try {

driver = (Driver)(EmbeddedDriver.class).newInstance();

...Connection conn = driver.

connect("jdbc:derby:c:\\apps\\rubyapps\\"+"film\\db\\development;",new Properties());

String sql = "update films set vibe=?, notes=?, tags=? "+"where id=?";

PreparedStatement statement = conn.prepareStatement(sql);

statement.setInt(1, Integer.parseInt(vibe));statement.setString(2, notes);statement.setString(3, tags);statement.setInt(4, Integer.parseInt(id));

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 28 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

statement.execute();...

Note here that only the differences between edit.jsp and new.jsp are shown, soplease refer to new.jsp to fill in the blanks.

The data is extracted from the RAW post data just as before, except this time anUPDATE PreparedStatement is with fewer variables that need to be set (as notall fields in a film entry are modifiable). Executing the statement updates the filmentry in the database.

Next, you'll deploy the JSP pages to WebSphere Application Server Express.

Deployment

With JSP pages in hand, you're ready for deployment. Create the following directorystructure (see Listing 19).

Listing 19. JSP project file and directory structure

--+ jsp--- new.jsp--- edit.jsp----+ WEB-INF----- web.xml------+ lib------- derby-10.1.3.jar

Grab the Derby JAR from the same location as you did for the lib/java directory inthe film JRuby on Rails application. Now define the web.xml as in Listing 20.

Listing 20. Writing an empty web.xml file

<!DOCTYPE web-app PUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

</web-app>

Now zip up all the files in the jsp project directory, and rename the created file tojsp.war. Now you're ready to deploy the JSP project to WebSphere ApplicationServer Express. Go back to the Install New Application page in Figure 15.

Figure 15. Installing the JSP project

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 57

Page 30: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Fill out the form as in Figure 15, click Next four times, and Finish once to open theInstallation successful page (Figure 16).

Figure 16. Installation successful

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 30 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 31: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Click Save to save the configuration and start the JSP Web application. You shouldsee the following started applications, as in Figure 17.

Figure 17. Live applications

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 57

Page 32: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

You can now redeploy this project. Rezip the jsp directory, rename it to jsp.war, andtype the two commands in Listing 21 (each on a single line).

Listing 21. Redeploy the project

cd c:\<path_to_WAS>\binwsadmin.bat -f c:\apps\rubyapps\redeployJSP.jacl -user username -password password

Section 6. Developing the Ajax client

With the JSP and Ruby code set up to help facilitate your Ajax client, you're ready tobegin development! This section shows you how to develop the complete Ajax clientthat you saw in Figure 1.

Before moving on, however, I'd like to draw your attention to a difference between

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 32 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 33: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

this project and a production application. To show what actually happens under thecovers, so to speak, you'll manually handle Ajax requests. For your actualapplication, you will likely want to use one of the many frameworks available, suchas Prototype. These libraries account for browser differences and make your lifemuch easier.

But in the meantime, look at what actually happens.

Retrieve and send XML and HTML data

First, set up the core send/receive functions that you'll use throughout your Ajaxclient. Create a new file, downloadurl.js, and define it, as in Listing 22.

Listing 22. Retrieving XML and HTTP support functions

function loadXML(fileName){var xmlDoc;if (window.ActiveXObject){

xmlDoc=new ActiveXObject("Microsoft.XMLDOM");}else if (document.implementation &&

document.implementation.createDocument){xmlDoc=document.implementation.createDocument("","",null);

}else{

alert('Unsupported browser');}xmlDoc.async=false;xmlDoc.load(fileName);return(xmlDoc);

}

function getRequestObject(){var request;var browser = navigator.appName;

if(browser.indexOf("Microsoft") > -1)request = new ActiveXObject("Microsoft.XMLHTTP");

elserequest = new XMLHttpRequest();

return request;}

function sendData(url, data, func) {request = getRequestObject();

request.open("POST", url, true);request.setRequestHeader("Content-Type",

"application/x-www-form-urlencoded");

request.onreadystatechange = function(){if (request.readyState == 4){func(request.responseText);

}};request.send(data);

}

function downloadUrl(url, func) {

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 57

Page 34: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

request = getRequestObject();

request.open("GET", url, true);request.onreadystatechange = function(){

if(request.readyState == 4){func(request.responseText);

}};request.send(null);

}

Here you have four functions. Essentially, the first one fetches XML into a DOMdocument object and returns it to the caller. With it, you'll list all film entries, as wellas individual film entries. The second is a helper function to the third and fourthfunctions that retrieves the appropriate XMLHttpRequest object based on thecurrent browser. The third function sends RAW XML data to the edit.jsp and new.jspfiles when adding new film entries and editing existing ones. The fourth functiondeletes existing entries in calls to the JRuby on Rails destroy action.

Next you'll begin development of the core HTML file where you'll also add severalJavaScript functions throughout the rest of this tutorial.

The core HTML and DIV tags

Where you hear Ajax mentioned, you will see div tags mentioned because they're aconvenient container for content that you can identify with an id attribute. Next, you'llcreate an HTML file to house the Ajax client. Delete the current index.html file in thepublic/ directory, create a new one, and begin to define it as in Listing 23.

Listing 23. The main HTML page

<html><head><title>Ajax Film Lover's Web Page</title>

<script src="downloadurl.js" type="text/javascript"></script>

<script type="text/javascript">...</script>

</head>

<body>

<div id="main" style="margin:0px auto; width: 1000px;"><div id="header" style="text-align: center;"><h1>Welcome Film Lovers!!</h1>

</div>

<div id="main-inner">

<div id="HTMLcontent" style="margin-top: 50px; width: 1000px;"></div>

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 34 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 35: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

<div id="footer"style="text-align: center; clear:both; padding-top: 50px;">

&copy; Film Lovers International Inc.<br/></div>

</div>

<script type="text/javascript">list();

</script></body>

</html>

Note here the downloadurl.js is included into the HTML. Then where you see the "..."is where you'll add all the JavaScript functions from now until the end of this tutorial.

Here the important div tag, where you'll place all the interactively updated HTML, isthe HTMLcontent div tag.

Next you start to develop the core Ajax functions.

Listing all films

Begin in natural order and list all film entries currently in the database. This willprovide other links where you can create new film entries, or where you can display,edit, or delete existing entries.

Continue to define the index.html file, as in Listing 24.

Listing 24. Listing all films through JavaScript and JRuby on Rails

<script type="text/javascript">

var filmsbaseurl = "http://localhost:9081/film/films";var editbaseurl = "http://localhost:9081/jsp/edit.jsp";var newbaseurl = "http://localhost:9081/jsp/new.jsp";

function displayShowEdit(name, value){return '<b>' + name + ':</b><br/>' + value +

'<br/><br/>';}

function displayEditNew(name, xmlname, value, size, rows){if(name != 'Notes')

return '<b>' + name + ':</b><br/><input size="'+ size + '" name="' + xmlname + '" value="' + value + '"/><br/><br/>';else

return '<b>' + name + ':</b><br/><textarea cols="'+ size + '" rows="' + rows + '" name="' + xmlname + '">' + value+ '</textarea><br/><br/>';

}

function displayShow(name, value){if(name != 'URL')

return '<b>' + name + ':</b> ' + value + '<br/>';else

return '<b>' + name + ':</b> <a href="' + value + '">'

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 57

Page 36: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

+ value + '</a><br/>';}

function displayList(name, value){if(name != 'URL')

return '<td>' + value + '</td>';else

return '<td><a href="' + value + '">' + value + '</a></td>';}

function displayButton(name, func, id){return '<input name="' + name + '" type="button" value="' + name + '"

onclick="javascript:' + func + '(' + id + ')"/><br/><br/>';}

function displayLink(name, id){return '<a href="javascript:' + name + '(' + id + ')">' + name + '</a>';

}

function getChildValue(item, name){return item.getElementsByTagName(name)[0].firstChild.nodeValue;

}

function processXML(xmlDoc, type){var tagStr = '';var items = '';var tags = '';var url = '';var tagName = '';var item = '';var vibe = '';var dateadded = '';var notes = '';var id = '';var title = '';var i = 0;if(type == 'list'){

tagStr = '<table border="1px"><tr><th>Title</th>'+'<th>Url</th><th>Tags</th>'+'<th>Vibe</th><th>Date Added</th>

<th>Notes</th></tr>';items = xmlDoc.getElementsByTagName("film");for (i = 0; i < items.length; i++) {item = items.item(i);title = getChildValue(item, "title");url = getChildValue(item, "url");tags = getChildValue(item, "tags");vibe = getChildValue(item, "vibe");dateadded = getChildValue(item, "dateadded");notes = getChildValue(item, "notes");id = getChildValue(item, "id");tagStr = tagStr + "<tr>" +

displayList('Title', title) +displayList('URL', url) +displayList('Tags', tags) +displayList('Vibe (number between 1 and 10 to '+

'specify how much you like the video)', vibe) +displayList('Date Added (YYYY-MM-DD)', dateadded) +displayList('Notes', notes) +'<td>' + displayLink('show', id) + '</td>' +'<td>' + displayLink('edit', id) + '</td>' +'<td>' + displayLink('deleteMe', id) + '</td></tr>';

}tagStr = tagStr + '</table><br/>' + displayLink('neww', '');

tagStr = tagStr +'</table><br/><a href="javascript:neww()">New Film</a>';

return tagStr;

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 36 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 37: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

}...}

function list(){var url = filmsbaseurl + ".xml";var res = processXML(loadXML(url), "list");document.getElementById("HTMLcontent").innerHTML = res;

}...

</script>

First, hardcode the three base URLs that you'll use constantly, as you'll modify thembased on the user input from the Ajax client. Next, create several helper functions todisplay various HTML elements, and the one (getChildValue) to get the textvalue elements in the XML file.

The next function, processXML, takes in a DOM Document and type. If the type islist (as it will be for listing all films) it sets up a table for displaying the XML data.Next the script fetches all film children from the XML document, and displays allfields in the table with Show, Edit and Delete links. It then returns the table alongwith a link to create a new film entry.

Lastly, note the main list() function sets up the proper link to grab the XML fromthe JRuby on Rails application, storing the response in res, and setting theHTMLcontent div to what's returned from the processXML function.

Check it out in action in Figure 18.

Figure 18. Listing all films

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 57

Page 38: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Here you can see all the links just created. Note that they aren't defined yet, and sothe page might or might not load due to these undefined functions.

Next you'll define the show function, to allow the display of individual film entries.

Showing individual films

Now you can list film entries. With the functionality you add here, you can view themindividually. Continue to edit the processXML function in the index.html file, as inListing 25.

Listing 25. Displaying single films using JavaScript and JRuby on Rails

...

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 38 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 39: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

tagStr = tagStr +'</table><br/><a href="javascript:neww()">New Film</a>';

return tagStr;}else if(type == 'show'){

items = xmlDoc.getElementsByTagName("films");item = items.item(i);title = getChildValue(item, "title");url = getChildValue(item, "url");tags = getChildValue(item, "tags");vibe = getChildValue(item, "vibe");dateadded = getChildValue(item, "dateadded");notes = getChildValue(item, "notes");id = getChildValue(item, "id");tagStr = displayShow('Title', title) +

displayShow('URL', url) +displayShow('Tags', tags) +displayShow('Vibe (number between 1 and 10 '+

'to specify how much you like the video)', vibe) +displayShow('Date Added (YYYY-MM-DD)', dateadded) +displayShow('Notes', notes) +'<br/>' + displayLink('edit', id) +'<br/>' + displayLink('list', '');

return tagStr;}

...}

function show(num){var url = filmsbaseurl + "/"+num+".xml";var res = processXML(loadXML(url), "show");document.getElementById("HTMLcontent").innerHTML = res;

}...

The new portion in the processXML function, where type == 'show', is more orless similar to what happens when type == 'list', except here you know thereis only a single film entry and there is no for loop. The big change comes in theshow() function where the ID chosen to look up is appended to the filmsbaseurlfollowed by ".xml". The returned HTML data displaying the individual film entry isfinally set to display in the HTMLcontent div.

See the show function in action in Figure 19.

Figure 19. Displaying an individual film

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 57

Page 40: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

And there you have it! You can, from here, go back to the list/index page, or edit theindividual film entry, which you'll code next.

Editing film entries

Now that you can list and view film entries, it's time to be able to edit them, andcomplete the processXML function. Continue to edit the processXML function inthe index.html file, as in Listing 26.

Listing 26. Editing a film entry using JavaScript

...

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 40 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 41: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

'<br/><br/><a href="javascript:edit(' + id +')">Edit<br/><a href="javascript:list()">Index'+'<br/><br/>';

return tagStr;}else if(type == 'edit'){

items = xmlDoc.getElementsByTagName("films");item = items.item(i);title = getChildValue(item, "title");url = getChildValue(item, "url");tags = getChildValue(item, "tags");vibe = getChildValue(item, "vibe");dateadded = getChildValue(item, "dateadded");notes = getChildValue(item, "notes");id = getChildValue(item, "id");tagStr = displayShowEdit('Title', title) +

displayShowEdit('URL', url) +displayEditNew('Tags', 'tags', tags, 50) +displayEditNew('Vibe (number between 1 and 10 to '+

'specify how much you like the video)','vibe', vibe, 2) +

displayShowEdit('Date Added (YYYY-MM-DD)', dateadded) +displayEditNew('Notes', 'notes', notes, 50, 10) +displayButton('save', 'saveedit', id) +'<br/>' + displayLink('show', id) +'<br/>' + displayLink('list', '');

return tagStr;}

}

function edit(num){var url = filmsbaseurl + "/"+num+".xml";var res = processXML(loadXML(url), "edit");document.getElementById("HTMLcontent").innerHTML = res;

}...

This time (in the processXML function) when type == 'edit', code executioncontinues here. This portion of code is much like the Show functionality, except herethree of the fields are editable (tags, vibe, and notes), and a Save button appearsthat calls the saveedit function.

See it in action in Figure 20.

Figure 20. Editing an existing film

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 57

Page 42: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 42 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 43: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Feel free to make some edits to your film entry. The Save button won't work yet, butthat's what you'll work on next.

Saving edited films

The form for editing films is live, but not hooked to anything. Now you'll write thesaveedit function to connect to the edit.jsp file sitting on WebSphere ApplicationServer Express, which will in turn save the new data into the film entry. Continue todefine the index.html file, as in Listing 27.

Listing 27. Saving edited film data back to the edit.jsp file using JavaScript

...function saveedit(num){var url = editbaseurl;

inputTags = document.getElementById("HTMLcontent").getElementsByTagName("input");

var xmldata = '<film><id>' + num + '</id>';for (var i = 0; i < inputTags.length; i++) {

var tag = inputTags.item(i);if(tag.name !== 'save'){xmldata = xmldata + "<" + tag.name + ">" + tag.value +

"</" + tag.name + ">";}

}

inputTags = document.getElementById("HTMLcontent").getElementsByTagName("textarea");

var name = inputTags.item(0).name;var value = inputTags.item(0).value;xmldata = xmldata + "<" + name + ">" + value + "</" + name + ">";xmldata = xmldata + '</film>';

sendData(url, xmldata, reload2);}

function reload2(text){alert(text);setTimeout("list()", 500);

}...

Here the URL to call is the editbaseurl pointing to the edit.jsp file. The nextseveral lines including the for loop grabs all HTML elements of type input from theHTMLcontent DIV, and places them in an XML document (ignoring the Save button).The next several lines after the for loop grabs the textarea field from the HTTP toadd the notes field to the XML document. With the XML document complete, thedata is sent to the edit.jsp file with the call to sendData with reload2 set as thecallback URL. When this URL is called, the result displays in an alert box ( Figure21).

Figure 21. Edit confirmation

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 43 of 57

Page 44: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 44 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 45: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Click OK to bring up the index/list page where all film entries display in a table asbefore (see Figure 22).

Figure 22. Listing the updated film

The film entry is updated. Now you'll add the functionality to delete film entries.

Deleting film entries

Since you can edit film entries, why not delete? That's what you'll do here, and goodnews, deleting film entries is the easiest of all the tasks. Continue to define theindex.html file, as in Listing 28.

Listing 28. Deleting entries through JavaScript and JRuby on Rails

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 45 of 57

Page 46: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

...function reload(){setTimeout("list()", 500);

}

function deleteMe(num){var url = filmsbaseurl + "/destroy/"+num;downloadUrl(url, function(response) {});reload();

}...

Here you define the deleteMe function that sets up the URL needed to destroy thespecified film entry. However, now the downloadUrl function is called with adummy callback function that does nothing. A reload happens after 500milliseconds, enough time for the entry to be deleted, and then the list() functionis called, reloading the film entries, as in Figure 23.

Figure 23. Deleting a film entry

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 46 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 47: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Now you only lack the ability to add new films. You'll work on that next.

Adding new films

With the ability to do everything but add new film entries, it's about time to add thisfunctionality. Continue to define the index.html file, as in Listing 29.

Listing 29. Adding new entries through JavaScript

...function neww(){

tagStr = displayEditNew('Title', 'title', '', 50) +displayEditNew('URL', 'url', '', 50) +displayEditNew('Tags', 'tags', '', 50) +displayEditNew('Vibe (number between 1 and 10 to '+

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 47 of 57

Page 48: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

'specify how much you like the video)','vibe', '', 2) +

displayEditNew('Date Added (YYYY-MM-DD)','dateadded', '', 50) +

displayEditNew('Notes', 'notes', '', 50, 10) +displayButton('save', 'savenew', '') +displayLink('list', '');

document.getElementById("HTMLcontent").innerHTML = tagStr;}...

Note here that you simply set the HTMLcontent div to display a form for enteringnew film data (see Figure 24).

Figure 24. Adding a new film

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 48 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 49: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 49 of 57

Page 50: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

But beside that, the neww() function is similar to the edit portion of theprocessXML function except that here nothing has a previous value, and every fieldgets its own input box or textarea. Next you'll define the savenew() function, thefunction tied to the Save button.

Saving new film data

Like the edit film entry form, here you'll send the new form to the new.jsp file ratherthan to edit.jsp. To complete the definition of the index.html file, add one lastfunction, as in Listing 30.

Listing 30. Saving new film data back to the new.jsp file using JavaScript

...function savenew(){var url = newbaseurl;

inputTags = document.getElementById("HTMLcontent").getElementsByTagName("input");

var xmldata = '<film>';for (var i = 0; i < inputTags.length; i++) {

var tag = inputTags.item(i);if(tag.name !== 'save'){xmldata = xmldata + "<" + tag.name + ">" + tag.value +

"</" + tag.name + ">";}

}

inputTags = document.getElementById("HTMLcontent").getElementsByTagName("textarea");

var name = inputTags.item(0).name;var value = inputTags.item(0).value;xmldata = xmldata + "<" + name + ">" + value + "</" + name + ">";xmldata = xmldata + '</film>';

sendData(url, xmldata, reload2);}...

Note that this function is very much like saveedit(), except here you send theRAW XML data to new.jsp instead of edit.jsp, and the XML data contains data foreach of the six fields required to create a new film entry. When the call tosendData() comes back, a confirmation displays (Figure 25).

Figure 25. Adding a new film confirmation

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 50 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 51: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 51 of 57

Page 52: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Click OK to return the view to the index/list area where you can see the new filmentry (Figure 26).

Figure 26. Listing the new film

Now you can redeploy the film JRuby on Rails application to include your newlycreated Ajax client. Type the commands in Listing 31 (again place each commandon its own line).

Listing 31. Redeploying the film JRuby on Rails application to include the Ajaxclient

cd c:\<path_to_WAS>\binwsadmin.bat -f c:\apps\rubyapps\redeploy.py -user username -password password

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 52 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 53: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

You now have a fully functioning Ajax client to manage your online film databasewith the help of JRuby on Rails and JSP programming!

Section 7. Summary

Wrapup

You successfully mastered how to run and communicate XML between your Ajaxclient and Java and JRuby on Rails applications on a Java application server,deployed within the same Web application! You also created a slick fully functionalAjax client that can create new films, edit, delete, and display through XMLcommunication using two different programming languages (Ruby and Java) withoutever again having to load a new HTML page from the server.

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 53 of 57

Page 54: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Downloads

Description Name Size Download method

Example source code x-jrorajax.zip 11KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 54 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 55: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

Resources

Learn

• Riding the Rails with WebSphere: Part 1: Combine Ruby on Rails withWebSphere Application Server and get rapid development with security,scalability, and reliability (Ryan Shillington, developerWorks, January 2008):Check out this useful article for more information on using Ruby on Rails withWebSphere and why you might want to join them together

• Ruby on Rails screencasts: Discover a collection of screencasts covering Rubyon Rails.

• Crossing borders: What's the secret sauce in Ruby on Rails? (Bruce Tate,developerWorks, May 2006): Read an article that explores the compromisesand design decisions that went into making Rails so productive within its niche.

• IBM WebSphere Application Server zone: Find the secure, scalable, resilientapplication infrastructure you need for SOA in the WebSphere ApplicationServer, the foundation of the IBM WebSphere software platform

• Overview on DB2's XML Capabilities (Cindy Wong, developerWorks, November2003): Explore the SQL/XML functions available with DB2 UDB version 8 andthe DB2 XML Extender.

• XML programming with SQL/XML and XQuery: See this IBM research paper onan integrated database architecture that enables SQL applications with XMLextensions as well as XQuery applications to operate on the same data. Thearchitecture allows for a seamless flow from relational data to XML and back.

• Introduction to XML tutorial (Doug Tidwell, developerWorks, August 2002):Need a more basic introduction to XML? Try the this tutorial and othereducational offerings, which cover the most fundamental topics.

• XML and Java technology: A return to basics (Brett McLaughlin,developerWorks, October 2007): Read this article that revisits some XMLbasics, from document structure to the age-old attributes versus elementsissue.

• Reading and writing the XML DOM in PHP (Jack Herrington, developerWorks,December 2005): Explore three methods for reading XML: the DOM library,SAX parser, and regular expressions.

• IBM XML certification: Find out how you can become an IBM-CertifiedDeveloper in XML and related technologies.

• XML technical library: See the developerWorks XML Zone for a wide range oftechnical articles and tips, tutorials, standards, and IBM Redbooks.

• developerWorks technical events and webcasts: Stay current with technology in

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 55 of 57

Page 56: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

these sessions.

• The technology bookstore: Browse for books on these and other technicaltopics.

• Podcasts: Tune in and catch up with interesting interviews that include IBMtechnical experts.

Get products and technologies

• JRuby: Get the Java powered Ruby implementation.

• WebSphere Application Server Express: Get a trial version of WebSphereApplication Server Express V6.1.

• IBM trial software for product evaluation: Build your next project with trialsoftware available for download directly from developerWorks, includingapplication development tools and middleware products from DB2®, Lotus®,Rational®, Tivoli®, and WebSphere®.

Discuss

• Participate in the discussion forum for this content.

• XML zone discussion forums: Participate in any of several XML-relateddiscussions.

• developerWorks XML zone: Share your thoughts: After you read this article,post your comments and thoughts in this forum. The XML zone editorsmoderate the forum and welcome your input.

• developerWorks blogs: Check out these blogs and get involved in thedeveloperWorks community.

About the author

Tyler AndersonTyler Anderson has graduated with a degree in computer science in 2004 and aMaster of Science degree in computer engineering in December, 2005, both fromBrigham Young University. Tyler is currently a freelance writer and developer forBackstop Media.

Trademarks

Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered

developerWorks® ibm.com/developerWorks

Use JRuby on Rails and XML to supercharge Ajax with a Java Application ServerPage 56 of 57 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 57: Use JRuby on Rails and XML to supercharge Ajax with a Java ...entsphere.com/pub/pdf/x-jrorajax-pdf.pdf · • Set up your JRuby project to use Derby as the database • Get a working

trademarks or trademarks of Adobe Systems Incorporated in the United States,and/or other countries.IBM, the IBM logo, ibm.com, DB2, developerWorks, Lotus, Rational, Tivoli,WebSphere, and pureXML are trademarks of IBM Corporation in the United States,other countries, or both.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.Other company, product, or service names may be trademarks or service marks ofothers.

ibm.com/developerWorks developerWorks®

Use JRuby on Rails and XML to supercharge Ajax with a Java Application Server© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 57 of 57