Getting Started with Java IDL: Developing a Client Applet


This topic introduces the basics of writing a CORBA client applet. An applet is a Java program to be included in HTML pages and executed in Java-enabled browsers. Developing a CORBA client applet is very similar to developing a CORBA client application, except that in the applet the code appears in the init() method rather than in the main() method. You can run the applet from the Applet Viewer or from a Web browser that is compatible with J2SE v1.3. The steps in this lesson are:

  1. Creating the Applet
  2. Understanding the Applet
  3. Compiling and Running the Hello World Applet

To see a completed version of HelloApplet.java, follow the link.

Creating the Applet

To create HelloApplet.java,

  1. Create a file named HelloApplet.java in the main project directory, Hello, using your favorite text editor.

  2. Enter the following code for HelloApplet.java in the text file. The following section, Understanding the Applet, explains each line of code in some detail.

    // The package containing our stubs.
    import HelloApp.*;
    
    // HelloClient will use the naming service.
    import org.omg.CosNaming.*;
    
    // The package containing special exceptions thrown by the name service.
    import org.omg.CosNaming.NamingContextPackage.*;
    
    // All CORBA applications need these classes.
    import org.omg.CORBA.*;
    
    // Needed for the applet.
    import java.awt.Graphics;
    
    
    public class HelloApplet extends java.applet.Applet
    {
      public void init()
      {
        try{
    
          // Create and initialize the ORB 
          // The applet 'this' is passed to make parameters from the  tag
          // available to initialize the ORB
          ORB orb = ORB.init(this, null);
          
          // Get the root naming context
          org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
          NamingContext ncRef = NamingContextHelper.narrow(objRef);
    
          // Resolve the object reference in naming
          NameComponent nc = new NameComponent("Hello", " ");
          NameComponent path[] = {nc};
          Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));
          
          // Call the Hello server object and print the results
          message = helloRef.sayHello();
    
        
        } catch(Exception e) {
            System.out.println("HelloApplet exception: " + e);
            e.printStackTrace(System.out);
          }  
      }
      String message = " ";
    
      public void paint(Graphics g)
      {
        g.drawString(message, 25, 50);
      }
    
    }
    

  3. Save and close HelloApplet.java.

Understanding the Applet

This section explains each line of HelloApplet.java, describing what the code does, as well as why it is needed for this applet.

Performing Basic Setup

The basic shell of a CORBA client applet is the same as most applets: You import required library packages, declare the applet class, define an init() method, and handle exceptions.

Importing Required Packages

The first step to creating the basic shell of the applet is to import the packages required for the client class:

// The package containing our stubs.
import HelloApp.*;

// HelloClient will use the naming service.
import org.omg.CosNaming.*;

// The package containing special exceptions thrown by the name service.
import org.omg.CosNaming.NamingContextPackage.*;

// All CORBA applications need these classes.
import org.omg.CORBA.*;

// Needed for the applet.
import java.awt.Graphics;

Declaring the Applet Class

Next, we declare the applet class:

public class HelloApplet extends java.applet.Applet
{
  // The init() method goes here.
}

Declaring the init() method

Every Java application needs a main method of some type. In an applet, the init method is used instead of the main method. The code you write under the init method overrides the Applet's default method so that it can respond to major events. In this case, the code will describe how the applet should be initialized each time it is loaded or reloaded. Typically, an applet will also include start, stop, and destroy methods.

  public void init()
  {
    // The try-catch block goes here.
  }

Handling CORBA System Exceptions

Because all CORBA programs can throw CORBA system exceptions at runtime, all of the init() functionality is placed within a try-catch block. CORBA programs throw system exceptions whenever trouble occurs during any of the processes (marshaling, unmarshaling, upcall) involved in invocation.

The exception handler prints the name of the exception and its stack trace to standard output (the Java console) so you can see what has gone wrong.

A try-catch block is set up inside init():

    try{
    
      // The rest of the HelloApplet code goes here.
    
    } catch(Exception e) {
        System.out.println("HelloApplet exception: " + e);
        e.printStackTrace(System.out);
      }

Creating an ORB Object

A CORBA client needs a local ORB object to perform all of its marshaling and IIOP work. Every client instantiates an org.omg.CORBA.ORB object and initializes it by passing certain information about itself to the ORB.

You declare and initialize an ORB variable inside the try-catch block:

      Properties props = new Properties();
      props.put("org.omg.CORBA.ORBInitialPort", "1050");
      ORB orb = ORB.init(this, props);

The call to the ORB's init() method passes in the applet, allowing you to set certain properties at runtime. Here we have set the ORBInitialPort property to 1050 so that it connects properly to the HelloServer.

Finding the Hello Server

Now that the applet has an ORB, it can ask the ORB to locate the actual service it needs, in this case the Hello server. There are a number of ways for a CORBA client to get an initial object reference; your client applet will use the COS Naming Service specified by OMG and provided with Java IDL.

Obtaining the Initial Naming Context

The first step in using the naming service is to get the initial naming context. In the try-catch block, below your ORB initialization, you call orb.resolve_initial_references() to get an object reference to the name service:

      org.omg.CORBA.Object objRef = 
            orb.resolve_initial_references("NameService");

The string "NameService" is defined for all CORBA ORBs. When you pass in that string, the ORB returns a naming context object that is an object reference to the name service.

Narrowing the Object Reference

As with all CORBA object references, objRef is a generic CORBA object. To use it as a NamingContext object, you must narrow it to its proper type. The call to narrow() is added just below the previous statement.

      NamingContext ncRef = NamingContextHelper.narrow(objRef);

Here you see the use of an idlj-generated helper class, similar in function to HelloHelper. The ncRef object is now an org.omg.CosNaming.NamingContext, and you can use it to access the naming service and find other services.

Finding a Service in Naming

Names can have different structures depending upon the implementation of the naming service. Consequently, CORBA name servers handle complex names by way of NameComponent objects. Each NameComponent holds a single part, or element, of the object's full name. An array of NameComponent objects can hold a fully-qualified path to an object on any computer file or disk system.

To find the Hello server, you first need a NameComponent to hold an identifying string for it. This code is found directly below the call to narrow().

      NameComponent nc = new NameComponent("Hello", " ");

This statement sets the id field of nc to "Hello" and the kind field to the empty string.

Because the path to the Hello object has just one element, create a single-element array out of nc. The NamingContext.resolve() method requires this array for its work:

      NameComponent path[] = {nc};

The NameComponent array is passed to the naming service's resolve() method to get an object reference to the Hello server and narrow it to a Hello object:

      Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));

Here you see the HelloHelper class at work. The resolve() method returns a generic CORBA object as you saw above when locating the name service itself. Therefore, you immediately narrow it to a Hello object, which is the object reference you need to perform the rest of your work.

Invoking the sayHello() Operation

CORBA invocations look like a method call on a local object. The complications of marshaling parameters to the wire, routing them to the server-side ORB, unmarshaling, and placing the upcall to the server method are completely transparent to the client programmer. Because so much is done for you by the generated code, invocation is really the easiest part of CORBA programming.

      message = helloRef.sayHello();

Finally, print the results of the invocation. This code is placed outside your init() method, but within the HelloApplet class:

String message = " ";

public void paint(Graphics g)
{
  g.drawString(message, 25, 50);
}

Compiling and Running the Hello World Applet

To run the Hello World applet, you first need to compile the applet file and generate the Applet subclass, then call the subclass within an HTML file using an <APPLET> tag.

Compiling the Client Applet

  1. Open a DOS prompt or terminal window. Change to the directory where the HelloApplet.java file resides.

  2. Run the Java compiler on HelloApplet.java:
    javac HelloApplet.java
    
  3. Correct any errors in your file and recompile if necessary. (You can copy the file from HelloApplet.java if you have trouble finding your typographical errors).

    The generated file HelloApplet.class can be found in your project directory.

Setting Up the HTML File

Once you've written an applet, you need to add it to an HTML page so that you can try it out. You do this by adding an <APPLET> tag to the basic HTML shell. When you have completed this step, you can run your applet using the Applet Viewer or from a J2SE v1.3-enabled Web browser.

This section describes how to create the basic HTML file and add the APPLET tag to it.

  1. Create a file named Tutorial.html using your favorite text editor in your project directory, Hello.

  2. Enter the following HTML code to Tutorial.html, or paste it from Tutorial.html:

    <HTML>
    <!--Copyright 2000, Sun Microsystems, Inc. -->
    <HEAD>
       <TITLE>Getting Started with Java IDL: Running HelloApplet</TITLE>
       <X-SAS-WINDOW TOP=42 BOTTOM=477 LEFT=4 RIGHT=534>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF">
    
    
    <H1 ALIGN=CENTER>Running the Hello World Applet</H1>
    <HR>
    
    <P>If all goes well, the applet appears below:
    
    <P>
    <APPLET CODE=HelloApplet.class 
            CODEBASE='enter_the_path_to_your_project_directory_here'
            WIDTH=500 
            HEIGHT=300>
    <PARAM name="org.omg.CORBA.ORBInitialHost" value=enter_server_machine_name>
    <PARAM name="org.omg.CORBA.ORBInitialPort" value=1050>
    </APPLET>
    
    
    </BODY>
    </HTML>
    

  3. Save the file and exit the editor.

The simplest form of the APPLET tag tells the browser to load the applet whose Applet subclass is name HelloApplet.class. When a Java-enabled browser encounters an <APPLET> tage, it reserves a display area of the specified WIDTH and HEIGHT, loads the bytecode for the specifiec Applet subclass, creates an instance of the subclass, and then calls the instances init method.

This applet includes PARAM tags, which let you customize the applet's configuration with parameters. In the first PARAM tag, the value for ORBInitialHost is the name of the machine where the CORBA name server runs. In this example, this will most likely be your local machine name. In the second PARAM tag, the value of ORBInitialPort is the one you are using to run the name server. This value was defined as 1050 earlier in this tutorial.

By default, a browser looks for an applet's class files in the same directory as the HTML file that has the <APPLET> tag. We could use the CODEBASE attribute to tell the browser in which directory the the applet's files are located. If the applet's files and the HTML file are in the same directory, as they may be in this example, you can eliminate this attribute.

Running the Applet

Now that you have the applet code and the HTML file that loads the applet, you are ready to run your applet. For information on how to do this, link to Running the Hello World Applet.

Troubleshooting

If you are having trouble running the applet inside your Java-enabled Web browser, make sure you have the JavaTM 2 Runtime Environment, Standard Edition, version 1.3.0, which includes the JavaTM Plug-in 1.3. This can be downloaded from http://java.sun.com/products/plugi n/index.html. Instructions for plugging it into your Web browser are available there as well.

On of the error messages indicative of this situation is security violation: method verification error.

For More Information

Developing Clients
Covers topics of interest to CORBA client programmers
Exceptions: System Exceptions
Explains how CORBA system exceptions work and provides details on the minor codes of Java IDL's system exceptions
Initialization:  System Properties
Explains what properties can be passed to the ORB at initialization
Naming Service
Covers the COS Naming Service in greater detail


Previous lesson: Developing a Client Application
Next lesson: Developing the Hello World Server
Tutorial home | HelloApplet.java
Tutorial.html
Home


Copyright © 1996, 1997, 2000 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.