Java RMI in Practice

Software Careers Fall 1997 Dr. Dobb's Journal

by Martin Remy


Martin is an Internet development consultant based in Denver, Colorado. He can be reached at martin@remylabs.com.
Listings
Insert In my article "Design Patterns, Java, and Web Development" (Dr. Dobb's Journal, June 1997), I described a mode of using Java applets "behind the scenes" in web applications. These applets, which I call "worker applets," are nonvisual components that provide state and session management, as well as connectivity to databases and other networked resources. Usually, worker applets are used in web applications where the burden of visual presentation falls almost entirely on HTML. If visual Java applets or ActiveX controls are a part of the design, it can be more efficient to include the worker code there. However, Java GUI applications often lack a certain fluidity when embedded in web pages, and even though the browser wars have taken their toll on its portability (through competing nonstandard HTML extensions), HTML has become remarkably capable of delivering compelling presentations in a portable and efficient manner. In this article, I'll expand upon worker applets by looking ahead to what the next generation of browsers has to offer Java programmers and by examining the merits of HTML as a presentation vehicle.

As a computing platform, the Web has not been home to the best designs and software architectures. Nor have good development practices been facilitated by the languages, tools, and technologies we've used to develop web apps over the years. (If you've found yourself cutting-and-pasting dozens of lines of JavaScript from one HTML page to another because a certain tag is not available in a certain browser, then you know what I mean.) As a first step toward delivering interactive applications on the Web, we used CGI. Millions of custom scripts were written to wire HTML pages to behind-the-firewall services and create applications. Later, browser scripting exacerbated the tendency to avoid reuse in web apps at all costs, resulting in further millions of scripts holding together applications by sheer willpower rather than sound design. However, scripts (including compiled scripts written in C) were all we had, and even though Java and ActiveX, along with a number of server-side alternatives to CGI, have arrived on the Web, scripts remain important ingredients in crafting a good interactive application for the Web.

Over the last couple of years, objects have found their way to the Web, facilitating better architectures and designs. Following the first glimpse of reusable binary objects on the Web in the form of Java applets, we've seen ActiveX controls on the server as well as the client, and a number of innovative alternatives to CGI, including Java servlets. With the release of Netscape Navigator 4.0 (part of Netscape Communicator), which is in Preview Release 5 at this writing, the many new features of Java 1.1 as well as CORBA/Internet Inter-ORB Protocol (IIOP) will be available for the first time in a browser.

The Architecture of Web Applications

To place these advances in a concrete development context, let's suppose you need to build a web application that delivers a technical interview to prospective employees who are beginning the hiring process at a company. The online interview (see Figure 1) consists of a series of multiple choice questions, and will serve as a technical prescreening before developers interview the candidate for six or seven hours. The interview must be flexible enough to incorporate questions from a number of different subject areas, and it should produce a randomized but fair set of questions. The interview must also be delivered in a visually compelling way, since it may form the candidate's first impressions of the company.

Given enough Jolt Cola and browser cookies, these goals are achievable by any of the technologies I've enumerated. But using Java 1.1's Remote Method Invocation (RMI), you can craft a solution that is easy to design, easy to build, and easy to maintain. In this example, I use RMI as opposed to CORBA, because I have the luxury of writing the remote object from scratch in Java. RMI is also relatively simple to use and serves a small project like this one well. RMI requires the definition of a Java interface, which will be used by the client program as the type of the remote object. A server program instantiates an object that implements this interface, and binds it to the RMI registry, which functions as the daemon process for RMI requests. The client program, upon discovering the RMI server and its objects, is able to invoke methods of the remote object as if it were local-the transport layer having been encapsulated by the RMI system. There is, of course, some awareness of the remote nature of the object, such as the fact that its methods may throw RemoteExceptions. And since, among other architectural considerations, remote method arguments are serialized by the RMI system, you should think twice about passing large objects as arguments to remote methods.

The remote interface in the interview application is an InterviewManagerInterface (see Listing One; listings begin on page 34), which requires the methods startInterview(), getCurrentQuestion(), storeResponse(), and advance(). This interface, which looks like an object to the client, can encapsulate a number of complex behaviors in the selection and sequencing of questions, as well as the tracking of responses. The class implementing this interface is InterviewServer; see Listing Two.

This class exists specifically to produce remote objects. It implements some state knowledge, so that the client (a worker applet that I'll discuss in more detail shortly) can know which question to pose next, and can recover from interrupted interviews (as might result from the candidate's surfing to another site during the interview). The class InterviewServer does not, however, implement the logic for generating a set of interview questions and storing the candidate's responses. This is done by a class called InterviewPlan (see Listing Four), which is quite simple in the example, but is poised to implement arbitrarily clever ways of selecting questions (as well as creative ways for persistently storing interrupted interviews so that these could be yielded up to an InterviewServer by a static method, for example). Note that while the listings compile under JDK 1.1.2, and were tested in smaller units, I was unable to test the entire application because Navigator 4.0, in Preview Release 5, is unable to recognize javakey-signed applets as signed. The listings should serve as an architectural template, and they include enough comments to inspire more complex applications built on the same design principles.

The Interview Worker Applet

The browser side of the interview application is driven by a worker applet, InterviewApplet (see Listing Three), which is contained in a hidden frame called "jframe." JavaScript calling the applet's methods from the main question frame "qframe" will refer to it as parent.jframe.document.InterviewApplet. The applet's init() method performs the lookup of the RMI server that contains the InterviewServer, registered by the name INTERVIEW_MGR. The start() method resets all local state information about the interview, and places a login form in the main frame. start() will only be called by the browser when the applet's containing frame is redrawn. A redraw would mean that the frameset has been reloaded, which indicates, in turn, that the user is either entering or reentering the application. The login form contains a JavaScript directive to call the applet's login() method when an interview ID has been submitted. The login() method will call the remote object's startInterview() method, and unless an exception is thrown, showCurrentQuestion() will be called. This method shows the next question as an HTML page in the main frame. If the interview was interrupted, or if the user bookmarked an already answered question, the InterviewPlan will cause showCurrentQuestion() to show the next unanswered question. The applet also implements the method verifyPage(), which is called by the onLoad event handler of each question document. This method verifies that the given document name is in fact the current one, and replaces it with the current page if it isn't.

The decision to use HTML, rather than making our applet visible and displaying the questions in its container, is based on several factors. The most important of these is flexibility. If you were required simply to show the text for each question, along with an icon or two, then presenting the questions in an applet would be simple. But HTML gives you the opportunity to embrace a much wider range of presentation styles without building a custom presentation framework in Java. This flexibility doesn't come without a price, because we have to require certain behaviors of HTML pages, such as calling the worker applet's respondAndAdvance() method when a response is submitted by the user, and calling verifyPage() in the onLoad event. But this is a small price to pay for the use of any number of plug-ins, VRML, dynamic HTML, layers, and all future enhancements to HTML. Browser plug-ins can often provide a good alternative to writing presentation code in Java. Plug-ins have an advantage over visual applets in that the code is already resident on the client machine and the presentation can be encoded in a very compact manner. Some plug-ins support streaming of content while it is being rendered in the browser. A technical interview is perhaps not the best showcase for these features (as my less-than-creative rendition in Figure 1 confirms), but there are many applications that can benefit from an HTML presentation managed by a worker applet. A second reason for using HTML rather than Java is maintainability. In the present architecture (with appropriate version-control procedures), it becomes easy for someone to swap out a question, or to rework a question's presentation using an HTML editor.


Question 7, C++

      One of the differences between structs
      and classes in C++ is:

      a. Structs cannot contain functions

      b. Default access in a struct is public

      c. You can't fail structs.

      ( )a  ( )b ( )c

Figure 1: Exmple online interview form.

Communication between the question document and the applet is straightforward. The applet exposes the methods already listed as public. Upon loading, the HTML document in the question frame (see Listing Five) calls the applet's verifyPage() method to enforce the correct order of questions. The questions may be multiple choice or yes/no questions, but the applet's respondAndAdvance() method must be called with an integral value when the user selects a response. The only page exempt from this requirement is the "interview concluded" page, which might instead contain hyperlinks to the company's public web site, or contact information for human resources staff. If the applet is not yet loaded when one of its methods is called by JavaScript, the browser will report a scripting error. There are several ways of preventing or dealing with this problem. Some of them are more effective and portable than others, although they usually exhibit these qualities in inverse proportions. I have not implemented any such measures in the listings, because they clutter the central concepts (for a solution, see my article, "Design Patterns, Java, and Web Development," Dr. Dobb's Journal, June 1997). The JavaScript in this example is deliberately sparse, since the design encapsulates control functionality nicely in the applet and the remote object. The interview applet is, in essence, a slide show controller with strict flow rules. Another feature of the present design is that the web server is not executing application code. Since I have off-loaded the server-side application logic to the RMI server, the web server is free to do what it does best, which is deliver content.

HTML and Object-Oriented Web Development

For a while now, there has been a movement to outfit web servers with application programming frameworks such as Active Server Pages and LiveWire. While useful, the script-based nature of these frameworks can make it difficult to achieve reuse and its attendant productivity gains. Some object-based server application frameworks have also emerged, such as JavaSoft's Servlet API. Servlets represent a big leap forward for object-oriented web development. However, they don't free you from the HTTP GET metaphor of programming web applications one HTML page or frameset at a time. This metaphor does not encourage the use of Java applets and ActiveX controls in modes other than the familiar embedded visual one. Worker applets, on the other hand, can be full-fledged software components that enable client/server and distributed computing based on a generic client-the web browser. By making use of the browser, you preserve an important contribution of the Web to human computer interaction-HTML.

There are many poorly designed HTML pages on today's web; but in the hands of creative professionals, HTML-along with just enough browser scripting-can be a powerful presentation vehicle. Soon, push clients may displace web browsers and their applets. What is being called "push," however, is sometimes nothing more than a "pulled" application that subsequently performs its own managed, automatic pulling of content from the Web-a worker applet in disguise. There are truly innovative push technologies, like Marimba's Castanet, but Castanet is much more important as a model infrastructure for delivering and maintaining applications than for content delivery. And while a new push vendor surfaces almost weekly, it is important to remember that the Web (along with HTML) was crafted as an open platform. HTML's academic heritage means that it was not invented to sell operating systems or browsers, but rather as the presentation language for a vision of how human communication using networked computers should take place. As a GUI application, the browser is unique, because it permits an infinite variety of interfaces to an infinite variety of applications. And while building these applications has not yet been possible in a productive, object-oriented way, a number of object-enabling technologies are now available, including Java 1.1 and IIOP in Navigator 4.0. Applets finally provide early glimpses of what a fully object-based web might look like. But in a connected world, applets are only half of the story. Servlets and other object-based server technologies will be the real workers in the Web of the future.

DDJ