Saturday, 30 January 2010

Using Java Applets

I had a system that I wanted to create where the user could do some complicated manipulation of data, before sending the results to the database. It seemed to me that a Java applet would be the best way to interface with the user, but how to interface the applet with Rails?

The applet itself was very straightforward. It picks up the initial data from two parameters, rt and pc (each a list of floats, combining to make pairs of data). I also needed a public class that would return the results in a string.
package railsapplet;

public class MyApplet extends javax.swing.JApplet {
MyData data;

@Override
public void init() {
String rt = getParameter("rt");
String pc = getParameter("pc");
data = new MyData(rt, pc);
// Set up UI
}

// etc.

public String getOutput() {
return data.getOutput();
}
}

I packaged my Java in a jar file, insides public/applets. My view needed to reference that applet.
<applet codebase="http://<%= ApplicationController::SITE %>/applets"
width="400" height="400"
code="railsapplet.MyApplet.class" archive="railsapplet.jar"
name="myapplet"
id="myapplet"
align="center">
<param name="rt" value="<%= @rt.join(" ") %>">
<param name="pc" value="<%= @pc.join(" ") %>">
<hr />
If you were using a Java-enabled browser,
you would see an applet right now.
<hr />
</applet>

The code base points to the public/applets folder (using a constant, SITE, for the domain and port). The two variables @rt and @pc are arrays of floats, which are compiled into strings. These can then be picked up by the applet.

Okay, so I have got the data from the database, and into my applet. The uses plays around with it, then wants to send the results back to the database. There are number of ways to get data out of an applet. One such is to use a JSObject in the applet to communicate with elements on the web page. However, the easiest way is to use JavaScript.

This JavaScript function will search the page for the "myapplet" element, then call the getOutput() method on it (retrieving the data from the applet). The string is placed in the "output" element.
<script language="JavaScript">
function getOutput() {
document.getElementById('output').value = document.getElementById('myapplet').getOutput();
}
</script>

To get it all to work, you need a little form on the web page, with a button and a hidden input. Click the button and the results will go on the hidden input, and the form then submitted.
<% form_tag :action => :glc_update do %>
<input type="hidden" name="output" id="output" />
<button type="button" onclick="getOutput(); submit();">Okay</button>
<% end %>

After that, it is up to Rails to examine the string, extracting the results.


Struggling with Ruby: Contents Page

1 comment:

Lianne Marie said...

It would be really helpful if you could post a link to a repository with your code. I'm trying to do a very similar thing myself, and I'd love to see the java code.