java 20 tutorial 20and 20guide

Upload: jailsonmartins

Post on 10-Apr-2018

246 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    1/53

    Java IDL Tutorial and Guide

    -1-

    Java IDL Tutorial and Guide

    1. Getting Started with Java TM IDL

    Java TM IDL is a technology for distributed objects--that is, objects interacting on differentplatforms across a network. Java IDL is similar to RMI (Remote Method Invocation), which

    supports distributed objects written entirely in the Java programming language. However, JavaIDL enables objects to interact regardless of whether they're written in the Java programminglanguage or another language such as C, C++, COBOL, or others.

    This is possible because Java IDL is based on the Common Object Request Brokerage Architecture(CORBA), an industry-standard distributed object model. A key feature of CORBA is IDL, alanguage-neutral Interface Definition Language. Each language that supports CORBA has its ownIDL mapping--and as its name implies, Java IDL supports the mapping for Java.

    To support interaction between objects in separate programs, Java IDL provides an Object RequestBroker, or ORB. The ORB is a class library that enables low-level communication between JavaIDL applications and other CORBA-compliant applications.

    This tutorial teaches the basic tasks in building a CORBA distributed application using Java IDL. You will build the classic "Hello World" program as a distributed application, with both applet andapplication clients. The Hello World program has a single operation that returns a string to beprinted.

    Any relationship between distributed objects has two sides: the client and the server. The serverprovides a remote interface, and the client calls a remote interface. These relationships arecommon to most distributed object standards, including RMI and CORBA. Note that in thiscontext, the terms client and server define object-level rather than application-level interaction--any application could be a server for some objects and a client of others. In fact, a single object

    could be the client of an interface provided by a remote object and at the same time implement aninterface to be called remotely by other objects.

    This figure shows how a one-method distributed object is shared between a CORBA client andserver to implement the classic "Hello World" application.

    A one-method distributed object shared between a CORBA client and server.

    On the client side, the application includes a reference for the remote object. The object referencehas a stub method, which is a stand-in for the method being called remotely. The stub is actuallywired into the ORB, so that calling it invokes the ORB's connection capabilities, which forwardsthe invocation to the server.

    On the server side, the ORB uses skeleton code to translate the remote invocation into a methodcall on the local object. The skeleton translates the call and any parameters to theirimplementation-specific format and calls the method being invoked. When the method returns, theskeleton code transforms results or errors, and sends them back to the client via the ORBs.

    Between the ORBs, communication proceeds by means of a shared protocol, IIOP--the InternetInter-ORB Protocol. IIOP, which is based on the standard TCP/IP internet protocol, defines how

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    2/53

    Java IDL Tutorial and Guide

    -2-

    CORBA-compliant ORBs pass information back and forth. Like CORBA and IDL, the IIOPstandard is defined by OMG, the Object Management Group.

    The Java IDL Development Process and the Hello World Tutorial

    This tutorial teaches the basic tasks in building a CORBA distributed application using Java IDL. You will build the classic Hello World program as a distributed application, with both applet andapplication clients. The Hello World program has a single operation that returns a string to beprinted.

    Despite its simple design, the Hello World program lets you learn and experiment with all thetasks required to develop almost any CORBA program that uses static invocation. The followingsteps provide a general guide to designing and developing a distributed object application withJava IDL. Links to the relevant steps of the tutorial will guide you through creating this sampleapplication.

    1. Define the remote interface

    You define the interface for the remote object using the OMG's interface definitionlangauge. You use IDL instead of the Java language because the idlj compilerautomatically maps from IDL, generating all Java language stub and skeleton source files,along with the infrastructure code for connecting to the ORB. Also, by using IDL, you makeit possible for developers to implement clients and servers in any other CORBA-compliantlanguage.

    Note that if you're implementing a client for an existing CORBA service, or a server for anexisting client, you would get the IDL interfaces from the implementer--such as a serviceprovider or vendor. You would then run the idlj compiler over those interfaces and followthese steps.

    Writing the IDL file in this tutorial walks you through these steps for the simple "HelloWorld" example.

    2. Compile the remote interface

    When you run the idlj compiler over your interface definition file, it generates the Javaversion of the interface, as well as the class code files for the stubs and skeletons thatenable your applications to hook into the ORB.

    Mapping Hello.idl to Java in this tutorial walks you through these steps for the simple"Hello World" example.

    3. Implement the server

    Once you run the idlj compiler, you can use the skeletons it generates to put together yourserver application. In addition to implementing the methods of the remote interface, yourserver code includes a mechanism to start the ORB and wait for invocation from a remoteclient.

    Developing the Hello World Server walks you through writing a simple server for the"Hello World" application.

    4. Implement the client

    Similarly, you use the stubs generated by the idlj compiler as the basis of your clientapplication. The client code builds on the stubs to start its ORB, look up the server using

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    3/53

    Java IDL Tutorial and Guide

    -3-

    the name service provided with Java IDL, obtain a reference for the remote object, and callits method.

    Developing a Client Application walks you through writing a simple client applicationand Developing a Client Applet walks you through writing a client applet that performsthe same functions as the client application.

    5. Start the applications

    Once you implement a server and a client, you can start the name service, then start theserver, then run the client.

    Compiling and Running the Hello World Application walks you through compilingand running the server and client program that together make up the "Hello World"application.

    Using Stringified Object References walks you through making an object reference when thereis no naming service.

    Running the Hello World Application on 2 Machines describes one way of distributing thesimple application across two machines - a client and a server.

    For More Information

    Although concepts are explained as they are introduced in the tutorial, you will find moreinformation in the Concepts section. New terms are linked to their definitions throughout thetutorial.

    The Object Management Group no longer maintains this site, but the CORBA for Beginnners page

    contains links to web pages that provide introductory CORBA information.

    2. Writing the Interface Definition Language (IDL) file

    Note: All command and troubleshooting instructions apply to Java 2 SDK v1.3.0 and its version of idlj only.

    Before you start working with Java IDL, you need to install version 1.3 of the Java 2 SDK. J2SDK v1.3.0 provides the Application Programming Interface (API) and Object Request Broker (ORB)needed to enable CORBA-based distributed object interaction, as well as the idlj compiler. The idljcompiler uses the IDL-to-Java mapping to convert IDL interface definitions to corresponding Javainterfaces, classes, and methods, which you can then use to implement your client and server code.

    This section teaches you how to write a simple IDL interface definition and how to translate theIDL interface to Java. It also describes the purpose of each file generated by the idlj compiler.

    These topics are included in this section:

    1. Writing Hello.idl 2. Understanding the IDL file 3. Mapping Hello.idl to Java 4. Understanding the idlj Compiler Output

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    4/53

    Java IDL Tutorial and Guide

    -4-

    Writing Hello.idl

    To create the Hello.idl file,

    1. Create a new directory, named Hello , for this application.2. Start your favorite text editor and create a file named Hello.idl in this directory.

    3.

    In your file, enter the code for the interface definition:

    module HelloApp{

    interface Hello{

    string sayHello();};

    };

    4. Save the file.

    Understanding the IDL file

    OMG IDL is a purely declarative language designed for specifying programming-language-independent operational interfaces for distributed applications. OMG specifies a mapping fromIDL to several different programming languages, including C, C++, Smalltalk, COBOL, Ada, andJava. When mapped, each statement in OMG IDL is translated to a corresponding statement inthe programming language of choice. You can use the tool idlj to map an IDL interface to Java andimplement the client class. When you map the same IDL to C++ and implement the server in thatlanguage, the Java client and C++ server interoperate through the ORB as though they werewritten in the same language.

    The IDL for Hello World is extremely simple; its single interface has a single operation. You need

    perform only three steps:

    1. Declare the CORBA IDL module 2. Declare the interface 3. Declare the operations

    Declaring the CORBA IDL Module

    A CORBA module is a namespace that acts as a container for related interfaces and declarations.It corresponds closely to a Java package. Each module statement in an IDL file is mapped to aJava package statement.

    The module statement looks like this:

    module HelloApp{

    // Subsequent lines of code here.};

    When you compile the IDL, the module statement will generate a package statement in the Javacode.

    Declaring the Interface

    Like Java interfaces, CORBA interfaces declare the API contract an object has with other objects.Each interface statement in the IDL maps to a Java interface statement when mapped.

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    5/53

    Java IDL Tutorial and Guide

    -5-

    In your Hello.idl file, the interface statement looks like this:

    module HelloApp{

    interface Hello // These{ // are the

    // interface

    }; // statement.};

    When you compile the IDL, this statement will generate an interface statement in the Java code. Your client and server classes will implement the Hello interface in different ways.

    Declaring the Operations

    CORBA operations are the behavior that servers promise to perform on behalf of clients thatinvoke them. Each operation statement in the IDL generates a corresponding method statement inthe generated Java interface.

    In your Hello.idl file, the operation statement looks like this:

    module HelloApp{

    interface Hello{

    string sayHello(); // This line is the operation statement.};

    };

    Our little Hello World application has only a single operation, so Hello.idl is now complete.

    3. Mapping Hello.idl to Java

    The tool idlj reads OMG IDL files and creates the required Java files. The idlj compiler defaults togenerating only the client-side bindings. If you need both client-side bindings and server-sideskeletons (as you do for our Hello World program), you must use the -fall option when running theidlj compiler. For more information on the IDL-to-Java compiler options , follow the link.

    1. Go to a command line prompt.2. Change to the directory containing your Hello.idl file.3. Enter the compiler command:

    idlj -fall Hello.idl

    If you list the contents of the directory, you will see that a directory called HelloApp has beencreated and that it contains six files. Open Hello.java in your text editor. Hello.java is thesignature interface and is used as the signature type in method declarations when interfaces of thespecified type are used in other interfaces. It looks like this:

    package HelloApp;

    /*** HelloApp/Hello.java* Generated by the IDL-to-Java compiler (portable), version "3.0"* from Hello.idl*/

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    6/53

    Java IDL Tutorial and Guide

    -6-

    public interface Hello extends HelloOperations, org.omg.CORBA.Object,org.omg.CORBA.portable.IDLEntity{} // interface Hello

    With an interface this simple, it is easy to see how the IDL statements map to the generated Java

    statements.

    IDL Statement Java Statement

    module HelloApp package HelloApp;

    interface Hello public interface Hello

    The single surprising item is the extends statement. All CORBA objects are derived fromorg.omg.CORBA.Object to ensure required CORBA functionality. The required code is generatedby idlj; you do not need to do any mapping yourself.

    In previous versions of the idlj compiler (known as idltojava), the operations defined on the IDLinterface would exist in this file as well. Starting with J2SDK v1.3.0, the IDL-to-Java mappingputs all of the operations defined on the IDL interface in the operations interface ,HelloOperations.java. The operations interface is used in the server-side mapping and as amechanism for providing optimized calls for co-located clients and servers. For Hello.idl, this filelooks like this:

    package HelloApp;

    /*** HelloApp/HelloOperations.java* Generated by the IDL-to-Java compiler (portable), version "3.0"* from Hello.idl*/

    public interface HelloOperations{

    String sayHello ();} // interface HelloOperations

    Because there is only one operation defined in this interface, it is easy to see how the IDLstatements map to the generated Java statements.

    IDL Statement Java Statement

    string sayHello(); String sayHello();

    Understanding the idlj Compiler Output

    The idlj compiler generates a number of files. The actual number of files generated depends on theoptions selected when the IDL file is compiled. The generated files provide standard functionality,so you can ignore them until it is time to deploy and run your program. The files generated by the

    idlj compiler for Hello.idl, with the -fall command line option, are:

    _HelloImplBase.java

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    7/53

    Java IDL Tutorial and Guide

    -7-

    This abstract class is the server skeleton , providing basic CORBA functionality for theserver. It implements the Hello.java interface. The server class HelloServant extends_HelloImplBase .

    _HelloStub.java This class is the client stub , providing CORBA functionality for the client. It implementsthe Hello.java interface.

    Hello.java This signature interface contains the Java version of our IDL interface. The Hello.java interface extends org.omg.CORBA.Object , providing standard CORBA object functionality.It also extends IDLEntity , and is used as the signature type in method declarations wheninterfaces of the specified type are used in other interfaces.

    HelloHelper.java This final class provides auxiliary functionality, notably the narrow() method required tocast CORBA object references to their proper types.

    HelloHolder.java This final class holds a public instance member of type Hello . It provides operations forout and inout arguments, which CORBA allows, but which do not map easily to Java'ssemantics.

    HelloOperations.java This operations interface contains the single method sayHello() . The IDL-to-Javamapping puts all of the operations defined on the IDL interface into this file. Theoperations interface is used in the server-side mapping and as a mechanism for providingoptimized calls for co-located clients and servers.

    When you write the IDL interface, you do all the programming required to generate all these filesfor your distributed application. The next steps are to implement the client and server classes. Inthe steps that follow, you will create HelloClient.java and HelloApplet.java client classes and theHelloServer.java class.

    Troubleshooting

    Error Message: "idlj" not found

    If you try to run idlj on the file Hello.idl and the system cannot find idlj, it is most likely notin your path. Make certain that the location of idlj (the J2SDK v.1.3 .bin directory) is inyour path, and try again.

    For More Information

    Mapping IDL to Java: Overview

    Provides the basics on mapping IDL constructs to the corresponding Java statements.

    Chapter 3 of the OMG CORBA/IIOP specification

    Provides the complete specification for OMG Interface Definition Language. At this writing,the specification can be downloaded fromhttp://www.omg.org/technology/documents/new_formal/corba.htm .

    4. Developing the Hello World Server

    The example server consists of two classes, the servant and the server. The servant, HelloServant,

    is the implementation of the Hello IDL interface; each Hello instance is implemented by aHelloServant instance. The servant is a subclass of _HelloImplBase, which is generated by the idljcompiler from the example IDL. The servant contains one method for each IDL operation, in thisexample, just the sayHello() method. Servant methods are just like ordinary Java methods; the

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    8/53

    Java IDL Tutorial and Guide

    -8-

    extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided bythe server and the stubs.

    The server class has the server's main() method, which:

    Creates an ORB instance Creates a servant instance (the implementation of one CORBA Hello object) and tells the

    ORB about it Gets a CORBA object reference for a naming context in which to register the new CORBA

    object Registers the new object in the naming context under the name "Hello" Waits for invocations of the new object

    This lesson introduces the basics of writing a CORBA transient server. The steps in this topiccover:

    1. Creating HelloServer.java 2. Understanding HelloServer.java

    3. Compiling the Hello World Server

    To see the complete version of HelloServer.java , follow the link.

    Creating HelloServer.java

    To create HelloServer.java,

    1. Start your text editor and create a file named HelloServer.java in your main projectdirectory, Hello.

    2. Enter the following code for HelloServer.java in the text file. The following section,

    Understanding HelloServer.java , explains each line of code in some detail.

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

    // HelloServer 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.*;

    public class HelloServer{

    public static void main(String args[]){

    try{

    // Create and initialize the ORBORB orb = ORB.init(args, null);

    // Create the servant and register it with the ORB

    HelloServant helloRef = new HelloServant();orb.connect(helloRef);

    // Get the root naming context

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    9/53

    Java IDL Tutorial and Guide

    -9-

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

    NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // Bind the object reference in naming// Make sure there are no spaces between ""NameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};ncRef.rebind(path, helloRef);

    // Wait for invocations from clientsjava.lang.Object sync = new java.lang.Object();synchronized(sync){

    sync.wait();}

    } catch(Exception e) {System.err.println("ERROR: " + e);e.printStackTrace(System.out);

    }}

    }

    class HelloServant extends _HelloImplBase{

    public String sayHello(){

    return "\nHello world!!\n";

    }}

    3. Save and close HelloServer.java .

    Understanding HelloServer.java

    This section explains each line of HelloServer.java, describing what the code does, as well as why itis needed for this application.

    Performing Basic Setup

    The structure of a CORBA server program is the same as most Java applications: You importrequired library packages, declare the server class, define a main() method, and handle exceptions.

    Importing Required Packages

    First, we import the packages required for the server class:

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

    // HelloServer 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.*;

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    10/53

    Java IDL Tutorial and Guide

    -10-

    Declaring the Server Class

    The next step is to declare the server class:

    public class HelloServer{

    // The main() method goes here.}

    Defining the main() Method

    Every Java application needs a main method. It is declared within the scope of the HelloServerclass:

    public static void main(String args[]){

    // The try-catch block goes here.}

    Handling CORBA System Exceptions

    Because all CORBA programs can throw CORBA system exceptions at runtime, all of the main()functionality is placed within a try-catch block. CORBA programs throw runtime exceptionswhenever trouble occurs during any of the processes (marshaling, unmarshaling, upcall) involvedin invocation. The exception handler simply prints the exception and its stack trace to standardoutput so you can see what kind of thing has gone wrong.

    The try-catch block is set up inside main(), as shown:

    try{

    // The rest of the HelloServer code goes here.

    } catch(Exception e) {System.err.println("ERROR: " + e);e.printStackTrace(System.out);

    }

    Creating an ORB Object

    Just like in the client application, a CORBA server also needs a local ORB object. Every serverinstantiates an ORB and registers its servant objects so that the ORB can find the server when it

    receives an invocation for it.

    The ORB variable is declared and initialized inside the try-catch block.

    ORB orb = ORB.init(args, null);

    The call to the ORB's init() method passes in the server's command line arguments, allowing you toset certain properties at runtime.

    Managing the Servant Object

    A server is a process that instantiates one or more servant objects. The servant implements theinterface generated by idlj and actually performs the work of the operations on that interface.Our HelloServer needs a HelloServant .

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    11/53

    Java IDL Tutorial and Guide

    -11-

    Instantiating the Servant Object

    We instantiate the servant object inside the try-catch block, just below the call to init(), as shown:

    HelloServant helloRef = new HelloServant();

    The section of code describing the servant class will be explained in a later step.

    The next step is to connect the servant to the ORB, so that the ORB can recognize invocations on itand pass them along to the correct servant:

    orb.connect(helloRef);

    Defining the Servant Class

    At the end of HelloServer.java, outside the HelloServer class, we define the class for the servantobject.

    class HelloServant extends _HelloImplBase{

    // The sayHello() method goes here.}

    The servant is a subclass of _HelloImplBase so that it inherits the general CORBA functionalitygenerated for it by the compiler.

    Next, we declare the required sayHello() method:

    public String sayHello(){

    // The method implementation goes here.}

    The sayHello() implementation looks like this:

    return "\nHello world!!\n";

    Working with COS Naming

    The HelloServer works with the naming service to make the servant object's operations availableto clients. The server needs an object reference to the name service, so that it can register itself and ensure that invocations on the Hello interface are routed to its servant object.

    Obtaining the Initial Naming Context

    In the try-catch block, below instantiation of the servant, we call orb.resolve_initial_references() toget an object reference to the name server:

    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 ORBreturns a naming context object that is an object reference for the name service.

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    12/53

    Java IDL Tutorial and Guide

    -12-

    Narrowing the Object Reference

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

    NamingContext ncRef = NamingContextHelper.narrow(objRef);

    Here you see the use of an idlj-generated helper class, similar in function to HelloHelper. ThencRef object is now an org.omg.CosNaming.NamingContext and you can use it to access thenaming service and register the server, as shown in the next topic.

    Registering the Servant with the Name Server

    Just below the call to narrow(), we create a new NameComponent member:

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

    This statement sets the id field of nc to "Hello" and the kind component to the empty string. Makesure there are no spaces between the "".

    Because the path to the Hello has a single element, we create the single-element array thatNamingContext.resolve requires for its work:

    NameComponent path[] = {nc};

    Finally, we pass path and the servant object to the naming service, binding the servant object tothe "Hello" id:

    ncRef.rebind(path, helloRef);

    Now, when the client calls resolve("Hello") on the initial naming context, the naming servicereturns an object reference to the Hello servant.

    Waiting for Invocation

    The previous sections describe the code that makes the server ready; the next section explains thecode that enables it to simply wait around for a client to request its service. The following code,which is at the end of (but within) the try-catch block, shows how to accomplish this.

    java.lang.Object sync = new java.lang.Object();synchronized(sync){

    sync.wait();}

    This form of Object.wait() requires HelloServer to remain alive (though quiescent) until aninvocation comes from the ORB. Because of its placement in main(), after an invocation completesand sayHello() returns, the server will wait again.

    Compiling the Hello World Server

    Now we will compile the HelloServer.java so that we can correct any error before continuing withthis tutorial.

    Windows users note that you should substitute backslashes (\) for the slashes (/) in all paths inthis document.

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    13/53

    Java IDL Tutorial and Guide

    -13-

    To compile HelloServer.java:

    1. Change to the Hello directory.2. Run the Java compiler on HelloServer.java :

    javac HelloServer.java HelloApp/*.java

    3. Correct any errors in your file and recompile if necessary. (You can copy the file fromHelloServer.java , if you have trouble finding your typographical errors).

    4. The files HelloServer.class and HelloServant.class are generated in the Hello directory.

    Running the Hello World Server

    The next section describes Running the Hello World Application .

    For More Information

    Exceptions: System Exceptions Explains how CORBA system exceptions work and provides details on the minor codes of Java IDL's system exceptions

    Developing Servers Covers topics of interest to CORBA server programmers

    Naming Service Covers the COS Naming Service in greater detail

    5. Developing a Client Application

    This topic introduces the basics of writing a CORBA client application. To create a CORBA client

    applet , follow the link. Included in this lesson are:

    1. Creating HelloClient.java 2. Understanding HelloClient.java 3. Compiling HelloClient.java

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

    Creating HelloClient.java

    To create HelloClient.java ,

    1. Start your text editor and create a file named HelloClient.java in your main projectdirectory, Hello .

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

    import HelloApp.*; // The package containing our stubs.import org.omg.CosNaming.*; // HelloClient will use the naming service.import org.omg.CORBA.*; // All CORBA applications need theseclasses.

    public class HelloClient{public static void main(String args[]){

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    14/53

    Java IDL Tutorial and Guide

    -14-

    try{

    // Create and initialize the ORBORB orb = ORB.init(args, null);

    // Get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // Resolve the object reference in naming// make sure there are no spaces between ""NameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));

    // Call the Hello server object and print resultsString Hello = helloRef.sayHello();System.out.println(Hello);

    } catch(Exception e) {System.out.println("ERROR : " + e);e.printStackTrace(System.out);

    }}

    }

    3. Save and close HelloClient.java .

    Understanding HelloClient.java

    This section explains each line of HelloClient.java , describing what the code does, as well aswhy it is needed for this application.

    Performing Basic Setup

    The basic shell of a CORBA client is the same as many Java applications: You import requiredlibrary packages, declare the application class, define a main method, and handle exceptions.

    Importing Required Packages

    First, we import the packages required for the client class:

    import HelloApp.*; // The package containing our stubs.import org.omg.CosNaming.*; // HelloClient will use the naming service.import org.omg.CORBA.*; // All CORBA applications need these classes.

    Declaring the Client Class

    The next step is to declare the client class:

    public class HelloClient{

    // The main() method goes here.}

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    15/53

    Java IDL Tutorial and Guide

    -15-

    Defining a main() Method

    Every Java application needs a main() method. It is declared within the scope of the HelloClient class, as follows:

    public static void main(String args[]){

    // The try-catch block goes here.}

    Handling CORBA System Exceptions

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

    Our exception handler simply prints the name of the exception and its stack trace to standard

    output so you can see what kind of thing has gone wrong.

    The try-catch block is set up inside main() ,

    try{

    // Add the rest of the HelloClient code here.

    } catch(Exception e) {System.out.println("ERROR : " + 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. Everyclient instantiates an org.omg.CORBA.ORB object and initializes it by passing to the object certaininformation about itself.

    The ORB variable is declared and initialized inside the try-catch block.

    ORB orb = ORB.init(args, null);

    The call to the ORB's init() method passes in your application's command line arguments,allowing you to set certain properties at runtime.

    Finding the Hello Server

    Now that the application has an ORB, it can ask the ORB to locate the actual service it needs, inthis case the Hello server. There are a number of ways for a CORBA client to get an initial objectreference; our client application will use the COS Naming Service specified by OMG and providedwith Java IDL. See Using Stringified Object References for information on how to get an initialobject reference when there is no naming service available.

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    16/53

    Java IDL Tutorial and Guide

    -16-

    Obtaining the Initial Naming Context

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

    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 ORBreturns the initial naming context, 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 aNamingContext object, you must narrow it to its proper type.

    NamingContext ncRef = NamingContextHelper.narrow(objRef);

    Here we see the use of an idlj -generated helper class, similar in function to HelloHelper . ThencRef object is now an org.omg.CosNaming.NamingContext and you can use it to access thenaming service and find other services. You will do that in the next step.

    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 name. An array of NameComponent objects can hold a fully specified 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 the Helloserver.

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

    This statement sets the id field of nc to "Hello" and the kind field to an empty string. Be sure thisis an empty string, do not enter a space between "".

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

    NameComponent path[] = {nc};

    Finally, we pass path to the naming service's resolve() method to get an object reference to theHello server and narrow it to a Hello object:

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

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

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    17/53

    Java IDL Tutorial and Guide

    -17-

    Invoking the sayHello() Operation

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

    String Hello = helloRef.sayHello();

    Finally, we print the results of the invocation to standard output:

    System.out.println(Hello);

    Compiling HelloClient.java

    Now we will compile HelloClient.java so that we can correct any errors before continuing withthis tutorial.

    Windows users note that you should substitute backslashes (\) for the slashes (/) in all paths inthis document.

    To compile HelloClient.java ,

    1. Change to the Hello directory.2. Run the Java compiler on HelloClient.java :

    javac HelloClient.java HelloApp/*.java

    3. Correct any errors in your file and recompile if necessary. (You can copy the file from

    HelloClient.java if you have trouble finding your typographical errors).4. The HelloClient.class is generated to the Hello directory.

    Running the Client Application

    We need to create and compile the Hello server before we can successfully run the Hello clientapplication. Running the Hello World application is covered in Running the Hello World

    Application .

    For More Information

    Developing Clients Covers topics of interest to CORBA client programmersExceptions: 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

    6. Developing a Client Applet

    This topic introduces the basics of writing a CORBA client applet. An applet is a Java program tobe included in HTML pages and executed in Java-enabled browsers. Developing a CORBA clientapplet is very similar to developing a CORBA client application, except that in the applet the code

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    18/53

    Java IDL Tutorial and Guide

    -18-

    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 lessonare:

    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 yourfavorite 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 ORBORB orb = ORB.init(this, null);

    // Get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // Resolve the object reference in namingNameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));

    // Call the Hello server object and print the resultsmessage = helloRef.sayHello();

    } catch(Exception e) {

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    19/53

    Java IDL Tutorial and Guide

    -19-

    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 aswhy 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 librarypackages, 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 theclient 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 usedinstead of the main method. The code you write under the init method overrides the Applet 's

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    20/53

    Java IDL Tutorial and Guide

    -20-

    default method so that it can respond to major events. In this case, the code will describe how theapplet should be initialized each time it is loaded or reloaded. Typically, an applet will also includestart , 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 exceptionswhenever trouble occurs during any of the processes (marshaling, unmarshaling, upcall) involvedin invocation.

    The exception handler prints the name of the exception and its stack trace to standard output (theJava 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. Everyclient instantiates an org.omg.CORBA.ORB object and initializes it by passing certain informationabout 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 atruntime. Here we have set the ORBInitialPort property to 1050 so that it connects properly to theHelloServer.

    Finding the Hello Server

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

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    21/53

    Java IDL Tutorial and Guide

    -21-

    Obtaining the Initial Naming Context

    The first step in using the naming service is to get the initial naming context . In the try-catchblock, below your ORB initialization, you call orb.resolve_initial_references() to get anobject 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 ORBreturns 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 aNamingContext object, you must narrow it to its proper type. The call to narrow() is added justbelow the previous statement.

    NamingContext ncRef = NamingContextHelper.narrow(objRef);

    Here you see the use of an idlj -generated helper class, similar in function to HelloHelper . ThencRef object is now an org.omg.CosNaming.NamingContext , and you can use it to access thenaming 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 disksystem.

    To find the Hello server, you first need a NameComponent to hold an identifying string for it. Thiscode 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. To makesure it's an empty string, make sure there are no spaces between the quotation marks.

    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 objectreference 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 narrowit to a Hello object, which is the object reference you need to perform the rest of your work.

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    22/53

    Java IDL Tutorial and Guide

    -22-

    Invoking the sayHello() Operation

    CORBA invocations look like a method call on a local object. The complications of marshalingparameters to the wire, routing them to the server-side ORB, unmarshaling, and placing the upcallto the server method are completely transparent to the client programmer. Because so much isdone 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, butwithin 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 tag.

    Compiling the Client Applet

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

    2. Run the Java compiler on HelloApplet.java :3. javac HelloApplet.java4. 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. Youdo this by adding an 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 projectdirectory, Hello .

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

    Getting Started with Java IDL: Running HelloApplet

    Running the Hello World Applet

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    23/53

    Java IDL Tutorial and Guide

    -23-

    If all goes well, the applet appears below:

    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 isname HelloApplet.class . When a Java-enabled browser encounters an tage, itreserves a display area of the specified WIDTHand HEIGHT, loads the bytecode for the specifiecApplet subclass, creates an instance of the subclass, and then calls the instances init method.

    This applet includes PARAMtags, which let you customize the applet's configuration withparameters. In the first PARAM tag, the value for ORBInitialHost is the name of the machinewhere the CORBA name server runs. In this example, this will most likely be your local machinename. In the second PARAM tag, the value of ORBInitialPort is the one you are using to run thename 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 thathas the tag. We could use the CODEBASEattribute to tell the browser in which directorythe 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 runyour 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 sureyou have the Java TM 2 Runtime Environment, Standard Edition, version 1.3.0, which includes theJava TM 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: methodverification error .

    For More Information

    Developing Clients Covers topics of interest to CORBA client programmers

    Exceptions: System Exceptions

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    24/53

    Java IDL Tutorial and Guide

    -24-

    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

    7. Running the Hello World Application

    This topic walks you through running the server and client program that together make up the"Hello World" application or applet.

    Running the Hello World Application

    Despite its simple design, the Hello World program lets you learn and experiment with all thetasks required to develop almost any CORBA program that uses static invocation . To run thisclient-server application on your development machine:

    1. Start the Java IDL Name Server. To do this from a UNIX command shell, enter:

    tnameserv -ORBInitialPort 1050&

    From an MS-DOS system prompt (Windows), enter:

    start tnameserv -ORBInitialPort 1050

    In this example, port 1050 has been chosen for the naming service. You can change this to adifferent value if port 1050 is occupied on your system. If the nameserverport is notspecified, port 900 will be chosen by default. When using Solaris software, you must become

    root to start a process on a port under 1024. For this reason, we recommend that you use aport number greater than or equal to 1024.

    2. From a second prompt or shell, start the Hello server:

    On Unix:

    java HelloServer -ORBInitialPort 1050&

    On Windows:

    start java HelloServer -ORBInitialPort 1050

    You can leave out -ORBInitialPort nameserverport if the name server is running on thedefault port.

    If the Hello server is running on a different host (machine) than the naming service, youwould need to specify where the naming service is running when you start the server. To dothis, you would use the -ORBInitialHost nameserverhost argument.

    3. From a third prompt or shell, run the Hello application client:

    java HelloClient -ORBInitialPort 1050

    You can leave out -ORBInitialPort nameserverport if the name server is running on thedefault port.

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    25/53

    Java IDL Tutorial and Guide

    -25-

    If the Hello client is running on a different host (machine) than the naming service, youwould need to specify where the naming service is running when you start the client. To dothis, you would use the -ORBInitialHost nameserverhost argument.

    4. The client prints the string from the server to the command line:

    Hello world!!

    The name server and the Hello World server, like many CORBA servers, run until you explicitlystop them. To avoid having many servers running, kill the server processes after the clientapplication returns successfully.

    Running the Hello World Applet

    You can run the applet from either a Java-enabled Web browser (with JRE 1.3) or from the Applet Viewer. In either case, you must run the Name Server and the HelloServer prior to invoking theapplet. To run the applet,

    1. From an MS-DOS system prompt (Windows) or command shell (UNIX), start the Java IDLname server:

    On Unix:

    tnameserv -ORBInitialPort 1050&

    On Windows:

    start tnameserv -ORBInitialPort 1050

    In this example, the nameserverport , which is the port on which you want the name serverto run, is set to 1050. If you do not specify this, port 900 will be chosen by default. Also notethat using Solaris software, you must become root to start a process on a port under 1024.For this reason, we recommend that you use a port number greater than or equal to 1024.

    2. Start the Hello server:

    On Unix:

    java HelloServer -ORBInitialPort 1050 &

    On Windows:

    start java HelloServer -ORBInitialPort 1050

    In this example, the ORBInitialPort , which is the port on which you want the nameserver to run, is set to 1050. If you do not specify this, port 900 will be chosen by default.

    Also note that using Solaris software, you must become root to start a process on a portunder 1024. For this reason, we recommend that you use a port number greater than orequal to 1024.

    3. Run the applet.

    To run the applet from the appletviewer,

    1. Change to the applet directory, Hello .

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    26/53

    Java IDL Tutorial and Guide

    -26-

    2. Start the appletviewer and browse Tutorial.html by typing:

    appletviewer Tutorial.html

    Hello world!! prints to the appletviewer frame.

    To run the applet from a Web browser, make sure you have the Java 2 RuntimeEnvironment, Standard Edition, version 1.3.0, which includes the Java Plugin 1.3,and the latest version of your browser, preferably Netscape 6, then:

    3. Open the Web browser.4. Open the file Tutorial.html .

    Hello world!! prints in the browser frame.

    If the applet does not run in the Web browser, make sure you have the Java 2 RuntimeEnvironment, Standard Edition, version 1.3.0, which includes the Java Plugin 1.3. This plugin isneeded to run the applet and may not be present in older Web browsers.

    The name server and the Hello World server, like many CORBA servers, run until you explicitlystop them. To avoid having many servers running, kill the server processes after the clientapplication returns successfully.

    Troubleshooting

    Security violation: method verification error

    Make sure you have the Java 2 Runtime Environment, Standard Edition, version 1.3.0, whichincludes the Java Plugin 1.3. This plugin is needed to run the applet and may not be present in

    older Web browsers. It can be downloaded from http://java.sun.com/products/plugin/index.html .

    Specifying ORB Initial Port

    The default ORB Initial Port is port 900. If you prefer, you can omit the port specifications if youstart the name server on port 900. Using Solaris software, you must become root to start a processon a port under 1024. Remember to exit from root access before continuing with the tutorial if youchoose this port for your name server.

    8. Using Stringified Object References

    To invoke an operation on a CORBA object, a client application needs a reference to the object. Youcan get such references in a number of ways, such as callingORB.resolve_initial_references() or using another CORBA object (like the name service). Inprevious sections of this tutorial, you used both of these methods to get an initial object reference.

    Often, however, there is no naming service available in the distributed environment. In thatsituation, CORBA clients use a stringified object reference to find their first object.

    In this lesson, you will learn how to create a stringified object reference as a part of the serverstartup, and how the client gets that reference and destringifies it for use as a real objectreference.

    The steps in this lesson are:

    1. Making a Stringified Object Reference

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    27/53

    Java IDL Tutorial and Guide

    -27-

    2. Getting a Stringified Object Reference 3. Destringifying the Object Reference 4. Compiling and Running a Stringified Hello World

    To see completed versions of the source code, follow the links to HelloServer.java andHelloClient.java .

    Making a Stringified Object Reference

    For a stringified object reference to be available to the client, the server must create it and store itsomewhere that the client can access. Your reference will be written to disk in the form of a textfile.

    1. Create a new directory at the same level as the Hello directory named HelloString . CopyHello.idl to this directory.

    2. Copy HelloServer.java from the Hello directory to the HelloString directory. Name itHelloServerString.java , and make the following changes in this file.

    3. Because the new server will write a file to disk, you need to add an import statement. Addthe following:

    import java.io.*; // needed for output to the file system.

    4. The new server won't use the naming service, so you don't need the CosNaming packages.Delete these lines from the code:

    import org.omg.CosNaming.*; // not needed for stringified versionimport org.omg.CosNaming.NamingContextPackage.*; // remove from code

    5. Delete the code that gets the initial naming context and resolves the reference to a Hello

    object:

    // Get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // Bind the object reference in namingNameComponent nc = new NameComponent("Hello", " ");NameComponent path[] = {nc};ncRef.rebind(path, helloRef);

    6. Call the ORB's object_to_string() method and pass it the reference to the servantobject. This returns the object reference in a string form that can be saved in a file on disk.

    String ior = orb.object_to_string(helloRef);

    7. Build the path to the file that will be stored, using system properties to determine the pathstructure and syntax.

    String filename = System.getProperty("user.home")+System.getProperty("file.separator")+"HelloIOR";

    8. Use standard Java operations to write the stringified ior to disk:

    FileOutputStream fos = new FileOutputStream(filename);PrintStream ps = new PrintStream(fos);ps.print(ior);

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    28/53

    Java IDL Tutorial and Guide

    -28-

    ps.close();

    9. Save and close HelloServerString.java .

    When HelloServerString runs, instead of calling the ORB and registering the servant objectwith naming, it creates the text file HelloIOR containing a stringified reference to the servant. Thefile is stored in your home directory.

    Getting a Stringified Object Reference

    Note to Windows users: You should substitute backslashes (\) for the slashes (/) in all paths in thisdocument.

    1. Copy HelloClient.java from the Hello directory to the HelloString directory. Name itHelloClientString.java , and make the following changes in this file.

    2. Because the new client will read a file from the disk, you need to change the importstatements. Add the following:

    import java.io.*; // needed for input from the file system.

    3. The new client won't use the naming service, so you don't need the CosNaming package.Delete this line from the code:

    import org.omg.CosNaming;* // not needed for stringified version

    4. Delete the code that gets the initial naming context and registers the servant with thenaming service:

    // 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 namingNameComponent nc = new NameComponent("Hello", " ");NameComponent path[] = {nc};Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));

    5. Use standard Java operations to read the file that has the object reference. Note that clientand server programs must know the name of the file and where it is stored.

    String filename = System.getProperty("user.home")+System.getProperty("file.separator")+"HelloIOR";

    FileInputStream fis = new FileInputStream(filename);DataInputStream dis = new DataInputStream(fis);String ior = dis.readLine();

    The HelloClientString application now has a String object containing the stringified objectreference.

    Destringifying the Object Reference

    To destringify the object reference in ior , call the standard ORB method:

    org.omg.CORBA.Object obj = orb.string_to_object(ior);

    Finally, narrow the CORBA object to its proper type, so that the client can invoke on it:

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    29/53

    Java IDL Tutorial and Guide

    -29-

    Hello helloRef = HelloHelper.narrow(obj);The rest of the client code stays the same. Save and close HelloClientString.java .

    Compiling and Running a Stringified Hello World

    Compiling and running the new version of Hello World requires most of the same steps as for thenaming service version.

    Compiling Hello World

    1. Change to the HelloString directory.2. Compile the IDL file. Enter the compiler command:

    idlj -fall Hello.idl

    3. Run the Java compiler on your source code:

    javac *.java

    4. Correct any errors in your files and recompile if necessary. (You can copy the files fromHelloServer.java and HelloClient.java if you have trouble finding any typographicalerrors.)

    HelloServerString.class , HelloServantString.class , and HelloClientString.class aregenerated to the HelloString directory.

    Running Hello World

    To be certain that you are running your own server, check that all Hello server and name server

    processes have been stopped. Stop them if they are running.

    1. From an MS-DOS system prompt (Windows) or command shell (UNIX), start the Helloserver with the stringified object reference:

    java HelloServerString -ORBInitialPort 1050 &

    2. From another prompt or shell, run the Hello application client with the stringified objectreference:

    java HelloClientString -ORBInitialPort 1050 &

    3. The client prints the string from the server to the command line:

    Hello world!!

    For More Information

    Initialization: Obtaining Initial Object References Explains the various ways of getting an initial object reference

    9. The "Hello World" Example on 2 machines

    To enable the Hello World Tutorial to run on two machines, follow the steps as directed in thetutorial , with the following changes. This tutorial was written for the Java (tm) 2 Platform,Standard Edition (J2Se(tm)), version 1.3. In this example, the client, stubs, and skeletons are

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    30/53

    Java IDL Tutorial and Guide

    -30-

    located on the client machine, and the server and name server are located on the server machine.This scenario can be changed to meet your needs and is provided simply as an introduction to oneway this can be accomplished.

    1. Create and compile the Hello.idl file on the client machine as indicated in the tutorial:

    idlj -fall Hello.idl

    2. Create HelloClient.java on the client machine. Compile the .java files, including the stubsand skeletons (which are in the directory HelloApp ):

    javac *.java HelloApp/*.java

    3. Create HelloServer.java on the server machine. Compile the .java files:

    javac *.java

    4. Start the Java IDL name server on the server machine. To do this on Unix:

    tnameserv -ORBInitialPort 1050&

    To do this on Windows:

    start tnameserv -ORBInitialPort 1050

    Note that the name server will run on port 1050 if you enter the command as listed. If youwant a different nameserverport , replace 1050 with the correct port number.

    5. On the server machine, start the Hello server, as follows:

    java HelloServer -ORBInitialPort 1050

    If you used a different nameserverport , replace 1050 with the correct port number.

    6. On the client machine, run the Hello application client. From a DOS prompt or shell, type:

    java HelloClient -ORBInitialHost namerserverhost -ORBInitialPort 1050

    Note that nameserverhost is the host on which the IDL name server is running. In thiscase, it is the server machine.

    If you used a different nameserverport , replace 1050 with the correct port number.

    7. Kill or stop the server process when finished.

    10. Hello World with Persistent State

    This document has not been updated for J2SE 1.3

    Java IDL only supports transient objects - if an object's server process halts and restarts, the objectreference becomes invalid. However, Example 2 illustrates how a transient object can store itsstate and re-initialize itself from this state each time the server is restarted.

    The Example 2 server hosts a Hello object that stores a string in a file. You provide the string as acommand line argument to the client program. The server Hello object "remembers" the string and

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    31/53

    Java IDL Tutorial and Guide

    -31-

    returns it to the client the next time that the client is run, even if the server has been stopped andrestarted.

    Example 2 is identical to Example 1 except for the persistence enhancements. This page onlydiscusses the code neccessary to these enhancements.

    This page contains:

    The IDL for the persistent "Hello World" program A transient server that creates an object, registers it in a naming context, and saves its

    state in a file. An application client .

    Instructions for compiling and running the example are provided.

    Interface Definition (Hello.idl)

    module HelloApp{

    interface Hello{

    exception cantWriteFile{};exception cantReadFile{};

    string sayHello( in string message)raises (cantWriteFile);

    string lastMessage()raises (cantReadFile);

    };

    };

    Because the Hello object reads from and writes to a file, you will need to throw Java languageexceptions. (See Implementing the Server below). The Hello interface must define and raiseexceptions in order to generate the appropriate skeleton definitions.

    The sayHello method has been modified to take a string argument, which will be stored in a fileat runtime. A lastMessage method has been added to return this stored string to the client.

    The IDL compiler generates a directory HelloApp/ HelloPackage that contains the followingexception class files:

    cantReadFile.java

    cantReadFileHelper.java cantReadFileHolder.java cantWriteFile.java cantWriteFileHelper.java cantWriteFileHolder.java

    Use of these classes is illustrated in the implementation below.

    Implementing the Server (HelloServer.java)

    // Copyright and License

    import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*;

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    32/53

    Java IDL Tutorial and Guide

    -32-

    import java.io.*;

    class HelloServant extends _HelloImplBase{

    public String sayHello(String msg)throws HelloApp.HelloPackage.cantWriteFile

    {try {

    synchronized(this) {File helloFile = new File("helloStorage.txt");FileOutputStream fos = new FileOutputStream(helloFile);byte[] buf = new byte[msg.length()];msg.getBytes(0, msg.length(), buf, 0);fos.write(buf);fos.close();

    }} catch(Exception e) {

    throw new HelloApp.HelloPackage.cantWriteFile();} return "\nHello world !!\n";

    }

    public String lastMessage()throws HelloApp.HelloPackage.cantReadFile

    {try {

    synchronized(this) {File helloFile = new File("helloStorage.txt");FileInputStream fis = new FileInputStream(helloFile);byte[] buf = new byte[1000];int n = fis.read(buf);String lastmsg = new String(buf);fis.close();return lastmsg;

    }} catch(Exception e) {

    throw new HelloApp.HelloPackage.cantReadFile();}

    } }

    public class HelloServer {

    public static void main(String args[]){

    try{// create and initialize the ORBORB orb = ORB.init(args, null);

    // create servant and register it with the ORBHelloServant helloRef = new HelloServant();orb.connect(helloRef);

    // get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // bind the Object Reference in Naming

    NameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};ncRef.rebind(path, helloRef);

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    33/53

    Java IDL Tutorial and Guide

    -33-

    // wait for invocations from clientsjava.lang.Object sync = new java.lang.Object();synchronized (sync) {

    sync.wait();}

    } catch (Exception e) {System.err.println("ERROR: " + e);e.printStackTrace(System.out);

    }}

    }

    The sayHello and lastMessage method implementations throw the exceptions defined in theIDL file. These methods must throw file IO exceptions or the Java language compiler issueswarnings and errors.

    The HelloServant object receives ansychronous and possibly simultaneous method requests atruntime. Therefore, you should enclose all file IO code in a synchronized clause.

    No changes are required to HelloServer.main .

    Implementing the Client (HelloClient.java)

    // Copyright and License

    import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CORBA.*;import java.io.*;

    public class HelloClient

    {public static void main(String args[]){

    try{// create and initialize the ORBORB orb = ORB.init(args, null);

    // get the root naming contextorg.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 results

    String oldhello = helloRef.lastMessage();System.out.println(oldhello); String hello = helloRef.sayHello( args[0] );System.out.println(hello);

    } catch (Exception e) {System.out.println("ERROR : " + e) ;

    e.printStackTrace(System.out);}}

    }

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    34/53

    Java IDL Tutorial and Guide

    -34-

    This client retrieves the stored message via lastMessage and stores the new message via anargument to sayHello .

    Building and Running Hello World

    The following instructions assume you can use port 1050 for the Java IDL name server. Substitutea different port if necessary. Note that for ports below 1024, you need root access on UNIXmachines, and administrator privileges on Windows95 and NT. Note also that the instructions usea slash (/) for path names. Windows95 and NT users should subtitute a backslash (\).

    Create source files as shown above.

    Run idlj on the IDL file to create stubs and skeletons:

    idltojava -fall Hello.idl

    Compile the .java files, including the stubs and skeletons:

    javac *.java HelloApp/*.java

    Make sure the name server is running:

    tnameserv -ORBInitialPort 1050&

    Start the Hello server:

    java HelloServer -ORBInitialPort 1050

    Run the Hello application client from a different shell than the server:

    java HelloClient "remember this message" -ORBInitialPort 1050

    11. Hello World with Callback Object

    Client programs often react to changes or updates that occur in a server. For example, a clientgraph or spreadsheet program might need to be updated with each stock price update on a stockmarket server. The client has two options in this scenario: (1) periodically ask for the stock pricevia a method request on the stock server or (2) ask to be notified by the server whenever a pricechange occurs. The second option is referred to as a "callback".

    Example 3 illustrates how a client program can pass a callback object to a server. The server thenissues a method request on the callback object and thereby notifies the client.

    Example 3 is identical to Example 1 except for the callback enhancements. This page onlydiscusses the code necessary to these enhancements.

    This page contains:

    The IDL for a "Hello world" program with a callback. A server implementation that callsback to a client.

    A client that sends a callback object reference to a server.

    Instructions for compiling and running the example are provided.

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    35/53

    Java IDL Tutorial and Guide

    -35-

    Interface Definition (Hello.idl)

    module HelloApp{

    interface HelloCallback{

    void callback(in string message);

    };

    interface Hello{

    string sayHello( in HelloCallback objRef, in string message );};

    };

    A HelloCallback is defined, which the client will implement.

    The sayHello method is modified to take an object reference argument and string argument.The object reference argument provides a means for the client to pass a callback object to theserver, which the server can invoke. The string argument is the string that the server will sendback to the client.

    Implementing the Server (HelloServer.java)

    // Copyright and License

    import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*;

    class HelloServant extends _HelloImplBase{

    public String sayHello( HelloCallback callobj, String msg ){

    callobj.callback(msg); return "\nHello world !!\n";

    }}

    public class HelloServer {

    public static void main(String args[])

    { try{// create and initialize the ORBORB orb = ORB.init(args, null);

    // create servant and register it with the ORBHelloServant helloRef = new HelloServant();orb.connect(helloRef);

    // get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // bind the Object Reference in NamingNameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    36/53

    Java IDL Tutorial and Guide

    -36-

    ncRef.rebind(path, helloRef);

    // wait for invocations from clientsjava.lang.Object sync = new java.lang.Object();synchronized (sync) {

    sync.wait();}

    } catch (Exception e) {System.err.println("ERROR: " + e);e.printStackTrace(System.out);

    }}

    }

    The sayHello method implementation has been modified to invoke the callback object that itreceives.

    Implementing the Client (HelloClient.java)

    // Copyright and License

    import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CORBA.*;

    class HelloCallbackServant extends _HelloCallbackImplBase{

    public void callback(String notification){

    System.out.println(notification);}

    }

    public class HelloClient{

    public static void main(String args[]){

    try{// create and initialize the ORBORB orb = ORB.init(args, null);

    // get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // resolve the Object Reference in NamingNameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));

    HelloCallbackServant helloCallbackRef = new HelloCallbackServant();orb.connect(helloCallbackRef);

    // call the Hello server object and print resultsString hello = helloRef.sayHello( helloCallbackRef,"\ntest..\n" );System.out.println(hello);

    } catch (Exception e) {System.out.println("ERROR : " + e) ;e.printStackTrace(System.out);

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    37/53

    Java IDL Tutorial and Guide

    -37-

    }}

    }

    The client implements the HelloCallbackServant object.

    The HelloClient.main instantiates the callback object and passes it to the server. The clientmust also register the callback object with the ORB.

    Building and Running Hello World

    The following instructions assume you can use port 1050 for the Java IDL name server. Substitutea different port if necessary. Note that for ports below 1024, you need root access on UNIXmachines, and administrator privileges on Windows95 and NT. Note also that the instructions usea slash (/) for path names. Windows95 and NT users should subtitute a backslash (\).

    Create the source code files as shown above.

    Run idlj on the IDL file to create stubs and skeletons:

    idlj -fall Hello.idl

    Compile the .java files, including the stubs and skeletons:

    javac *.java HelloApp/*.java

    Make sure the name server is running:

    tnameserv -ORBInitialPort 1050&

    Start the Hello server:

    java HelloServer -ORBInitialPort 1050

    Run the Hello application client from a different shell than the server:

    java HelloClient -ORBInitialPort 1050

    12. Hello World with Implementation Inheritance

    Ordinarily, servant classes must inherit from the ImplBase class generated by the idlj compiler.This is inadequate for servant classes that need to inherit functionality from another Java class.The Java programming language allows a class only one superclass and the generated ImplBase class occupies this position.

    Example 4 illustrates how a servant class can inherit (an implementation) from any Java class. Inthis example, the HelloServant class inherits its entire implementation from another Java classHelloBasic . At runtime, method requests for HelloServant are delegated to another idlj -generated class.

    Example 4 is identical to Example 1 except for implementation inheritance enhancements. Thispage only discusses the code necessary for these enhancements.

    This section contains:

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    38/53

    Java IDL Tutorial and Guide

    -38-

    The IDL for a simple "Hello World" program A server implementation that delegates method requests for HelloServant to another

    Java class. A client program.

    Instructions for compiling and running the example are provided.

    Interface Definition (Hello.idl)

    module HelloApp{

    interface Hello{

    string sayHello();};

    };

    Compile the IDL interface with the command:

    idlj -fall Hello.idl

    The files generated by this command are discussed in the basic tutorial .

    Then use the compiler again to generate the Tie bindings:

    idlj -fallTIE Hello.idlThe second command generates an additional file in a HelloApp subdirectory:Hello_Tie.java

    This class acts as the skeleton, receiving invocations from the ORB and delegating them tothe servant that actually does the work.

    Implementing the Server (HelloServer.java)

    // Copyright and License

    import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*;

    class HelloBasic{

    public String sayHello(){

    return "\nHello world !!\n";}

    }

    class HelloServant extends HelloBasic implements HelloOperations {}

    public class HelloServer {

    public static void main(String args[]){

    try{// create and initialize the ORB

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    39/53

    Java IDL Tutorial and Guide

    -39-

    ORB orb = ORB.init(args, null);

    // create servant and register it with the ORBHelloServant servant = new HelloServant();Hello helloRef = new Hello_Tie(servant); orb.connect(helloRef);

    // get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // bind the Object Reference in NamingNameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};ncRef.rebind(path, helloRef);

    // wait for invocations from clientsjava.lang.Object sync = new java.lang.Object();synchronized (sync) {

    sync.wait();}

    } catch (Exception e) {System.err.println("ERROR: " + e);e.printStackTrace(System.out);

    }}

    }

    Implementing the Client (HelloClient.java)

    // Copyright and License

    import HelloApp.*;import org.omg.CosNaming.*;import org.omg.CORBA.*;

    public class HelloClient{

    public static void main(String args[]){

    try{// create and initialize the ORBORB orb = ORB.init(args, null);

    // get the root naming contextorg.omg.CORBA.Object objRef =

    orb.resolve_initial_references("NameService");NamingContext ncRef = NamingContextHelper.narrow(objRef);

    // resolve the Object Reference in NamingNameComponent nc = new NameComponent("Hello", "");NameComponent path[] = {nc};Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));

    // call the Hello server object and print resultsString hello = helloRef.sayHello();

    System.out.println(hello);} catch (Exception e) {

    System.out.println("ERROR : " + e) ;

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    40/53

    Java IDL Tutorial and Guide

    -40-

    e.printStackTrace(System.out);}

    }}

    Building and Running Hello World

    The following instructions assume you can use port 1050 for the Java IDL name server. Substitutea different port if necessary. Note that for ports below 1024, you need root access on UNIXmachines, and administrator privileges on Windows95 and NT. Note also that the instructions usea slash (/) for path names. Windows95 and NT users should subtitute a backslash (\).

    Create source code files as shown above.

    Run idlj on the IDL file to create stubs and skeletons:

    idlj -fall Hello.idl

    Then run the idlj compiler again to generate the Tie classes:

    idlj -fallTIE Hello.idl

    Compile the .java files, including the stubs and skeletons:

    javac *.java HelloApp/*.java

    Make sure the name server is running:

    tnameserv -ORBInitialPort 1050&

    Start the Hello server:

    java HelloServer -ORBInitialPort 1050

    Run the Hello application client from a different shell than the server:

    java HelloClient -ORBInitialPort 1050

    13. Exceptions

    CORBA has two types of exceptions: standard system exceptions which are fully specified by theOMG and user exceptions which are defined by the individual application programmer. CORBA exceptions are a little different from Java exception objects, but those differences are largelyhandled in the mapping from IDL to Java.

    Topics in this section include:

    Differences Between CORBA and Java Exceptions System Exceptions

    o System Exception Structure o Minor Codes o Completion Status

    User Exceptions Minor Code Meanings

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    41/53

    Java IDL Tutorial and Guide

    -41-

    Differences Between CORBA and Java Exceptions

    To specify an exception in IDL, the interface designer uses the raises keyword. This is similar tothe throws specification in Java. When you use the exception keyword in IDL you create a user-defined exception. The standard system exceptions need not (and cannot) be specified this way.

    System Exceptions

    CORBA defines a set of standard system exceptions, which are generally raised by the ORBlibraries to signal systemic error conditions like:

    Server-side system exceptions, such as resource exhaustion or activation failure. Communication system exceptions, for example, losing contact with the object, host down,

    or cannot talk to ORB daemon (orbd). Client-side system exceptions, such as invalid operand type or anything that occurs before

    a request is sent or after the result comes back.

    All IDL operations can throw system exceptions when invoked. The interface designer need notspecify anything to enable operations in the interface to throw system exceptions -- the capabilityis automatic.

    This makes sense because no matter how trivial an operation's implementation is, the potential of an operation invocation coming from a client that is in another process, and perhaps (likely) onanother machine, means that a whole range of errors is possible.

    Therefore, a CORBA client should always catch CORBA system exceptions. Moreover, developerscannot rely on the Java compiler to notify them of a system exception they should catch, becauseCORBA system exceptions are descendants of java.lang.RuntimeException .

    System Exception Structure

    All CORBA system exceptions have the same structure:

    exception { // descriptive of errorunsigned long minor ; // more detail about errorCompletionStatus completed ; // yes, no, maybe

    }

    System exceptions are subtypes of java.lang.RuntimeException throughorg.omg.CORBA.SystemException :

    java.lang.Exception|+--java.lang.RuntimeException

    |+--org.omg.CORBA.SystemException

    |+--BAD_PARAM|+--//etc.

    Minor Codes

    All CORBA system exceptions have a minor code field, a number that provides additionalinformation about the nature of the failure that caused the exception. Minor code meanings are not

  • 8/8/2019 Java 20 Tutorial 20and 20guide

    42/53

    Java IDL Tutorial and Guide

    -42-

    specified by the OMG; each ORB vendor specifies appropriate minor codes for thatimplementation. For the meaning of minor codes thrown by the Java ORB, see Minor codemeanings .

    Completion Status

    All CORBA system exceptions have a completion status field, indicating the status of the operationthat threw the exception. The completion codes are:

    COMPLETED_YESThe object implementation has completed processing prior to the exception being raised.

    COMPLETED_NOThe object implementation was not invoked prior to the exception being raised.

    COMPLETED_MAYBEThe status of the invocation is u