Oracle9i CORBA Developer's Guide and Reference
Release 1 (9.0.1)

Part Number A90187-01
Go To Documentation Library
Home
Go To Product List
Book List
Go To Table Of Contents
Contents
Go To Index
Index

Master Index

Feedback

Go to previous page Go to next page

A
Example Code: CORBA

Oracle9i installs several samples under the $ORACLE_HOME/javavm/demo directory. Some of these samples are included in this appendix for your perusal.

The examples in the $ORACLE_HOME/javavm/demo directory include a UNIX makefile and Windows NT batch file to compile and run each example. You need a Java-enabled Oracle9i database with the standard EMP and DEPT demo tables to run the examples.

The emphasis in these short examples is on demonstrating features of the ORB and CORBA, not on elaborate Java coding techniques. Each of the examples includes a README file that tell you what files the example contains, what the example does, and how to compile and run the example.

Basic Example

The following is a Bank example that demonstrates a simple CORBA application. Included is the README, the IDL, the server code, and the client code. Refer to the $ORACLE_HOME/javavm/demo/corba/basic directory for the Makefile.

README

This is an Oracle9i-compatible version of the VisiBroker Bank
example. The major differences from the Vb example are:

(1) There is no server main loop. For Oracle9i the
"wait-for-activation" loop is part of the IIOP presentation (MTS
server).

(2) _boa.connect(object) is used instead of the less portable
 _boa_obj_is_ready(object) in the server object implementation to
register the new Account objects.

(3) The client program contains the code necessary to lookup the
AccountManager object (published under /test/BankCorb) and activate it,
and to authenticate the client to the server. (Note that object
activation and authentication, via NON_SSL_LOGIN, happen "under the
covers" so to speak on the lookup() method invocation.)

(4) There is also a tie implementation of this example, with the
server being AccountManagerImplTie.java.

Bank.IDL

// Bank.idl

module common {
  interface Account {
    float balance();
  };
  interface AccountManager {
    Account open(in string name);
  };
};

Server

The server code is implemented in the following:

AccountManagerImpl.java

// AccountManagerImpl.java

package server;

import common.*;
import java.util.*;

public class AccountManagerImpl extends _AccountManagerImplBase
{
  private Dictionary _accounts = new Hashtable();
  private Random _random = new Random();

  public synchronized Account open(String accountName)
  {
    // Lookup the account in the account dictionary.
    Account account = (Account) _accounts.get(accountName);

    // If there was no account in the dictionary, create one.
    if(account == null) {

      // Make up the account's balance, between 0 and 1000 dollars.
      float balance = Math.abs(_random.nextInt()) % 100000 / 100f;

      // Intialize orb and boa
      //org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
      //org.omg.CORBA.BOA boa = orb.BOA_init();

      // Create the account implementation, given the balance.
      account = new AccountImpl(balance);

      // register object with boa
      //boa.obj_is_ready(account);
      //orb.connect(account);
      _orb().connect(account);


      // Print out the new account.
      // This just goes to the system trace file for Oracle 9i.
      System.out.println("Created " + accountName + "'s account: " + account);

      // Save the account in the account dictionary.
      _accounts.put(accountName, account);
    }
    // Return the account.
    return account;
  }
}

AccountImpl.java

package server; 
import common.*;

public class AccountImpl extends _AccountImplBase
{
  private float _balance;

  public AccountImpl(float balance)
  {
    _balance = balance;
  }

  public float balance()
  {
    return _balance;
  }
}

AccountManagerImplTie.java

package server;

import common.*;
import java.util.*;
import oracle.aurora.AuroraServices.ActivatableObject;


public class AccountManagerImplTie implements AccountManagerOperations, 
                                              ActivatableObject
{
  private Dictionary _accounts = new Hashtable();
  private Random _random = new Random();

  public synchronized Account open(String name)
  {
    // Lookup the account in the account dictionary.
    Account account = (Account) _accounts.get(name);

    // If there was no account in the dictionary, create one.
    if(account == null) {

      // Make up the account's balance, between 0 and 1000 dollars.
      float balance = Math.abs(_random.nextInt()) % 100000 / 100f;

      // Intialize orb and boa
      org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
      //org.omg.CORBA.BOA boa = orb.BOA_init();

      // Create the account implementation, given the balance.
      account = new AccountImpl(balance);

      // register object with boa
      //boa.obj_is_ready(account);
      orb.connect(account);

      // Print out the new account.
      // This just goes to the system trace file for Oracle 9i.
      System.out.println("Created " + name + "'s account: " + account);

      // Save the account in the account dictionary.
      _accounts.put(name, account);
    }
    // Return the account.
    return account;
  }

  public org.omg.CORBA.Object _initializeAuroraObject()
  {
    return new _tie_AccountManager(this);
  }
}

Client.java

package client;

import common.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class Client
{
  public static void main (String[] args)
  {
    if (args.length != 5) {
      System.out.println("usage: Client user password GIOP_SERVICE CorbaPubname 
accountName");
      System.exit(1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String corbaPubname = args[3];
    String accountName = args[4];

    Hashtable env = new Hashtable();
    env.put(Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);

    try {
      Context ic = new InitialContext(env);

      AccountManager manager =
        (AccountManager)ic.lookup(GIOP_SERVICE + corbaPubname);

      // Request the account manager to open a named account.
      Account account = manager.open(accountName);

      // Get the balance of the account.
      float balance = account.balance();

      // Print out the balance.
      System.out.println("The balance in " + accountName +
"'s account is $" + balance); } catch (Exception e) { System.out.println("Client.main(): " + e.getMessage()); } } }

StoredClient.java

package client;

import common.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class StoredClient
{
  public static String callBankCorb(String corbaPubname, String accountName)
  {
    Hashtable env = new Hashtable();

    String ret = null;
    try {
      Context ic = new InitialContext(env);

      AccountManager manager =
        (AccountManager)ic.lookup(corbaPubname);

      // Request the account manager to open a named account.
      Account account = manager.open(accountName);

      // Get the balance of the account.
      float balance = account.balance();

      // Print out the balance.
      ret = "The balance in " + accountName + "'s account is $" + balance;
    } catch (Exception e) {
      ret = "StoredClient.callBankCorb(): " + e.getMessage();
    }
    return ret;
  }
}

IFR Example

The following example shows how to use the IFR. Soft copy is located at $ORACLE_HOME/javavm/demo/corba/basic/bankWithIFR.

Bank.IDL

module common {
  interface Account {
    float balance();
  };
  interface AccountManager {
    Account open(in string name);
  };
};

Server

The server code is implemented in the AccountManager, Account, and TIE classes.

AccountManagerImpl.java

package server;

import common.*;
import java.util.*;

public class AccountManagerImpl extends _AccountManagerImplBase
{
  private Dictionary _accounts = new Hashtable();
  private Random _random = new Random();

  public synchronized Account open(String accountName)
  {
    // Lookup the account in the account dictionary.
    Account account = (Account) _accounts.get(accountName);

    // If there was no account in the dictionary, create one.
    if(account == null) {

      // Make up the account's balance, between 0 and 1000 dollars.
      float balance = Math.abs(_random.nextInt()) % 100000 / 100f;

      // Intialize orb and boa
      //org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
      //org.omg.CORBA.BOA boa = orb.BOA_init();

      // Create the account implementation, given the balance.
      account = new AccountImpl(balance);

      // register object with boa
      //boa.obj_is_ready(account);
      //orb.connect(account);
      _orb().connect(account);


      // Print out the new account.
      // This just goes to the system trace file for Oracle 9i.
      System.out.println("Created " + accountName + "'s account: " + account);

      // Save the account in the account dictionary.
      _accounts.put(accountName, account);
    }
    // Return the account.
    return account;
  }
}

AccountImpl.java

package server;

import common.*;

public class AccountImpl extends _AccountImplBase
{
  private float _balance;

  public AccountImpl(float balance)
  {
    _balance = balance;
  }

  public float balance()
  {
    return _balance;
  }
}

AccountManagerImplTie.java

package server;

import common.*;
import java.util.*;
import oracle.aurora.AuroraServices.ActivatableObject;


public class AccountManagerImplTie implements AccountManagerOperations, 
                                              ActivatableObject
{
  private Dictionary _accounts = new Hashtable();
  private Random _random = new Random();

  public synchronized Account open(String name)
  {
    // Lookup the account in the account dictionary.
    Account account = (Account) _accounts.get(name);

    // If there was no account in the dictionary, create one.
    if(account == null) {

      // Make up the account's balance, between 0 and 1000 dollars.
      float balance = Math.abs(_random.nextInt()) % 100000 / 100f;

      // Intialize orb and boa
      org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
      //org.omg.CORBA.BOA boa = orb.BOA_init();

      // Create the account implementation, given the balance.
      account = new AccountImpl(balance);

      // register object with boa
      //boa.obj_is_ready(account);
      orb.connect(account);

      // Print out the new account.
      // This just goes to the system trace file for Oracle 9i.
      System.out.println("Created " + name + "'s account: " + account);

      // Save the account in the account dictionary.
      _accounts.put(name, account);
    }
    // Return the account.
    return account;
  }

  public org.omg.CORBA.Object _initializeAuroraObject()
  {
    return new _tie_AccountManager(this);
  }
}

Client

The client code is facilitated in the following:

Client.java

package client;

import common.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.omg.CORBA.Repository;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class Client
{
  public static void main (String[] args)
  {
    if (args.length != 5) {
      System.out.println("usage: Client user password GIOP_SERVICE CorbaPubname 
accountName");
      System.exit(1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String corbaPubname = args[3];
    String accountName = args[4];

    Hashtable env = new Hashtable();
    env.put(Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);

    try {
      Context ic = new InitialContext(env);

      AccountManager manager =
        (AccountManager)ic.lookup(GIOP_SERVICE + corbaPubname);

      // Request the account manager to open a named account.
      Account account = manager.open(accountName);

      // Get the balance of the account.
      float balance = account.balance();

      // Print out the balance.
      System.out.println
        ("The balance in " + accountName + "'s account is $" + balance);

      System.out.println("Calling the implicit method get_interface()");
      org.omg.CORBA.InterfaceDef intf =
        (org.omg.CORBA.InterfaceDef)account._get_interface_def();
      System.out.println("intf = " + intf.name());

      System.out.println("Now explicitly looking up for IFR and printing the");
      System.out.println("whole repository");
      System.out.println("");

      Repository rep = (Repository)ic.lookup(GIOP_SERVICE + "/etc/ifr");

      new PrintIDL(org.omg.CORBA.ORB.init()).print(rep);

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

PrintIDL.java

package client;

import common.*;
import java.io.PrintStream;
import java.util.Vector;
import java.io.DataInputStream;
import org.omg.CORBA.Repository;

public class PrintIDL
{
  private static org.omg.CORBA.ORB _orb;
  private static PrintStream _out = System.out;
  private static int _indent;

  
  public PrintIDL (org.omg.CORBA.ORB orb) {
    _orb = orb;
  }
  private void println(Object o) {
    for(int i = 0; i < _indent; i++) {
      _out.print("  ");
    }
    _out.println(o);
  }    

  private String toIdl(org.omg.CORBA.IDLType idlType) {
    org.omg.CORBA.Contained contained = 
org.omg.CORBA.ContainedHelper.narrow(idl Type); return contained == null ? idlType.type().toString() : contained.absolute_name(); } public void print(org.omg.CORBA.Container container)
throws org.omg.CORBA.UserException { org.omg.CORBA.Contained[] contained = container.contents(org.omg.CORBA.DefinitionKind.dk_all, true); for(int i = 0; i < contained.length; i++) { { org.omg.CORBA.ContainedPackage.Description description =
contained[i].describe(); org.omg.CORBA.portable.OutputStream output =
_orb.create_output_stream(); org.omg.CORBA.ContainedPackage.DescriptionHelper.write(output,
description); org.omg.CORBA.portable.InputStream input = output.create_input_stream(); org.omg.CORBA.ContainedPackage.Description description2 = org.omg.CORBA.ContainedPackage.DescriptionHelper.read(input); org.omg.CORBA.Any any1 = _orb.create_any(); org.omg.CORBA.ContainedPackage.DescriptionHelper.insert(any1,
description); org.omg.CORBA.Any any2 = _orb.create_any(); org.omg.CORBA.ContainedPackage.DescriptionHelper.insert(any2,
description2); if(!any1.equals(any1) || !any1.equals(any2) || !any2.equals(any2) || !any2.equals(any1)) { System.out.println("\n*** The desriptions were not equal (1) *** \n"); } org.omg.CORBA.ContainedPackage.Description description3 = org.omg.CORBA.ContainedPackage.DescriptionHelper.extract(any2); if(description.kind != description2.kind || !description.value.equals(description3.value)) { System.out.println("\n*** The desriptions were not equal (2) *** \n"); } } switch(contained[i].def_kind().value()) { case org.omg.CORBA.DefinitionKind._dk_Attribute: printAttribute(org.omg.CORBA.AttributeDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Constant: printConstant(org.omg.CORBA.ConstantDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Exception: printException(org.omg.CORBA.ExceptionDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Interface: printInterface(org.omg.CORBA.InterfaceDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Module: printModule(org.omg.CORBA.ModuleDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Operation: printOperation(org.omg.CORBA.OperationDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Alias: printAlias(org.omg.CORBA.AliasDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Struct: printStruct(org.omg.CORBA.StructDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Union: printUnion(org.omg.CORBA.UnionDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_Enum: printEnum(org.omg.CORBA.EnumDefHelper.narrow(contained[i])); break; case org.omg.CORBA.DefinitionKind._dk_none: case org.omg.CORBA.DefinitionKind._dk_all: case org.omg.CORBA.DefinitionKind._dk_Typedef: case org.omg.CORBA.DefinitionKind._dk_Primitive: case org.omg.CORBA.DefinitionKind._dk_String: case org.omg.CORBA.DefinitionKind._dk_Sequence: case org.omg.CORBA.DefinitionKind._dk_Array: default: break; } } } private void printConstant(org.omg.CORBA.ConstantDef def)
throws org.omg.CORBA.UserException { println("const " + toIdl(def.type_def()) + " " + def.name() + " = " +
def.value() + ";"); } private void printStruct(org.omg.CORBA.StructDef def)
throws org.omg.CORBA.UserException { println("struct " + def.name() + " {"); _indent++; org.omg.CORBA.StructMember[] members = def.members(); for(int j = 0; j < members.length; j++) { println(toIdl(members[j].type_def) + " " + members[j].name + ";"); } _indent--; println("};"); } private void printUnion(org.omg.CORBA.UnionDef def)
throws org.omg.CORBA.UserException { println("union " + def.name() + "
switch(" + toIdl(def.discriminator_type_def()) + ") {"); org.omg.CORBA.UnionMember[] members = def.members(); int default_index = def.type().default_index(); _indent++; for(int j = 0; j < members.length; j++) { if(j == default_index) { println("default:"); } else { println("case " + members[j].label + ":"); } _indent++; println(toIdl(members[j].type_def) + " " + members[j].name + ";"); _indent--; } _indent--; println("};"); } private void printException(org.omg.CORBA.ExceptionDef def)
throws org.omg.CORBA.UserException { println("exception " + def.name() + " {"); _indent++; org.omg.CORBA.StructMember[] members = def.members(); for(int j = 0; j < members.length; j++) { println(toIdl(members[j].type_def) + " " + members[j].name + ";"); } _indent--; println("};"); } private void printEnum(org.omg.CORBA.EnumDef def) throws org.omg.CORBA.UserException { org.omg.CORBA.TypeCode type = def.type(); println("enum " + type.name() + " {"); _indent++; int count = type.member_count(); for(int j = 0; j < count; j++) { println(type.member_name(j) + ((j == count - 1) ? "" : ",")); } _indent--; println("};"); } private void printAlias(org.omg.CORBA.AliasDef def)
throws org.omg.CORBA.UserException { org.omg.CORBA.IDLType idlType = def.original_type_def(); String arrayBounds = ""; while(true) { // This is a little strange, since the syntax of typedef'ed // arrays is stupid. org.omg.CORBA.ArrayDef arrayDef =
org.omg.CORBA.ArrayDefHelper.narrow(idlType); if(arrayDef == null) { break; } arrayBounds += "[" + arrayDef.length() + "]"; idlType = arrayDef.element_type_def(); } println("typedef " + toIdl(idlType) + " " + def.name() + arrayBounds + ";"); } private void printAttribute(org.omg.CORBA.AttributeDef def)
throws org.omg.CORBA.UserException { String readonly = def.mode() == org.omg.CORBA.AttributeMode.ATTR_READONLY ? "readonly " : ""; println(readonly + "attribute " + toIdl(def.type_def()) + " " + def.name() + ";"); } private void printOperation(org.omg.CORBA.OperationDef def)
throws org.omg.CORBA.UserException { String oneway = def.mode() == org.omg.CORBA.OperationMode.OP_ONEWAY ? "oneway " : ""; println(oneway + toIdl(def.result_def()) + " " + def.name() + "("); _indent++; org.omg.CORBA.ParameterDescription[] parameters = def.params(); for(int k = 0; k < parameters.length; k++) { String[] mode = { "in", "out", "inout" }; String comma = k == parameters.length - 1 ? "" : ","; println(mode[parameters[k].mode.value()] + " " +
toIdl(parameters[k].type_def) + " " + parameters[k].name + comma); } _indent--; org.omg.CORBA.ExceptionDef[] exceptions = def.exceptions(); if(exceptions.length > 0) { println(") raises ("); _indent++; for(int k = 0; k < exceptions.length; k++) { String comma = k == exceptions.length - 1 ? "" : ","; println(exceptions[k].absolute_name() + comma); } _indent--; } println(");"); } private void printInterface(org.omg.CORBA.InterfaceDef idef)
throws org.omg.CORBA.UserException { String superList = ""; { org.omg.CORBA.InterfaceDef[] base_interfaces = idef.base_interfaces(); if(base_interfaces.length > 0) { superList += " :"; for(int j = 0; j < base_interfaces.length; j++) { String comma = j == base_interfaces.length - 1 ? "" : ","; superList += " " + base_interfaces[j].absolute_name() + comma; } } } println("interface " + idef.name() + superList + " {"); _indent++; print(idef); _indent--; println("};"); } private void printModule(org.omg.CORBA.ModuleDef def)
throws org.omg.CORBA.UserException { println("module " + def.name() + " {"); _indent++; print(def); _indent--; println("};"); } }

Callback Example

The callback example is available online at $ORACLE_HOME/javavm/demo/examples/corba/basic/callback.

IDL Files

Client.IDL

module common {
  interface Client {
    wstring helloBack ();
  };
};

Server.IDL

#include <Client.idl>

module common {
  interface Server {
    wstring hello (in Client object);
  };
};

Server

ServerImpl.java

package server;

import common.*;
import oracle.aurora.AuroraServices.ActivatableObject;

public class ServerImpl extends _ServerImplBase implements ActivatableObject 
{
  public String hello (Client client) {
    return "I Called back and got: " + client.helloBack ();
  }

  public org.omg.CORBA.Object _initializeAuroraObject () {
    return this;
  }
}

Client

The client invokes the server object, which calls back to another object on the client-side. The originating client is implemented in Client.java. The client-side callback object is implemented in ClientImpl.java.

Client.java

// Client.java

package client;

import common.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class Client
{
  public static void main (String[] args) throws Exception
  {
    if (args.length != 4) {
      System.out.println ("usage: Client user password GIOP_SERVICE corbaPubname
");
      System.exit (1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String corbaPubname = args[3];

    Hashtable env = new Hashtable ();
    env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put (Context.SECURITY_PRINCIPAL, user);
    env.put (Context.SECURITY_CREDENTIALS, password);
    env.put (Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
    Context ic = new InitialContext (env);

    // Get the server object before preparing the client object
    // You have to do it in that order to get the ORB initialized correctly
    Server server = (Server)ic.lookup (GIOP_SERVICE + corbaPubname);

    // Create the client object and publish it to the orb in the client
    //org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init ();
    com.visigenic.vbroker.orb.ORB orb = oracle.aurora.jndi.orb_dep.Orb.init();
    org.omg.CORBA.BOA boa = orb.BOA_init ();
    ClientImpl client = new ClientImpl ();
    boa.obj_is_ready (client);

    // Pass the client to the server that will call us back
    System.out.println (server.hello (client));
  }
}

ClientImpl.java

package client;

import common.*;
import oracle.aurora.AuroraServices.ActivatableObject;

public class ClientImpl extends _ClientImplBase implements ActivatableObject 
{
  public String helloBack ()
  {
    return "Hello Client World!";
  }

  public org.omg.CORBA.Object _initializeAuroraObject ()
  {
    return this;
  }
}

TIE Example

This example demonstrates how to use the TIE mechanism.

Hello.IDL

module common {
  interface Hello {
    wstring helloWorld ();
  };
};

Server Code - HelloImpl.java

package server;

import common.*;
import oracle.aurora.AuroraServices.ActivatableObject;

public class HelloImpl implements HelloOperations, ActivatableObject 
{
  public String helloWorld()
  {
    return "Hello World!";
  }

  public org.omg.CORBA.Object _initializeAuroraObject()
  {
    return new _tie_Hello (this);
  }
}

Client.java

package client;

import common.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class Client
{
  public static void main (String[] args) throws Exception
  {
    if (args.length != 4) {
      System.out.println("usage: Client user password GIOP_SERVICE corbaPubname"
);
      System.exit(1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String corbaPubname = args[3];

    Hashtable env = new Hashtable();
    env.put(Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
    Context ic = new InitialContext(env);

    Hello hello = (Hello) ic.lookup(GIOP_SERVICE + corbaPubname);
    System.out.println(hello.helloWorld());
  }
}

Pure CORBA Client

This example uses CORBA Naming Service to retrieve any objects instead of JNDI.

Bank.IDL

module common {
  interface Account { float balance(); };
  interface AccountManager { Account open(in string name); };
};

Server Code

AccountManagerImpl.java

package server;

import common.*;
import java.util.*;
import org.omg.CORBA.Object;
import oracle.aurora.AuroraServices.ActivatableObject;

public class AccountManagerImpl extends _AccountManagerImplBase
  implements ActivatableObject
{
  private Dictionary _accounts = new Hashtable ();
  private Random _random = new Random();

  // Constructors
  public AccountManagerImpl() { super(); }        
  public AccountManagerImpl(String name) { super(name); }        

  public Object  _initializeAuroraObject()
  {
    return new AccountManagerImpl("BankManager");
  }

  public synchronized Account open(String name)
  {
    // Lookup the account in the account dictionary.
    Account account = (Account) _accounts.get (name);

    // If there was no account in the dictionary, create one.
    if (account == null) {
      // Make up the account's balance, between 0 and 1000 dollars.
      float balance = Math.abs (_random.nextInt ()) % 100000 / 100f;

      // Create the account implementation, given the balance.
      account = new AccountImpl(balance);

      // Make the object available to the ORB.
      _orb().connect(account);

      // Print out the new account.
      System.out.println("Created " + name + "'s account: " + account);

      // Save the account in the account dictionary.
      _accounts.put(name, account);
    }

    // Return the account.
    return account;
  }
}

AccountImpl.java

package server;

import common.*;

public class AccountImpl extends _AccountImplBase
{
  private float _balance;

  public AccountImpl () { _balance = (float) 100000.00; }
  public AccountImpl (float balance) { _balance = balance; }        
  public float balance () { return _balance; }        
}

Client.java

package client;

import common.*;
import org.omg.CORBA.Object;
import org.omg.CORBA.SystemException;
import org.omg.CosNaming.NameComponent;
import oracle.aurora.client.Login;
import oracle.aurora.AuroraServices.LoginServer;
import oracle.aurora.AuroraServices.LoginServerHelper;
import oracle.aurora.AuroraServices.PublishedObject;
import oracle.aurora.AuroraServices.PublishingContext;
import oracle.aurora.AuroraServices.PublishedObjectHelper;
import oracle.aurora.AuroraServices.PublishingContextHelper;

public class Client
{
  public static void main(String args[]) throws Exception
  {
    // Parse the args
    if (args.length < 4 || args.length > 5 ) {
      System.out.println ("usage: Client user password HOST PORT SID");
      System.exit(1);
    }
    String username = args[0];
    String password = args[1];
    String host = args[2];
    String port = args[3];
    String sid = null;
    if(args.length == 5)
      sid  = args[4];

    // Declarations for an account and manager
    Account account = null;
    AccountManager manager = null;
    com.visigenic.vbroker.orb.ORB orb;
    PublishingContext rootCtx = null;

    // access the Aurora Names Service
    try {
      // Initialize the ORB
      String initref;
      initref = (sid == null) ? "iioploc://" + host + ":" + port :
        "iioploc://" + host + ":" + port + ":" + sid;
      System.getProperties().put("ORBDefaultInitRef", initref);

      /*
       * Alternatively the following individual properties can be set
       * which take precedence over the URL above
      System.getProperties().put("ORBBootHost", host);
      System.getProperties().put("ORBBootPort", port);
      if(sid != null)
        System.getProperties().put("ORACLE_SID", sid);
       */

      /*
       * Some of the other properties that you can set
       System.getProperties().put("ORBNameServiceBackCompat", "false");
       System.getProperties().put("USE_SERVICE_NAME", "true");
       System.getProperties().put("ORBUseSSL", "true");
       System.getProperties().put("TRANSPORT_TYPE", "sess_iiop");
       */

      orb = oracle.aurora.jndi.orb_dep.Orb.init();
      // Get the Name service Object reference
      rootCtx = PublishingContextHelper.narrow(orb.resolve_initial_references(
                                                          "NameService"));
      // Get the pre-published login object reference
      PublishedObject loginPubObj = null;    
      LoginServer serv = null;
      NameComponent[] nameComponent = new NameComponent[2];
      nameComponent[0] = new NameComponent ("etc", "");
      nameComponent[1] = new NameComponent ("login", "");

      // Lookup this object in the Name service
      Object loginCorbaObj = rootCtx.resolve (nameComponent);

      // Make sure it is a published object
      loginPubObj = PublishedObjectHelper.narrow (loginCorbaObj);

      // create and activate this object (non-standard call)
      loginCorbaObj = loginPubObj.activate_no_helper ();
      serv = LoginServerHelper.narrow (loginCorbaObj);
      
      // Create a client login proxy object and authenticate to the DB
      Login login = new Login (serv);
      login.authenticate (username, password, null);
      
      // Now create and get the bank object reference
      PublishedObject bankPubObj = null;
      nameComponent[0] = new NameComponent ("test", "");
      nameComponent[1] = new NameComponent ("bank", "");

      // Lookup this object in the name service
      Object bankCorbaObj = rootCtx.resolve (nameComponent);

      // Make sure it is a published object
      bankPubObj = PublishedObjectHelper.narrow (bankCorbaObj);

      // create and activate this object (non-standard call)
      bankCorbaObj = bankPubObj.activate_no_helper ();
      manager = AccountManagerHelper.narrow (bankCorbaObj);
      
      account = manager.open ("Jack.B.Quick");

      float balance = account.balance ();
      System.out.println ("The balance in Jack.B.Quick's account is $" 
                          + balance);      
    } catch (SystemException e) {
      System.out.println ("Caught System Exception: " + e);
      e.printStackTrace ();            
    } catch (Exception e) {
      System.out.println ("Caught Unknown Exception: " + e);
      e.printStackTrace ();            
    }
  }
}

JTA Examples

Single-Phase Commit JTA Transaction Example

Employee.IDL

module employee {
  struct EmployeeInfo {
    wstring name;
    long number;
    double salary; 
  };

  exception SQLError {
    wstring message;
  };

  interface Employee {
    void setUpDSConnection (in wstring dsName) raises (SQLError);
    EmployeeInfo getEmployee (in wstring name) raises (SQLError);
    void updateEmployee (in EmployeeInfo name) raises (SQLError);
  };
};

Client.java

import employee.*;

import java.sql.DriverManager;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.transaction.UserTransaction;

import java.sql.SQLException;
import javax.naming.NamingException;

import oracle.aurora.jndi.jdbc_access.jdbc_accessURLContextFactory;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class Client
{
  public static void main (String[] args) throws Exception 
  {
    if (args.length != 7)
    {
      System.out.println ("usage: Client sessiiopURL jdbcURL objectName " + 
                          "user password userTxnName dataSrcName");
      System.exit (1);
    }
    String sessiiopURL = args [0];
    String jdbcURL = args [1];
    String objectName = args [2];
    String user = args [3];
    String password = args [4];
    String utName = args [5];
    String dsName = args [6];

    // lookup usertransaction object in the namespace
    UserTransaction ut = lookupUserTransaction (user, password, 
                                                jdbcURL, utName);

    // lookup employee object in the namespace
    Employee employee = lookupObject (user, password, sessiiopURL, objectName);
    EmployeeInfo info;

    // for (int ii = 0; ii < 10; ii++) 
    // {
    // start a transaction
    ut.begin ();

    // set up the DS on the server
    employee.setUpDSConnection (dsName);

    // retrieve the info
    info = employee.getEmployee ("SCOTT");
    System.out.println ("Before Update: " + info.name +"  " + info.salary);

    // change the salary and update it
    System.out.println ("Increase by 10%");
    info.salary += (info.salary * 10) / 100;
    employee.updateEmployee (info);    

    // commit the changes
    ut.commit ();

    // NOTE: you can do this before the commit of the previous transaction
    // (without starting a txn) then it becomes part of the first 
    // global transaction.
    // start another transaction to retrieve the updated info
    ut.begin ();

    // Since, you started a new transaction, the DS needs to be
    // enlisted with the 'new' transaction. Hence, setup the DS on the server
    employee.setUpDSConnection (dsName);

    // try to retrieve the updated info
    info = employee.getEmployee ("SCOTT");
    System.out.println ("After Update: " + info.name +"  " + info.salary);

    // commit the seond transaction
    ut.commit ();

    /*
     * ut.rollback ();
     * ut.begin ();
     * info = employee.getEmployee ("SCOTT", dsName);
     * System.out.println (info.name + " "  + " " + info.salary);    
     * 
     * System.out.println ("Increase by 10%");
     * info.salary += (info.salary * 10) / 100;
     * employee.updateEmployee (info);
     * 
     * info = employee.getEmployee ("SCOTT", dsName);
     * System.out.println (info.name + " "  + " " + info.salary);    
     * //ut.commit ();
     * ut.rollback ();
     * }
     */
  }

  private static UserTransaction lookupUserTransaction (String user,
                                                        String password,
                                                        String jdbcURL,
                                                        String utName)
  {
    UserTransaction ut = null;
    try {
      Hashtable env = new Hashtable ();
      env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
      env.put (Context.SECURITY_PRINCIPAL, user);
      env.put (Context.SECURITY_CREDENTIALS, password);
      env.put(jdbc_accessURLContextFactory.CONNECTION_URL_PROP, jdbcURL);
      Context ic = new InitialContext (env);

      DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ());
      
      ut = (UserTransaction)ic.lookup ("jdbc_access:/" + utName);
    } catch (NamingException e) {
      e.printStackTrace ();
    } catch (SQLException e) {
      e.printStackTrace ();
    }
    return ut;
  }

  private static Employee lookupObject (String user, String password,
                                         String sessiiopURL, String objectName)
  {
    Employee emp = null;
    try {
      Hashtable env = new Hashtable ();
      env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
      env.put (Context.SECURITY_PRINCIPAL, user);
      env.put (Context.SECURITY_CREDENTIALS, password);
      env.put (Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
      Context ic = new InitialContext (env);

      System.out.println ("Trying to lookup: " + sessiiopURL + objectName);
      emp = (Employee)ic.lookup (sessiiopURL + objectName);
    } catch (NamingException e) {
      e.printStackTrace ();
    }
    return emp;
  }
}

EmployeeServer.sqlj

package employeeServer;

import employee.*;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

//import oracle.aurora.transaction.xa.OracleJTADataSource;

public class EmployeeImpl 
       extends _EmployeeImplBase 
{
  Context ic = null;
  DataSource ds = null;
  Connection conn = null;

  public void setUpDSConnection (String dsName) 
       throws SQLError 
  { 
    try { 
      if (ic == null) 
        ic = new InitialContext ();

      // get a connection to the local DB
      ds = (DataSource)ic.lookup (dsName);

      // get a connection to the local DB
      // ((OracleJTADataSource)ds).setURL ("jdbc:oracle:kprb:");
      conn = ds.getConnection ();
    } catch (NamingException e) {
      e.printStackTrace ();
      throw new SQLError ("setUpDSConnection failed:" + e.toString ());
    } catch (SQLException e) {
      e.printStackTrace ();
      throw new SQLError ("setUpDSConnection failed:" + e.toString ());
    }
  }

  public EmployeeInfo getEmployee (String name) 
       throws SQLError 
  {
    try {
      if (conn == null)
        throw new SQLError ("getEmployee: conn is null");

      int empno = 0;
      double salary = 0.0;
      #sql { select empno, sal into :empno, :salary from emp
                    where ename = :name };
      return new EmployeeInfo (name, empno, (float)salary);
    } catch (SQLException e) {
      throw new SQLError (e.getMessage ());
    }
  }

  public void updateEmployee (EmployeeInfo employee) 
       throws SQLError 
  {
    if (conn == null)
      throw new SQLError ("updateEmployee: conn is null");

    try {
      #sql { update emp set ename = :(employee.name), sal = :(employee.salary)
                    where empno = :(employee.number) };
    } catch (SQLException e) {
      throw new SQLError (e.getMessage ());
    }
  }
}

Two-Phase Commit JTA Transaction Example

Employee.IDL

module employee {
  struct EmployeeInfo {
    wstring name;
    long number;
    double salary; 
  };

  exception SQLError {
    wstring message;
  };

  interface Employee {
    void initialize (in wstring user, in wstring password, 
                     in wstring serviceURL, in wstring utName, 
                     in wstring dsName) raises (SQLError);
    void setRemoteObject (in wstring objName) raises (SQLError);

    EmployeeInfo getEmployee (in wstring empName) raises (SQLError);
    EmployeeInfo getRemoteEmployee (in wstring name) raises (SQLError);
    void updateEmployee (in EmployeeInfo empInfo) raises (SQLError);
    void updateRemoteEmployee (in EmployeeInfo empInfo) raises (SQLError);
  };
};

Client.java

import employee.*;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;

import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class Client
{
  public static void main (String[] args) throws Exception
  {
    if (args.length != 6)
    {
      System.out.println ("usage: Client serviceURL objectName " + 
                          "user password userTxnName dataSrcName");
      System.exit (1);
    }
    String serviceURL = args [0];
    String objectName = args [1];
    String user = args [2];
    String password = args [3];
    String utName = args [4];
    String dsName = args [5];

    Hashtable env = new Hashtable ();
    env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put (Context.SECURITY_PRINCIPAL, user);
    env.put (Context.SECURITY_CREDENTIALS, password);
    env.put (Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
    Context ic = new InitialContext (env);

    EmployeeInfo localInfo;
    EmployeeInfo remoteInfo;

    try {
      // lookup an employee object
      Employee employee = (Employee)ic.lookup (serviceURL + objectName);

      // initialize the employee object
      employee.initialize (user, password, serviceURL, utName, dsName);

      // setup the remote Object
      employee.setRemoteObject (objectName);

      // get info for "SCOTT" 
      localInfo = employee.getEmployee ("SCOTT");
      System.out.println ("Before Update: " + localInfo.name + "  " +
                          localInfo.salary);
      // get info for "SMITH" 
      remoteInfo = employee.getRemoteEmployee ("SMITH");
      System.out.println ("               " + remoteInfo.name + "  " + 
                          remoteInfo.salary);

      // try to update locally
      localInfo.salary += 100;
      remoteInfo.salary += 200;

      // update Scott's salary
      employee.updateEmployee (localInfo);

      // update Smith's salary
      employee.updateRemoteEmployee (remoteInfo);

      // get updated info for "SCOTT" 
      localInfo = employee.getEmployee ("SCOTT");
      System.out.println ("After Update: " + localInfo.name +"  " + 
                          localInfo.salary);

      // get updated info for "SMITH" 
      remoteInfo = employee.getRemoteEmployee ("SMITH");
      System.out.println ("              " + remoteInfo.name +"  " + 
                          remoteInfo.salary);
    } catch (SQLError e) {
      System.out.println ("  Got SQLError: " + e.toString ());
    }
  }
}

Server

package employeeServer;

import employee.*;

import java.sql.Connection;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.Status;
import javax.transaction.UserTransaction;

import java.sql.SQLException;
import javax.naming.NamingException;

import oracle.aurora.jndi.sess_iiop.ServiceCtx;
import oracle.aurora.transaction.xa.OracleJTADataSource;

public class EmployeeImpl extends _EmployeeImplBase 
{
  Context inSessionLookupctx = null;
  Context remoteLookupCtx = null;
  UserTransaction ut = null;
  DataSource ds = null;
  Connection conn = null;
  String utName = null;
  String dsName = null;
  String user = null;
  String pwd = null;
  String serviceURL = null;
  Employee remoteEmployee = null;

  private void setInSessionLookupContext () 
       throws NamingException
  {
    // NOTE: here we need to set env as 2-phase coord needs
    //       branches, user/pwd to be set (branches is must)
    Hashtable env = new Hashtable ();
    env.put ("oracle.aurora.jta.branches", "true");
    env.put (Context.SECURITY_PRINCIPAL, user);
    env.put (Context.SECURITY_CREDENTIALS, pwd);
    inSessionLookupctx = new InitialContext (env);
    // ic = new InitialContext ();
  }

  private void setRemoteLookupInitialContext ()
       throws NamingException
  {
    Hashtable env = new Hashtable ();
    env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put (Context.SECURITY_PRINCIPAL, user);
    env.put (Context.SECURITY_CREDENTIALS, pwd);
    env.put (Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
    remoteLookupCtx = new InitialContext (env);
  }

  public void initialize (String user, String password, String serviceURL,
                          String utName, String dsName) 
       throws SQLError 
  { 
    try {
      // set the local variables
      this.user = user;
      this.pwd = password;
      this.utName = utName;
      this.dsName = dsName;
      this.serviceURL = serviceURL;

      // set up a ctx to lookup the local/in-session objects
      if (inSessionLookupctx == null)
        setInSessionLookupContext ();

      // setup a ctx to lookup the remote objects
      if (remoteLookupCtx == null)
        setRemoteLookupInitialContext ();

      // lookup the usertransaction
      if (utName != null)
        ut = (UserTransaction)inSessionLookupctx.lookup (utName);

      // get a connection to the local DB
      if (dsName != null)
        ds = (DataSource)inSessionLookupctx.lookup (dsName);
    } catch (NamingException e) {
      e.printStackTrace ();
      throw new SQLError ("setUpDSConnection failed:" + e.toString ());
    }
  }

  public void setRemoteObject (String objName) 
       throws SQLError
  {
    if (remoteLookupCtx == null) 
      throw new SQLError ("setRemoteObject: context is null");
    if (serviceURL == null) 
      throw new SQLError ("setRemoteObject: serviceURL is null");

    try {
      if (remoteEmployee == null)
        remoteEmployee = (Employee)remoteLookupCtx.lookup (serviceURL + 
                                                           objName);
      remoteEmployee.initialize (user, pwd, serviceURL, utName, dsName);
    } catch (NamingException e) {
      e.printStackTrace ();
      throw new SQLError ("setRemoteObject: " + e.toString ());
    }
    return;
  }

  public EmployeeInfo getEmployee (String name) 
       throws SQLError
  {
    System.out.println ("getEmployee: begin");
    this.startTrans ();

    EmployeeInfo info = this.doSelect (name);
    System.out.println ("getEmployee: end");
    return info;
  }

  public EmployeeInfo getRemoteEmployee (String name)
       throws SQLError
  {
    System.out.println ("getRemoteEmployee: begin");
    if (remoteEmployee == null)
      throw new SQLError ("updateRemoteEmployee--remoteEmployee is NULL");

    EmployeeInfo info = remoteEmployee.getEmployee (name); 
    System.out.println ("getRemoteEmployee: end " + info.name + "  " + 
                        info.salary);

    this.commitTrans ();
    return info;
  }

  public void updateEmployee (EmployeeInfo empInfo)
       throws SQLError
  {
    System.out.println ("updateEmployee: begin");
    this.startTrans ();

    try {
      System.out.println ("  Before updating: ");
      this.doSelect (empInfo.name);

      #sql { update emp set ename = :(empInfo.name), sal = :(empInfo.salary)
                    where empno = :(empInfo.number) };
      System.out.println ("  After updating: ");
      this.doSelect (empInfo.name);
    } catch (SQLException e) {
      System.out.println ("updateEmployee: end with SQLException");
      e.printStackTrace ();
      throw new SQLError ("updateEmployee failed: " + e.toString ());
    }
    System.out.println ("updateEmployee: end");
  }

  public void updateRemoteEmployee (EmployeeInfo empInfo)
       throws SQLError
  {
    System.out.println ("updateRemoteEmployee: begin");
    if (remoteEmployee == null)
      throw new SQLError ("updateRemoteEmployee--remoteEmployee is NULL");
    
    remoteEmployee.updateEmployee (empInfo);
    System.out.println ("updateRemoteEmployee: end");
    this.commitTrans ();
    return;
  }

  private void getLocalDBConenction ()
       throws SQLError
  {
    try {
      if (ds == null)
        throw new SQLError ("datasource is not set");
      // get a connection to the local DB
      ((OracleJTADataSource)ds).setURL ("jdbc:oracle:kprb:");
      conn = ds.getConnection ();
    } catch (SQLException e) {
      System.out.println ("getLocalDBConenction: end: with SQLException");
      e.printStackTrace ();
      throw new SQLError (e.toString ());
    }
  }

  private void startTrans () 
       throws SQLError 
  {
    try {
      if (ut == null)
        throw new SQLError ("startTrans: userTransaction is null");

      // start a new-transaction iff no-txn is associated with the thread
      if (ut.getStatus () == Status.STATUS_NO_TRANSACTION)
        ut.begin ();

      // get the local-db connection--To enlist with the TM
      this.getLocalDBConenction ();
    } catch (Exception e) {
      throw new SQLError ("startTrans failed:" + e.toString ());
    }
  }

  private void commitTrans ()
       throws SQLError
  {
    try {
      ut.commit ();
    } catch (Exception e) {
      throw new SQLError ("commitTrans failed:" + e.toString ());
    }
  }

  private EmployeeInfo doSelect (String name)
       throws SQLError
  {
    try {
      int empNo = 0;
      double empSalary = 0.0;
      #sql { select empno, sal into :empNo, :empSalary from emp
             where ename = :name };
      System.out.println ("  (" + name + ", " + empSalary + ")");
      return new EmployeeInfo (name, empNo, (float)empSalary);
    } catch (SQLException e) {
      System.out.println ("getEmployee: end: with SQLException");
      e.printStackTrace ();
      throw new SQLError (e.toString ());
    }
  }
}

JTS Transaction Example

Employee.IDL

module employee {
  struct EmployeeInfo {
    wstring name;
    long number;
    double salary; 
  };

  exception SQLError {
    wstring message;
  };

  interface Employee {
    EmployeeInfo getEmployee (in wstring name) raises (SQLError);
    EmployeeInfo getEmployeeForUpdate (in wstring name) raises (SQLError);
    void updateEmployee (in EmployeeInfo name) raises (SQLError);
  };
};

Client.java

import employee.*;

import oracle.aurora.jndi.sess_iiop.ServiceCtx;

import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;

public class Client
{
  public static void main (String[] args) throws Exception {
    if (args.length != 4) {
      System.out.println ("usage: Client serviceURL objectName user password");
      System.exit (1);
    }
    String serviceURL = args [0];
    String objectName = args [1];
    String user = args [2];
    String password = args [3];

    // get the handle to the InitialContext
    Hashtable env = new Hashtable ();
    env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put (Context.SECURITY_PRINCIPAL, user);
    env.put (Context.SECURITY_CREDENTIALS, password);
    env.put (Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
    Context ic = new InitialContext (env);

    // This is using Server-side TX services, specifically, JTS/XA TX:

    // get handle to the object and it's info
    Employee employee = (Employee)ic.lookup (serviceURL + objectName);

    // get the info about a specific employee
    EmployeeInfo info = employee.getEmployee ("SCOTT");
    System.out.println ("Beginning salary = " + info.salary);
    System.out.println ("Decrease by 10%");
    // do work on the object or it's info
    info.salary -= (info.salary * 10) / 100;

    // call update on the server-side
    employee.updateEmployee (info);

    System.out.println ("Final Salary = " + info.salary);
  }
}

Server

package employeeServer;

import employee.*;
import java.sql.*;

import oracle.aurora.jts.util.*;
import org.omg.CosTransactions.*;

public class EmployeeImpl extends _EmployeeImplBase 
{
  Control c;
 
  private void startTrans () throws SQLError {
    try {
      TS.getTS ().getCurrent ().begin ();
    } catch (Exception e) {
      throw new SQLError ("begin failed:" + e);
    }
  }

  private void commitTrans () throws SQLError {
    try {
      TS.getTS ().getCurrent ().commit (true);
    } catch (Exception e) {
      throw new SQLError ("commit failed:" + e);
    }
  }
  
  public EmployeeInfo getEmployee (String name) throws SQLError {
    try {
      startTrans ();

      int empno = 0;
      double salary = 0.0;
      #sql { select empno, sal into :empno, :salary from emp
                    where ename = :name };
      c = TS.getTS().getCurrent().suspend();
      return new EmployeeInfo (name, empno, (float)salary);
    } catch (SQLException e) {
      throw new SQLError (e.getMessage ());
    } catch (Exception e) {
      throw new SQLError (e.getMessage());
    }
  }

  public EmployeeInfo getEmployeeForUpdate (String name) throws SQLError {
    try {
      startTrans ();

      int empno = 0;
      double salary = 0.0;
      #sql { select empno, sal into :empno, :salary from emp
                    where ename = :name for update };
      return new EmployeeInfo (name, empno, (float)salary);
    } catch (SQLException e) {
      throw new SQLError (e.getMessage ());
    }
  }

  public void updateEmployee (EmployeeInfo employee) throws SQLError {
    try {
      TS.getTS().getCurrent().resume(c);

      #sql { update emp set ename = :(employee.name), sal = :(employee.salary)
                    where empno = :(employee.number) };
      commitTrans ();
    } catch (SQLException e) {
      throw new SQLError (e.getMessage ());
    } catch (Exception e) {
      throw new SQLError (e.getMessage ());
    }
  }
}

SSL Examples

Client-Side Authentication

Hello.IDL

module common {
  interface Hello {
    wstring helloWorld ();
  };
};

Client.java

package client;

import common.Hello;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;

public class Client
{

  public static void main (String[] args) throws Exception {
    if (args.length != 3) {
      System.out.println("usage: Client serviceURL objectName credsFile");
      System.exit(1);
    }
    String serviceURL = args [0];
    String objectName = args [1];
    String credsFile = args [2];

    Hashtable env = new Hashtable();
    env.put(Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put(Context.SECURITY_AUTHENTICATION, ServiceCtx.SSL_CLIENT_AUTH);
    env.put(Context.SECURITY_CREDENTIALS, "welcome");

    // Simply specify  a file that contains all the credential info. This is 
    // the file generated by the wallet manager tool.
    env.put(Context.SECURITY_PRINCIPAL, credsFile);

/*
    // As an alternative, you may also set the credentials individually, as
    // shown bellow.
    env.put(ServiceCtx.SECURITY_USER_CERT, testCert_base64);
    env.put(ServiceCtx.SECURITY_CA_CERT, caCert_base64);
    env.put(ServiceCtx.SECURITY_ENCRYPTED_PKEY, encryptedPrivateKey_base64);
    //System.getProperties().put("AURORA_CLIENT_SSL_DEBUG", "true");
*/

    Context ic = new InitialContext(env);

    Hello hello = (Hello) ic.lookup(serviceURL + objectName);
    System.out.println(hello.helloWorld());
  }
}

Server

package server;

import common.*;

public class HelloImpl extends _HelloImplBase {
  public String helloWorld() {
    String v = System.getProperty("oracle.server.version");
    return "Hello client, your javavm version is " + v + ".";
  }
}

Server-Side Authentication

This example includes setting a trustpoint. If you do not want to involve trustpoints, just remove the section of the code that sets the trustpoint.

Hello.IDL

module common {
  interface Hello {
    wstring helloWorld ();
  };
};

Client.java

package client;

import common.Hello;
import java.util.Hashtable;
import java.io.*;
import java.security.cert.*;  // for JDK 1.2
//import javax.security.cert.*;  // for JDK 1.1
import javax.naming.Context;
import javax.naming.InitialContext;
import oracle.aurora.ssl.*;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;
import oracle.aurora.jndi.sess_iiop.SessionCtx;
import oracle.aurora.AuroraServices.LoginServer;


public class Client
{
   private static String trustedCert =  
"MIIB1jCCAYCgAwIBAgIQQQFhvgccFLBfXGa6Y/iSGzANBgkqhkiG9w0BAQQFADBsMQswCQYDVQQG"+
"EwJVUzEPMA0GA1UEChQGT3JhY2xlMSkwJwYDVQQLFCBFbnRlcnByaQpzZSBBcHBsaWNhdGlvbiBT"+
"ZXJ2aWNlczEhMB8GA1UEAxQYRUFTUUEgQ2VydGlmaWNhdGUgU2VydmVyMB4XDTAwMDcyODIzMDA0"+
"OVoXDTAzMDcwNzIzMDA0OVowbDELMAkGA1UEBhMCVVMxDzANBgNVBAoUBk9yYWNsZTEpMCcGA1UE"+
"CxQgRW50ZXJwcmkKc2UgQXBwbGljYXRpb24gU2VydmljZXMxITAfBgNVBAMUGEVBU1FBIENlcnRp"+
"ZmljYXRlIFNlcnZlcjBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCy+w2AxY8u5kKI3rco9PWNr1Bb"+
"C3bwFZzd4+sdTqyHDy8Y2t2E7qfg9CwBO5ki530vT4ImH5x6lhbPN4QbcfgRAgMBAAEwDQYJKoZI"+
"hvcNAQEEBQADQQAYMohM/rz5ksAeorTw9qDcfH2TV6Qu0aXBvNJqBT5x4RvwLWYGMzcy77uSkiM1"+
"NkF3xY7MfZGqObKE3NQNgEuK";


 static boolean verifyPeerCert(org.omg.CORBA.Object obj) throws Exception
 {
   org.omg.CORBA.ORB orb = oracle.aurora.jndi.orb_dep.Orb.init();

   // Get the SSL current 
   AuroraCurrent current = AuroraCurrentHelper.narrow
       (orb.resolve_initial_references("AuroraSSLCurrent"));
      
   // Check the cipher
   System.out.println("Negotiated Cipher:  " + 
                      current.getNegotiatedCipherSuite(obj));
   // Check the protocol version
   System.out.println("Protocol Version:   " + 
                      current.getNegotiatedProtocolVersion(obj));
   // Check the peer's certificate
   System.out.println("The account obj's certificate chain : "); 
   byte [] [] certChain = current.getPeerDERCertChain(obj);
   System.out.println("length : " + certChain.length);
   System.out.println("Certificates: ");

   // JDB 1.2 way
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   for(int i = 0; i < certChain.length; i++) {
     ByteArrayInputStream bais = new ByteArrayInputStream(certChain[i]);
     Certificate  xcert = cf.generateCertificate(bais); 
     System.out.println(xcert);
     if(xcert instanceof X509Certificate) 
     {
       X509Certificate x509Cert = (X509Certificate)xcert;
       String globalUser = x509Cert.getSubjectDN().getName();
       System.out.println("DN out of the cert : " + globalUser); 
     }
   }

   // JDK 1.1 way
/*
   java.security.Security.setProperty("cert.provider.x509v1", 
                    "oracle.security.cert.X509CertificateImpl");
   for(int i = 0; i < certChain.length; i++) {
   javax.security.cert.X509Certificate cert = 
      javax.security.cert.X509Certificate.getInstance(certChain[i]);
   String globalUser = cert.getSubjectDN().getName();
   System.out.println("DN out of the cert : " + globalUser); 
   }
*/

   
   return true;
 }

  public static void main (String[] args) throws Exception {
    if (args.length != 2) {
      System.out.println("usage: Client serviceURL objectName");
      System.exit(1);
    }
    String serviceURL = args [0];
    String objectName = args [1];

    Hashtable env = new Hashtable();
    env.put(Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    env.put(Context.SECURITY_AUTHENTICATION, ServiceCtx.SSL_LOGIN);
    env.put(Context.SECURITY_PRINCIPAL, "scott");
    env.put(Context.SECURITY_CREDENTIALS, "tiger");
    
    // setup the trust point
    env.put(ServiceCtx.SECURITY_TRUSTED_CERT, trustedCert);

    Context ic = new InitialContext(env);

    // Make an SSL connection to the server first. If the connection
    // succeeds, then inspect the  server's certificate, since we haven't
    // specified a trust point.
    // Get a SessionCtx that represents a database instance
    ServiceCtx service = (ServiceCtx)ic.lookup (serviceURL);
    SessionCtx session1 = (SessionCtx)service.createSubcontext (":session1");
    // Lookup login object for the purpose of getting hold of some corba 
    // object needed for verifyPeerCert(). We should provide an extension
    // to just getting the NS object, for this purpose.
    LoginServer obj = (LoginServer) session1.activate("/etc/login");

    if(!verifyPeerCert(obj))
      throw new org.omg.CORBA.COMM_FAILURE("Verification of Peer cert failed");

    // Now that we trust the server, let's go ahead and do our business.
    session1.login();
    Hello hello = (Hello) session1.activate(objectName);
    System.out.println(hello.helloWorld());
  }
}

Server

package server;

import common.*;

public class HelloImpl extends _HelloImplBase {
  public String helloWorld() {
    String v = System.getProperty("oracle.server.version");
    return "Hello client, your javavm version is " + v + ".";
  }
}

Session Example

You can manage sessions in multiple ways, which are all discussed in "Session Management Scenarios". The example presented here demonstrates how to access two sessions from a single client.

Hello.IDL

module common
{
  interface Hello
  {
    wstring helloWorld();
    void setMessage(in wstring message);
  };
};

Client.java

package client;

import common.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;
import oracle.aurora.jndi.sess_iiop.SessionCtx;
import oracle.aurora.AuroraServices.LoginServer;
import oracle.aurora.client.Login;

public class Client
{
  public static void main (String[] args) throws Exception
  {
    if (args.length != 4) {
      System.out.println ("usage: Client user password GIOP_SERVICE 
corbaPubname"); System.exit (1); } String user = args[0]; String password = args[1]; String GIOP_SERVICE = args[2]; String corbaPubname = args[3]; // Prepare a simplified Initial Context as we are going to do // everything by hand Hashtable env = new Hashtable (); env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi"); Context ic = new InitialContext (env); // Get a SessionCtx that represents a database instance ServiceCtx service = (ServiceCtx) ic.lookup(GIOP_SERVICE); // Create and authenticate a first session in the instance. SessionCtx session1 = (SessionCtx)service.createSubcontext (":session1"); LoginServer login_server1 = (LoginServer)session1.activate ("etc/login"); Login login1 = new Login (login_server1); login1.authenticate (user, password, null); // Create and authenticate a second session in the instance. SessionCtx session2 = (SessionCtx)service.createSubcontext (":session2"); LoginServer login_server2 = (LoginServer)session2.activate ("etc/login"); Login login2 = new Login (login_server2); login2.authenticate (user, password, null); // Activate one Hello object in each session Hello hello1 = (Hello)session1.activate (corbaPubname); Hello hello2 = (Hello)session2.activate (corbaPubname); // Verify that the objects are indeed different hello1.setMessage ("Hello from Session1"); hello2.setMessage ("Hello from Session2"); System.out.println (hello1.helloWorld ()); System.out.println (hello2.helloWorld ()); } }

Server

package server;

import common.*;
import oracle.aurora.AuroraServices.ActivatableObject;

public class HelloImpl extends _HelloImplBase implements ActivatableObject 
{
  String message;

  public String helloWorld()
  {
    return message;
  }

  public void setMessage(String message)
  {
    this.message = message;
  }

  public org.omg.CORBA.Object _initializeAuroraObject()
  {
    return this;
  }
}

Applet Example

JDK and JInitiator Applets

HTML for JDK 1.1

<pre>
<html>
<title> CORBA Applet talking to 9i</title>
<h1> CORBA applet talking to 9i using java plug in 1.1  </h1>
<hr>
The good old bank example
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = 500 HEIGHT = 50  codebase="http://java.sun.com/products/plugin/1.1/jinst
all-11-win32.cab#Version=1,1,0,0">
<PARAM NAME = CODE VALUE = OracleClientApplet.class >
<PARAM NAME = ARCHIVE VALUE = "oracleClient.jar,aurora_client.jar,vbjorb.jar,vbj
app.jar" >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.1">
<PARAM NAME="ORBdisableLocator" VALUE="true">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.1"
ORBdisableLocator="true" java_CODE = OracleClientApplet.class java_ARCHIVE = "or
acleClient.jar,aurora_client.jar,vbjorb.jar,vbjapp.jar" WIDTH = 500 HEIGHT = 50
  pluginspage="http://java.sun.com/products/plugin/1.1/plugin-install.html">
<NOEMBED></COMMENT>
</NOEMBED></EMBED>
</OBJECT>

</center>
<hr>
</pre>

HTML for JDK 1.2

<pre>
<html>
<title> CORBA applet talking to 9i</title>
<h1> CORBA applet talking to 9i using Java plug in 1.2 </h1>
<hr>
The good old bank example
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = 500 HEIGHT = 50  codebase="http://java.sun.com/products/plugin/1.2/jinst
all-11-win32.cab#Version=1,1,0,0">
<PARAM NAME = CODE VALUE = OracleClientApplet.class >
<PARAM NAME = ARCHIVE VALUE = "oracleClient.jar,aurora_client.jar,vbjorb.jar,vbj
app.jar" >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.1.2">
<PARAM NAME="ORBdisableLocator" VALUE="true">
<PARAM NAME="org.omg.CORBA.ORBClass" VALUE="com.visigenic.vbroker.orb.ORB">
<PARAM NAME="org.omg.CORBA.ORBSingletonClass" VALUE="com.visigenic.vbroker.orb.O
RB">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.1.2"
ORBdisableLocator="true"
org.omg.CORBA.ORBClass="com.visigenic.vbroker.orb.ORB"
org.omg.CORBA.ORBSingletonClass="com.visigenic.vbroker.orb.ORB" java_CODE = Orac
leClientApplet.class java_ARCHIVE = "oracleClient.jar,aurora_client.jar,vbjorb.j
ar,vbjapp.jar" WIDTH = 500 HEIGHT = 50   pluginspage="http://java.sun.com/produc
ts/plugin/1.2/plugin-install.html">
<NOEMBED></COMMENT>
</NOEMBED></EMBED>
</OBJECT>

</center>
<hr>
</pre>

HTML for Oracle JInitiator

<h1>CORBA applet talking to 9i using JInitiator 1.1.7.18</h1>
   <COMMENT>
   <EMBED   type="application/x-jinit-applet;version=1.1.7.18"
      java_CODE="OracleClientApplet"
      java_CODEBASE="http://mysun:8080/applets/bank"
      java_ARCHIVE="oracleClient.jar,aurora_client.jar,vbjorb.jar,vbjapp.jar"
      WIDTH=400
      HEIGHT=100
      ORBdisableLocator="true"
      org.omg.CORBA.ORBClass="com.visigenic.vbroker.orb.ORB"
      org.omg.CORBA.ORBSingletonClass="com.visigenic.vbroker.orb.ORB"
      serverHost="mysun"
      serverPort=8080
      <NOEMBED>
      </COMMENT>
      </NOEMBED>
    </EMBED>

Applet Client

// ClientApplet.java

import java.awt.*;

import oracle.aurora.jndi.sess_iiop.ServiceCtx;

import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;
import Bank.*;

public class OracleClientApplet extends java.applet.Applet {

  private TextField _nameField, _balanceField;
  private Button _checkBalance;
  private Bank.AccountManager _manager;

  public void init() {
    // This GUI uses a 2 by 2 grid of widgets.
    setLayout(new GridLayout(2, 2, 5, 5));
    // Add the four widgets.
    add(new Label("Account Name"));
    add(_nameField = new TextField());
    add(_checkBalance = new Button("Check Balance"));
    add(_balanceField = new TextField());
    // make the balance text field non-editable.
    _balanceField.setEditable(false);
    try {
      String serviceURL = "sess_iiop://mysun:2222";
      String objectName = "/test/myBank";

      // Initialize the ORB (using the Applet).
      Hashtable env = new Hashtable();
      env.put(Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
      env.put(Context.SECURITY_PRINCIPAL, "scott");
      env.put(Context.SECURITY_CREDENTIALS, "tiger");
      env.put(Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
      env.put(ServiceCtx.APPLET_CLASS, this);
      
      Context ic = new InitialContext(env);
    _manager = (AccountManager)ic.lookup (serviceURL + objectName);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      throw new RuntimeException();
    }
  }

  public boolean action(Event ev, Object arg) {
    if(ev.target == _checkBalance) {
      // Request the account manager to open a named account.
      // Get the account name from the name text widget.
      Bank.Account account = _manager.open(_nameField.getText());
      // Set the balance text widget to the account's balance.
      _balanceField.setText(Float.toString(account.balance()));
      return true;
    }
    return false;
  }

}

Visigenic Applet

README

To run VisiClient applet, you need to do the following.

Start osagent and gatekeeper (with port 16000)
(for gate keeper, create a file called gatekeeper.properties and just
put this entry in there : exterior_port=16000)

Then start the Bank server (vbj Server &).

Your browser should have Jinitiator installed (use ojdk-pc.us.oracle.com
for getting JInitiator, jdk 1.1.7.18)
(Browser security doesn't have to be off, i.e, you may set it to
AppletHost in Jinitiator)

Then simply connect to  mysun:8080/applets/bank/VisiClient.html

HTML for Visigenic Client Applet

<h1>Visigenic Client applet</h1>
   <COMMENT>
   <EMBED   type="application/x-jinit-applet;version=1.1.7.18"
      java_CODE="VisiClientApplet"
      java_CODEBASE="http://mysun:8080/applets/bank"
      java_ARCHIVE="visiClient.jar,vbjorb.jar,vbjapp.jar"
      WIDTH=400
      HEIGHT=100
      ORBgatekeeperIOR="http://mysun:16000/gatekeeper.ior"
      USE_ORB_LOCATOR="true"
      ORBbackCompat="true"
      serverHost="mysun"
      serverPort=8080
      <NOEMBED>
      </COMMENT>
      </NOEMBED>
    </EMBED>

Visigenic Client Applet

// ClientApplet.java

import java.awt.*;

public class VisiClientApplet extends java.applet.Applet {

  private TextField _nameField, _balanceField;
  private Button _checkBalance;
  private Bank.AccountManager _manager;

  public void init() {
    // This GUI uses a 2 by 2 grid of widgets.
    setLayout(new GridLayout(2, 2, 5, 5));
    // Add the four widgets.
    add(new Label("Account Name"));
    add(_nameField = new TextField());
    add(_checkBalance = new Button("Check Balance"));
    add(_balanceField = new TextField());
    // make the balance text field non-editable.
    _balanceField.setEditable(false);
    // Initialize the ORB (using the Applet).
    org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(this, null);
    // Locate an account manager.
    _manager = Bank.AccountManagerHelper.bind(orb, "BankManager");
  }

  public boolean action(Event ev, Object arg) {
    if(ev.target == _checkBalance) {
      // Request the account manager to open a named account.
      // Get the account name from the name text widget.
      Bank.Account account = _manager.open(_nameField.getText());
      // Set the balance text widget to the account's balance.
      _balanceField.setText(Float.toString(account.balance()));
      return true;
    }
    return false;
  }

}


Go to previous page Go to next page
Oracle
Copyright © 1996-2001, Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Product List
Book List
Go To Table Of Contents
Contents
Go To Index
Index

Master Index

Feedback