module HelloApp { interface Hello { string sayHello(); }; };
% idltojava hello.idl % ls -l HelloApp/*.java -rw-r--r-- 247 HelloApp/Hello.java -rw-r--r-- 1771 HelloApp/HelloHelper.java -rw-r--r-- 781 HelloApp/HelloHolder.java -rw-r--r-- 1452 HelloApp/_HelloImplBase.java -rw-r--r-- 960 HelloApp/_HelloStub.javaThe files created are:
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. public class HelloClient { public static void main(String args[]) { try{ // Create and initialize the ORB ORB orb = ORB.init(args, 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 results String Hello = helloRef.sayHello(); System.out.println(Hello); } catch(Exception e) { System.out.println("ERROR : " + e); e.printStackTrace(System.out); } } }
If inheritance is used, the servant class extends the ImplBase class generated by idltojava and it only needs to implement the methods declared in the Java interface.
This is illustrated in the this program:
import HelloApp.*; // The package containing our stubs. import org.omg.CosNaming.*; // HelloServer will use the naming service. import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; // All CORBA applications need these classes. public class HelloServer { public static void main(String args[]) { try{ // Create and initialize the ORB ORB 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 org.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); // Wait for invocations from clients java.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"; } }
setenv JAVA_HOME /usr/local/Java/LastJDK alias java $JAVA_HOME/bin/java alias javac $JAVA_HOME/bin/javac alias tnameserv $JAVA_HOME/bin/tnameserv
% tnameserv -ORBInitialPort 1050 &
% idltojava Hello.idl
% javac HelloClient.java HelloApp/*.java
% javac HelloServer.java HelloApp/*.java
% java HelloServer -ORBInitialPort 1050 &
% java HelloClient -ORBInitialPort 1050