Oracle8i Enterprise JavaBeans and CORBA Developer's Guide
Release 8.1.5

A64683-01

Library

Product

Contents

Index

Prev  Chap Top Next

Basic Examples

helloworld

readme.txt

Overview
========

This is the most basic program that you can create for the Orcale8i
EJB server. One bean, HelloBean, is implemented. The bean and
associated classes are loaded into the database, and the bean home
interface is published as /test/myHello, as specified in the bean
deployment descriptor hello.ejb.

The bean contains a single method: helloWorld, which simply returns a
String containing the JavaVM version number to the client that invokes
it.

This example shows the minimum number of files that you must provide
to implement an EJB application: five. The five are:

(1) the bean implementation:    helloServer/HelloBean.java in this example
(2) the bean remote interface:  hello/Hello.java
(3) the bean home interface:    hello/HelloHome.java
(4) the deployment descriptor:  hello.ejb
(5) a client app or applet:     Client.java is the application in this example



Source Files
============


Client.java
-----------

You invoke the client program from a command prompt, and pass it four
arguments, the

   - service URL (service ID, hostname, port, and SID if port is a listener)
   - name of the published bean to lookup and instantiate
   - username
   - password that authenticates the client to the Oracle8i database server

For example:
% java -classpath LIBs Client sess_iiop://localhost:2222 /test/myHello scott 
tiger

where LIBs is the classpath that must include

$ORACLE_HOME/lib/aurora_client.jar
$ORACLE_HOME/jdbc/lib/classes111.zip
$ORACLE_HOME/lib/vbjorb.jar
$ORACLE_HOME/lib/vbjapp.jar
$JAVA_HOME/lib/classes.zip

(Note: for NT users, the environment variables would be %ORACLE_HOME% and
%JAVA_HOME%.)

The client code performs the following steps:

   - gets the arguments passed on the command line
   - creates a new JNDI Context (InitialContext())
   - looks up the published bean to find and activate its home interface
   - using the home interface, instantiates through its create()
     method a new bean object, hello
   - invokes the helloWorld() method on the hello object and prints the results

The printed output is:

Hello client, your javavm version is 8.1.5.


hello.ejb
---------

The bean deployment descriptor. This source file does the following:

   - shows the class name of the bean implementation in the deployment name:
       helloServer.HelloBean
   - names the published bean "/test/myHello"
   - declares the remote interface implementation: hello.Hello
   - declares the home interface: hello.HelloHome
   - sets RunAsMode to the client's identity (SCOTT in this case)
   - allows all members of the group PUBLIC to run the bean
   - sets the transaction attribute to TX_SUPPORTS

The deployement descriptor is read by the deployejb tool, which uses
it to load the required classes, and publish the bean home
interface. (Deployejb does much else also. See the Tools chapter in
the Oracle8i EJB and CORBA Developer's Guide for more information.)


helloServer/HelloBean.java
--------------------------

This is the EJB implementation. Note that the bean class is public,
and that it implements the SessionBean interface, as required by the
EJB specification.

The bean implements the one method specified in the remote interface:
helloWorld(). This method gets the system property associated with
"oracle.server.version" as a String, and returns a greeting plus the
version number as a String to the invoking client.

The bean implementation also implements ejbCreate() with no parameters,
following the specification of the create() method in hello/HelloHome.java.

Finally, the methods ejbRemove(), setSessionContext(), ejbActivate(), and
ejbPassivate() are implemented as required by the SessionBean interface. In
this simple case, the methods are implemented with null bodies.

(Note that ejbActivate() and ejbPassivate() are never called in the
8.1.5 release of the EJB server, but they must be implemented as
required by the interface.)


hello/Hello.java
----------------

This is the bean remote interface. In this example, it specifies only
one method: helloWorld(), which returns a String object. Note the two
import statements, which are required, and that the helloWorld()
method must be declared as throwing RemoteException. All bean methods
must be capable of throwing this exception. If you omit the
declaration, the deployejb tool will catch it and error when you try
to deploy the bean.


hello/HelloHome.java
--------------------

This is the bean home interface. In this example, a single create()
method is declared. It returns a Hello object, as you saw in the
Client.java code.

Note especially that the create() method must be declared as able to
throw RemoteException and CreateException. These are required. If you
do not declare these, the deployejb tool will catch it and error when
you try to deploy the bean.



Compiling and Running the Example
=================================


UNIX
----

Enter the command 'make all' or simply 'make' in the shell to compile,
load, and deploy the objects, and run the client program.  Other
targets are 'run' and 'clean'.

Make sure that a shell environment variable ORACLE_HOME is set to
point to the home location of the Oracle installation. This is
operating system dependent, so see the Installation documentation that
came with your system for the location. Also, review the README file
for the Oracle database, and the README file for the CORBA/EJB server
(the Oracle8i ORB), for additional up-to-date information.


Windows NT
----------

On Windows NT, run the batch file makeit.bat from a DOS command prompt
to compile, load, and deploy the objects. Run the batch file runit.bat
to run the client program, and see the results.


Make sure that the environment variables %ORACLE_HOME%, %CLASSPATH%,
and %SERVICE% are set appropriately for the DOS command window. You
can set these as either user or system environment variables from the
Control Panel. Double click on System in the Control Panel then on
the Environment tab to set these variables. Start a new DOS window
after setting environment variable values.


See the Installation documentation that came with your Oracle8i system
for the values of these variables. Also, review the README file for
the Oracle database, and the README file for the CORBA/EJB server (the
Oracle8i ORB), for additional up-to-date information.

You can also set an environment variable %JAVA_HOME% to point to the
root of your Java JDK. For example, SET JAVA_HOME=C:\JDK1.1.6.

hello.ejb

SessionBean helloServer.HelloBean
{
  BeanHomeName = "test/myHello";
  RemoteInterfaceClassName = hello.Hello;
  HomeInterfaceClassName = hello.HelloHome;

  AllowedIdentities = { PUBLIC };
  RunAsMode = CLIENT_IDENTITY;
//  TransactionAttribute = TX_SUPPORTS;
}

Client.java

import hello.Hello;
import hello.HelloHome;

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];

    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);

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

helloServer/HelloBean.java

package helloServer;

import javax.ejb.SessionBean;
import javax.ejb.CreateException;
import javax.ejb.SessionContext;
import java.rmi.RemoteException;

public class HelloBean implements SessionBean
{
  // Methods of the Hello interface
  public String helloWorld () throws RemoteException {
    String v = System.getProperty("oracle.server.version");
    return "Hello client, your javavm version is " + v + ".";
  }

  // Methods of the SessionBean
  public void ejbCreate () throws RemoteException, CreateException {}
  public void ejbRemove() {}
  public void setSessionContext (SessionContext ctx) {}
  public void ejbActivate () {}
  public void ejbPassivate () {}
}

hello/Hello.java

package hello;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Hello extends EJBObject  
{
  public String helloWorld () throws RemoteException;
}

hello/HelloHome.java

package hello;

import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import java.rmi.RemoteException;

public interface HelloHome extends EJBHome
{
  public Hello create () throws RemoteException, CreateException;
}

saveHandle

readme.txt

Overview
========

This example shows how a client program can get a bean handle, using
getHandle(), and write it out to a file. A second client then reads the bean
handle, and accesses the first client's bean.

For simplicity, the example simply writes the bean handle out to a file. In a
'real' program, you would use some other less kludgy but more complicated
means to pass the bean handle.

This example uses SSL_CREDENTIAL authentication for both clients, so the
Oracle server must have access to a cwallet.sso SSL credential for the example
to run.

Also, the session that the first client creates) must still be alive when
Client2 runs, so you have 60 seconds to run Client2 after Client1 prints its
message. (60 seconds is the timeout value set in the deployment descriptor.)

(See the timeout example in the ejb session directory for a way to keep a
session alive programmatically after the client terminates. You can also set a
high value in the SessionTimeout attribute in the deployment descriptor.)


Source Files
============

Client1.java
-----------

You invoke the first client program from a command prompt, and pass it five
arguments, the

   - service URL (service ID, hostname, port, and SID if port is a listener)
   - name of the published bean to lookup and instantiate
   - database username
   - password that authenticates the client to the Oracle8i database server
   - the name of a file to hold the bean handle

For example:
% java -classpath LIBs Client1 sess_iiop://localhost:2481:ORCL \
    /test/saveHandle scott tiger handlefile.dat

where LIBs is the classpath that must include

$ORACLE_HOME/lib/aurora_client.jar
$ORACLE_HOME/jdbc/lib/classes111.zip
$ORACLE_HOME/lib/vbjorb.jar
$ORACLE_HOME/lib/vbjapp.jar
$ORACLE_HOME/lib/vbj30ssl.jar
$JAVA_HOME/lib/classes.zip

The client code performs the following steps:

   - gets the arguments passed on the command line
   - creates a new JNDI Context (InitialContext())
   - looks up the published bean to find and activate its home interface
   - using the home interface, instantiates through its create()
     method a new bean object, testBean
   - sets up an object output stream, using the file name supplied
   - writes the bean handle to the output as an object
   - invokes the query method on the test bean, and prints the results
   - updates the employee's salary

The printed output from Client1 is:

Client1: 7499 (ALLEN) has salary 2600.0


Client2.java
------------

Client2 is called with four arguments. They are:

   - the service URL
   - the username
   - the password
   - the name of the file from which to read the bean handle

Client2 reads the bean handle from the file, and invokes the query() method on
the bean that that gets.

The printed output from Client2 is:

Client2: read the bean handle from the file.
Client2: 7499 (ALLEN) now has salary 3100.0


saveHandle.ejb
--------------

The deployment descriptor for the bean.  If the SessionTimeout attribute is
commented out, that is a work-around for an 8.1.4 bug.


save/saveHandle.java
--------------------

The bean remote interface. Specifies the query() and update() methods that are
implemented in saveHandleServer/saveHandleBean.java.


save/saveHandleHome.java
------------------------

The bean home interface. Specifies the query() and update() methods that are
implemented in saveHandleServer/saveHandleBean.java.


saveHandleServer/saveHandleBean.sqlj
------------------------------------

The bean implementation.


saveHandleServer/EmpRecord.java
-------------------------------

The class that the update() method of the bean returns.



Compiling and Running the Example
=================================


UNIX
----

Enter the command 'make all' or simply 'make' in the shell to compile, load,
and deploy the objects, and run the client program.  Other targets are 'run'
and 'clean'.

Make sure that a shell environment variable ORACLE_HOME is set to point to the
home location of the Oracle installation. This is operating system dependent,
so see the Installation documentation that came with your system for the
location. Also, review the README file for the Oracle database, and the README
file for the CORBA/EJB server (the Oracle8i ORB), for additional up-to-date
information.


Windows NT
----------

On Windows NT, run the batch file makeit.bat from a DOS command prompt to
compile, load, and deploy the objects. Run the batch file runit.bat to run the
client program, and see the results.


Make sure that the environment variables %ORACLE_HOME%, %CLASSPATH%, and
%SERVICE% are set appropriately for the DOS command window. You can set these
as either user or system environment variables from the Control Panel. Double
click on System in the Control Panel then on the Environment tab to set these
variables. Start a new DOS window after setting environment variable values.


See the Installation documentation that came with your Oracle8i system
for the values of these variables. Also, review the README file for
the Oracle database, and the README file for the CORBA/EJB server (the
Oracle8i ORB), for additional up-to-date information.

You can also set an environment variable %JAVA_HOME% to point to the
root of your Java JDK. For example, SET JAVA_HOME=C:\JDK1.1.6.

saveHandle.ejb

// saveHandle EJB deployment descriptor.

SessionBean saveHandleServer.saveHandleBean {
  BeanHomeName = "test/saveHandle";
  RemoteInterfaceClassName = save.saveHandle;
  HomeInterfaceClassName = save.saveHandleHome;

  AllowedIdentities = {SCOTT};

  SessionTimeout = 60;
  StateManagementType = STATEFUL_SESSION;

  RunAsMode = CLIENT_IDENTITY;

  public save.EmpRecord query (int e) throws SQLException { 
    TransactionAttribute = TX_REQUIRED;
    RunAsMode = CLIENT_IDENTITY;      
    AllowedIdentities = { SCOTT };
  }

  public void update (int e, double s) throws SQLException { 
    TransactionAttribute = TX_REQUIRED;
    RunAsMode = CLIENT_IDENTITY;      
    AllowedIdentities = { SCOTT };
  }

  public String getMessage() throws RemoteException {
    RunAsMode = CLIENT_IDENTITY;      
    AllowedIdentities = { SCOTT };
  }

  public void setMessage(String message) throws RemoteException {
    RunAsMode = CLIENT_IDENTITY;      
    AllowedIdentities = { SCOTT };
  }
}


Client1.java

import save.saveHandle;
import save.saveHandleHome;
import save.EmpRecord;

import java.io.*;

import oracle.aurora.jndi.sess_iiop.ServiceCtx;

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


public class Client1 {
  public static void main (String [] args) throws Exception {
    int empNumber = 7499;  // ALLEN

    if (args.length != 5) {
      System.out.println("usage: Client serviceURL objectName user password"
			 + " handlefile");
      System.exit(1);
    }
    String serviceURL = args [0];
    String objectName = args [1];
    String user = args [2];
    String password = args [3];
    String handlefile = 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.SSL_CREDENTIAL);
    Context ic = new InitialContext(env);

    // Access the Bean
    saveHandleHome home = (saveHandleHome)ic.lookup (serviceURL + objectName);
    saveHandle testBean = home.create ();

    // Save the bean handle to a file.
    FileOutputStream fostream = new FileOutputStream (handlefile);
    ObjectOutputStream ostream = new ObjectOutputStream (fostream);
    ostream.writeObject (testBean.getHandle ());
    ostream.flush ();
    fostream.close ();

    // Get name and current salary.
    EmpRecord empRec = testBean.query(empNumber);
    System.out.print("Client1: ");
    System.out.println(empRec.empno + " (" + empRec.ename
		       + ") has salary " + empRec.sal);
    
    // Increase ALLEN's salary.
    testBean.update (empNumber, empRec.sal + 500.00);
    testBean.setMessage("Client1 updated 7499's salary/");
    // Sleep 30 seconds to let Client2 connect to the SessionBean
    //    Thread.sleep (30000);
  }
}


Client2.java

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

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

import save.saveHandle;
import save.saveHandleHome;
import save.EmpRecord;


public class Client2 {
  public static void main (String [] args) throws Exception {
    int empNumber = 7499;     // ALLEN

    if (args.length != 4) {
      System.out.println("usage: Client serviceURL username password"
			 + " handlefile");
      System.exit(1);
    }
    String serviceURL = args [0];
    String username = args [1];
    String password = args [2];
    String handlefile = args [3];

    Hashtable env = new Hashtable();
    env.put (Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    Context ic = new InitialContext (env);
    ServiceCtx service = (ServiceCtx)ic.lookup (serviceURL);

    // Initialize the service context to authenticate. Role and props
    // are null. Use SSL credential authentication.
    service.init (username, password, null, true, null);

    // Get a ref to the bean, by reading the file.
    FileInputStream finstream = new FileInputStream (handlefile);
    ObjectInputStream istream = new ObjectInputStream (finstream);
    javax.ejb.Handle handle  = (javax.ejb.Handle)istream.readObject ();
    finstream.close ();
    saveHandle bean = (saveHandle)handle.getEJBObject ();
    System.out.println ("Client2: read the bean handle from the file.");

    // Run the query on the bean handle.
    EmpRecord empRec = bean.query (empNumber);
    System.out.println("Client2: " + bean.getMessage());
    System.out.println("Client2: " +
        empRec.empno + " (" + empRec.ename +
        ") now has salary " + empRec.sal);

  }
}


save/saveHandle.java

package save;

import saveHandleServer.EmpRecord;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface saveHandle extends EJBObject  {

  public EmpRecord query (int empNumber)
       throws java.sql.SQLException, RemoteException;

  public void update (int empNumber, double newSalary)
       throws java.sql.SQLException, RemoteException;

}


save/saveHandleHome.java

package save;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface saveHandleHome extends EJBHome {
  public saveHandle create()
       throws CreateException, RemoteException;
}


save/EmpRecord.java

package save;

import java.rmi.*;

public class EmpRecord implements java.io.Serializable {
  public String ename;
  public int empno;
  public double sal;

  public EmpRecord (String ename, int empno, double sal) {
    this.ename = ename;
    this.empno = empno;
    this.sal = sal;
  }
}

save/saveHandle.java

package save;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface saveHandle extends EJBObject  {

  public EmpRecord query (int empNumber)
       throws java.sql.SQLException, RemoteException;

  public void update (int empNumber, double newSalary)
       throws java.sql.SQLException, RemoteException;

  public String getMessage()
       throws RemoteException;

  public void setMessage(String message)
       throws RemoteException;
}


saveHandleServer/saveHandleBean.sqlj

package saveHandleServer;

import save.EmpRecord;

import java.sql.*;
import java.rmi.RemoteException;
import javax.ejb.*;

#sql iterator EmpIter (int empno, String ename, double sal);

public class saveHandleBean implements SessionBean {
  String message = "No message";
  SessionContext ctx;

  public void update(int empNumber, double newSalary)
       throws SQLException, RemoteException
  {
    #sql {update emp set sal = :newSalary where empno = :empNumber};
  }

  public EmpRecord query (int empNumber) throws SQLException, RemoteException
  {
    String ename;
    double sal;

    #sql { select ename, sal into :ename, :sal from emp 
                  where empno = :empNumber }; 

    return new EmpRecord (ename, empNumber, sal);
  }

  public String getMessage() throws RemoteException {
    return message;
  }

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

  public void ejbCreate() throws CreateException, RemoteException {
  }

  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void ejbRemove() {
  }

  public void setSessionContext(SessionContext ctx) {
    this.ctx = ctx;
  }

}

sqljimpl

readme.txt

Overview
========

This example demonstrates doing a database query using SQLJ. pay
attention to the makefile (UNIX) or the makeit.bat batch file (Windows
NT), and note that the files that SQLJ generates (SER files converted
to class files) must be loaded into the database with deployejb also.

Compare this example with the jdbcimpl basic EJB example, which uses
JDBC instead of SQLJ to perform exactly the same query.


Source files
============

Client.java
-----------

Invoke the client program from the command line, passing it four
arguments:
   - the name of the service URL, e.g. sess_iiop://localhost:2222
   - the path and name of the published bean, e.g. /test/employeeBean
   - the username for db authentication
   - the password (you wouldn't do this in a production program, of course)

For example

% java Client -classpath LIBs sess_iiop://localhost:2222 /test/employeeBean
   scott tiger

The client looks up and activates the bean, then invokes the query() method on
the bean. query() returns an EmpRecord structure with the salary and the name
of the employee whose ID number was passed to query().

There is no error checking in this code. See the User's Guide for more
information about the appropriate kinds of error checking in this kind of
client code.

The client prints:

Emp name is ALLEN
Emp sal  is 3100.0


employeeServer/employeeBean.sqlj
--------------------------------

This class is the bean implementation. A SQLJ named iterator is declared to
hold the results of the query. The myIter.next(); statement is used as is to
keep the code simple: after all the parameter passed in is a known valid
primary key for the EMP table. (See what happens if you try an empno that is
not in the table.)

The EmpIter getter methods are used to retrieve the query results into the
EmpRecord object, which is then returned *by value*, as a serialized object,
to the client.


employeeServer/EmpRecord.java
-----------------------------

A class that is in essence a struct to contain the employee name and salary,
as well as the ID number.

Note that the class *must* be defined as implementing the java.rmi.Serializable
interface, to make it a valid serializable RMI object that can be passed from
server to the client.


employee/employee.java
----------------------

The bean remote interface. 


employee/employeeHome.java
--------------------------

The bean home interface.


Compiling and Running the Example
=================================

UNIX
----

Enter the command 'make all' or simply 'make' in the shell to compile,
load, and deploy the objects, and run the client program.  Other
targets are 'run' and 'clean'.

Make sure that a shell environment variable ORACLE_HOME is set to
point to the home location of the Oracle installation. This is
operating system dependent, so see the Installation documentation that
came with your system for the location. Also, review the README file
for the Oracle database, and the README file for the CORBA/EJB server
(the Oracle8i ORB), for additional up-to-date information.


Windows NT
----------

On Windows NT, run the batch file makeit.bat from a DOS command prompt
to compile, load, and deploy the objects. Run the batch file runit.bat
to run the client program, and see the results.


Make sure that the environment variables %ORACLE_HOME%, %CLASSPATH%,
and %SERVICE% are set appropriately for the DOS command window. You
can set these as either user or system environment variables from the
Control Panel. Double click on System in the Control Panel then on
the Environment tab to set these variables. Start a new DOS window
after setting environment variable values.


See the Installation documentation that came with your Oracle8i system
for the values of these variables. Also, review the README file for
the Oracle database, and the README file for the CORBA/EJB server (the
Oracle8i ORB), for additional up-to-date information.

You can also set an environment variable %JAVA_HOME% to point to the
root of your Java JDK. For example, SET JAVA_HOME=C:\JDK1.1.6.

employee.ejb

// sqljimpl EJB deployment descriptor.

SessionBean employeeServer.EmployeeBean {
  BeanHomeName = "test/employeeBean";
  RemoteInterfaceClassName = employee.Employee;
  HomeInterfaceClassName = employee.EmployeeHome;

  AllowedIdentities = {SCOTT};

  //  SessionTimeout = 20;
  StateManagementType = STATEFUL_SESSION;

  RunAsMode = CLIENT_IDENTITY;

  TransactionAttribute = TX_REQUIRED;
}

Client.java

import employee.Employee;
import employee.EmployeeHome;
import employee.EmpRecord;

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];

    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);

    EmployeeHome home = (EmployeeHome)ic.lookup (serviceURL + objectName);
    Employee testBean = home.create();
    EmpRecord empRec = empRec = testBean.query (7499);
    System.out.println ("Emp name is " + empRec.ename);
    System.out.println ("Emp sal  is " + empRec.sal);
  }
}

employee/Employee.java

package employee;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Employee extends EJBObject  {
  public EmpRecord query (int empNumber)
       throws java.sql.SQLException, RemoteException;
}

employee/EmployeeHome.java

package employee;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface EmployeeHome extends EJBHome {
  public Employee create()
       throws CreateException, RemoteException;
}

employee/EmpRecord.java

package employee;

public class EmpRecord implements java.io.Serializable {
  public String ename;
  public int empno;
  public double sal;

  public EmpRecord (String ename, int empno, double sal) {
    this.ename = ename;
    this.empno = empno;
    this.sal = sal;
  }
}

employeeServer/EmployeeBean.sqlj

package employeeServer;

import employee.EmpRecord;

import java.sql.*;
import java.rmi.RemoteException;
import javax.ejb.*;

public class EmployeeBean implements SessionBean {
  SessionContext ctx;

  public void ejbCreate() throws CreateException, RemoteException {
  }

  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void ejbRemove() {
  }

  public void setSessionContext(SessionContext ctx) {
    this.ctx = ctx;
  }

  public EmpRecord query (int empNumber) throws SQLException, RemoteException
  {
    String ename;
    double sal;

    #sql { select ename, sal into :ename, :sal from emp 
                  where empno = :empNumber }; 

    return new EmpRecord (ename, empNumber, sal);
  }
}

jdbcimpl

readme.txt

Overview
========

This example demonstrates using JDBC in an EJB to do a database query.
This example does a simple query of the database EMP table, using JDBC
methods.

Compare this example with the sqljimpl basic EJB example, which uses
SQLJ instead of JDBC to perform exactly the same query.


Source files
============

Client.java
-----------

Invoke the client program from the command line, passing it four
arguments:
   - the name of the service URL, e.g. sess_iiop://localhost:2222
   - the path and name of the published bean, e.g. /test/employeeBean
   - the username for db authentication
   - the password (you wouldn't do this in a production program, of course)

For example

% java Client -classpath LIBs sess_iiop://localhost:2481:ORCL \
         /test/employeeBean scott tiger

The client looks up and activates the bean, then invokes the query() method on
the bean. query() returns an EmpRecord structure with the salary and the name
of the employee whose ID number was passed to query().

There is no error checking in this code. See the User's Guide for more
information about the appropriate kinds of error checking in this kind of
client code.

The client prints:

Employee name is KING
Employee sal is  5000.0

employeeServer/employeeBean.java
--------------------------------

This class is the bean implementation. A JDBC prepared statement is used
to formulate the query, which contains a WHERE clause.

The result set getter methods are used to retrieve the query results into the
EmpRecord object, which is then returned *by value*, as a serialized object,
to the client.


employeeServer/EmpRecord.java
-----------------------------

A class that is in essence a struct to contain the employee name and salary,
as well as the ID number.

Note that the class *must* be defined as implementing the java.rmi.Serializable
interface, to make it a valid serializable RMI object that can be passed from
server to the client.


employee/employee.java
----------------------

The bean remote interface. 


employee/employeeHome.java
--------------------------

The bean home interface.


Compiling and Running the Example
=================================

UNIX
----

Enter the command 'make all' or simply 'make' in the shell to compile,
load, and deploy the objects, and run the client program.  Other
targets are 'run' and 'clean'.

Make sure that a shell environment variable ORACLE_HOME is set to
point to the home location of the Oracle installation. This is
operating system dependent, so see the Installation documentation that
came with your system for the location. Also, review the README file
for the Oracle database, and the README file for the CORBA/EJB server
(the Oracle8i ORB), for additional up-to-date information.


Windows NT
----------

On Windows NT, run the batch file makeit.bat from a DOS command prompt
to compile, load, and deploy the objects. Run the batch file runit.bat
to run the client program, and see the results.


Make sure that the environment variables %ORACLE_HOME%, %CLASSPATH%,
and %SERVICE% are set appropriately for the DOS command window. You
can set these as either user or system environment variables from the
Control Panel. Double click on System in the Control Panel then on
the Environment tab to set these variables. Start a new DOS window
after setting environment variable values.


See the Installation documentation that came with your Oracle8i system
for the values of these variables. Also, review the README file for
the Oracle database, and the README file for the CORBA/EJB server (the
Oracle8i ORB), for additional up-to-date information.

You can also set an environment variable %JAVA_HOME% to point to the
root of your Java JDK. For example, SET JAVA_HOME=C:\JDK1.1.6.

employee.ejb

// jdbcimpl EJB deployment descriptor

SessionBean employeeServer.EmployeeBean {
  BeanHomeName = "test/employeeJDBCBean";
  RemoteInterfaceClassName = employee.Employee;
  HomeInterfaceClassName = employee.EmployeeHome;

  AllowedIdentities = {SCOTT};

  SessionTimeout = 20;
  StateManagementType = STATEFUL_SESSION;

  RunAsMode = CLIENT_IDENTITY;

  TransactionAttribute = TX_REQUIRED;
}

Client.java

import employee.Employee;
import employee.EmployeeHome;
import employee.EmpRecord;

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];

    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);

    EmployeeHome home = (EmployeeHome)ic.lookup (serviceURL + objectName);
    Employee testBean = home.create ();
    EmpRecord empRec = testBean.query (7839);
    System.out.println ("Employee name is " + empRec.ename);
    System.out.println ("Employee sal is  " + empRec.sal);
  }
}

employee/Employee.java

package employee;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Employee extends EJBObject  {
  public EmpRecord query (int empNumber)
       throws java.sql.SQLException, RemoteException;
}

employee/Employeehome.java

package employee;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface EmployeeHome extends EJBHome {
  public Employee create()
       throws CreateException, RemoteException;
}


employee/EmpRecord.java

package employee;

public class EmpRecord implements java.io.Serializable {
  public String ename;
  public int empno;
  public double sal;

  public EmpRecord (String ename, int empno, double sal) {
    this.ename = ename;
    this.empno = empno;
    this.sal = sal;
  }
}

employeeServer/EmployeeBean.java

package employeeServer;

import employee.EmpRecord;

import java.sql.*;
import java.rmi.RemoteException;
import javax.ejb.*;

public class EmployeeBean implements SessionBean {
  SessionContext ctx;

  public void ejbCreate() throws CreateException, RemoteException {
  }

  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void ejbRemove() {
  }

  public void setSessionContext(SessionContext ctx) {
    this.ctx = ctx;
  }

  public EmpRecord query (int empNumber) throws SQLException, RemoteException
  {
    Connection conn =
      new oracle.jdbc.driver.OracleDriver().defaultConnection ();
    PreparedStatement ps =
      conn.prepareStatement ("select ename, sal from emp where empno = ?");
    try {
      ps.setInt (1, empNumber);
      ResultSet rset = ps.executeQuery ();
      if (!rset.next ())
        throw new RemoteException ("no employee with ID " + empNumber);
      return new EmpRecord (rset.getString (1), empNumber, rset.getFloat (2));
    } finally {
      ps.close();
    }
    //    return null;
  }
}

callback

readme.txt

Overview
========

This example shows how an EJB can do callbacks to the client system. The
callback mechanism uses RMI over IIOP, and the Caffeine tool java2rmi_iiop is
used to generate the required classes for the RMI mechanisms.

The EJB is called with a reference to a client-side callback object
(clientImpl), and the bean itself returns a message plus the message that it
gets when it calls back to the client.

That is, the EJB returns "I called back and got: " plus the return value that
it gets when it invokes the client-side callback object method helloBack(),
which in this example is "Hello Client World!".

The UNIX makefile or the makeit.bat NT batch file shows how to invoke
the java2rmi_iiop compiler to generate the required stub and other classes for
the RMI callback mechanism.


Source Files
============


Client.java
-----------

You invoke the client program from a command prompt, and pass it four
arguments, the

   - service URL (service ID, hostname, port, and SID if port is a listener)
   - name of the published bean to lookup and instantiate
   - username
   - password that authenticates the client to the Oracle8i database server

For example:
% java -classpath LIBs Client sess_iiop://localhost:2481:ORCL \
    /test/myServerBean scott tiger

where LIBs is the classpath that must include

$ORACLE_HOME/lib/aurora_client.jar
$ORACLE_HOME/jdbc/lib/classes111.zip
$ORACLE_HOME/lib/vbjorb.jar
$ORACLE_HOME/lib/vbjapp.jar
$JAVA_HOME/lib/classes.zip

The client code performs the following steps:

   - gets the arguments passed on the command line
   - creates a new JNDI Context (InitialContext())
   - looks up the published bean to find and activate its home interface
   - using the home interface, instantiates through its create()
     method a new bean object, server
   - invokes the hello() method on the server object, passing it the 
        client-side callback object (clientImpl), and prints the results

The printed output from the client is:

I Called back and got: Hello Client World!


server.ejb
----------

The ServerBean deployment descriptor.


server/ServerHome.java
----------------------

The ServerBean home interface.


server/Server.java
------------------

The ServerBean remote interface.


serverServer/ServerBean.java
----------------------------

The ServerBean implementation. It calls the client-side callback object.


client/Client.java
------------------

The remote interface for the client callback class.


clientServer/ClientImpl.java
----------------------------

The implementation of the client callback class. Note the use of
ActivatableObject in this class.



Compiling and Running the Example
=================================

UNIX
----

Enter the command 'make' in the shell to compile, load, and deploy the
objects, and run the client program.  Other targets are 'run' and 'clean'.

Make sure that a shell environment variable ORACLE_HOME is set to
point to the home location of the Oracle installation. This is
operating system dependent, so see the Installation documentation that
came with your system for the location. Also, review the README file
for the Oracle database, and the README file for the CORBA/EJB server
(the Oracle8i ORB), for additional up-to-date information.


Windows NT
----------

On Windows NT, run the batch file makeit.bat from a DOS command prompt
to compile, load, and deploy the objects. Run the batch file runit.bat
to run the client program, and see the results.


Make sure that the environment variables %ORACLE_HOME%, %CLASSPATH%,
and %SERVICE% are set appropriately for the DOS command window. You
can set these as either user or system environment variables from the
Control Panel. Double click on System in the Control Panel then on
the Environment tab to set these variables. Start a new DOS window
after setting environment variable values.


See the Installation documentation that came with your Oracle8i system
for the values of these variables. Also, review the README file for
the Oracle database, and the README file for the CORBA/EJB server (the
Oracle8i ORB), for additional up-to-date information.

You can also set an environment variable %JAVA_HOME% to point to the
root of your Java JDK. For example, SET JAVA_HOME=C:\JDK1.1.6.

client.java

import server.Server;
import server.ServerHome;
import clientServer.ClientImpl;

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];

    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);

    // now, create the ClientBean.
    ClientImpl clientImpl = new ClientImpl ();

    // now, create the Server Bean object
    ServerHome server_home = (ServerHome)ic.lookup (serviceURL + objectName);
    Server server = server_home.create ();
    System.out.println (server.hello (clientImpl));
  }
}

server.ejb

// This the generic database work bean template

SessionBean serverServer.ServerBean
{
  BeanHomeName = "test/myServerBean";
  RemoteInterfaceClassName = server.Server;
  HomeInterfaceClassName = server.ServerHome;

  AllowedIdentities = { PUBLIC };

  // SessionTimeout = 0;
  // StateManagementType = STATEFUL_SESSION;

  RunAsMode = CLIENT_IDENTITY;

  TransactionAttribute = TX_NOT_SUPPORTED;
}

client/Client.java

package client;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Client extends Remote {
  public String helloBack () throws RemoteException;
}

clientServer/ClientImpl.java

package clientServer;

import client.Client;

import java.rmi.RemoteException;
import org.omg.CORBA.Object;

import oracle.aurora.AuroraServices.ActivatableObject;

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

  public Object _initializeAuroraObject () {
    return this;
  }
}

server/Server.java

package server;

import client.Client;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Server extends EJBObject
{
  public String hello (Client client) throws RemoteException;
}

server/ServerHome.java

package server;

import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;

public interface ServerHome extends EJBHome
{
  public Server create () throws RemoteException, CreateException;
}

serverServer/ServerBean.java

package serverServer;

import server.Server;
import server.ServerHome;
import client.Client;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;
import java.rmi.RemoteException;

public class ServerBean implements SessionBean
{
  // Methods of the Hello interface
  public String hello (Client client) throws RemoteException
  {
    return "I Called back and got: " + client.helloBack ();
  }

  // Methods of the SessionBean
  public void ejbCreate () throws RemoteException, CreateException {}
  public void ejbRemove() {}
  public void setSessionContext (SessionContext ctx) {}
  public void ejbActivate () {}
  public void ejbPassivate () {}
}

beanInheritance

readme.txt

Overview
========

This example show two beans: Foo and Bar. In the example, the Bar bean
inherits from the Foo bean. The required coding and the effects of
this bean inheritance are demonstrated in this example.


Source Files
============


Client.java
-----------

You invoke the client program from a command prompt, and pass it four
arguments, the

   - service URL (service ID, hostname, port, and SID if port is a listener)
   - name of the published bean to lookup and instantiate
   - username
   - password that authenticates the client to the Oracle8i database server

For example:
% java -classpath LIBs Client sess_iiop://localhost:2222 /test/myHello scott 
tiger

where LIBs is the classpath that must include

$ORACLE_HOME/lib/aurora_client.jar
$ORACLE_HOME/jdbc/lib/classes111.zip
$ORACLE_HOME/lib/vbjorb.jar
$ORACLE_HOME/lib/vbjapp.jar
$JAVA_HOME/lib/classes.zip

(Note: for NT users, the environment variables would be %ORACLE_HOME% and
%JAVA_HOME%.)

The client code performs the following steps:

   - gets the arguments passed on the command line
   - creates a new JNDI Context (InitialContext())
   - looks up the published bean to find and activate its home interface
   - using the home interface, instantiates through its create()
     method a new bean object, hello
   - invokes the helloWorld() method on the hello object and prints the results

The printed output is:

Hello World
Hello World from bar
Hello World 2 from bar
Hello World from bar


foo.ejb
-------

The Foo bean deployment descriptor. See ../helloworld/readme.txt for a
more complete description of a typical example deployment descriptor.


bar.ejb
-------

The bar bean deployment descriptor.


inheritance/FooHome.java
------------------------

The Foo bean home interface. Specifies a single no-parameter create() method.


inheritance/Foo.java
--------------------

The Foo remote interface. Note that only a single method, hello(), is
specified.


inheritance/BarHome.java
------------------------

The Bar bean home interface. Specifies a single no-parameter create() method.


inheritance/Bar.java
--------------------

The Bar remote interface. Note that only a single method, hello2(), is
specified.


inheritanceServer/FooBean.java
------------------------------

The Foo bean implementation. Implements the hello() method of
inheritance/Foo.java, returning a String greeting.


inheritanceServer/BarBean.java
------------------------------

The Bar bean implementation. Implements both the hello() method inherited from
FooBean, as well as the hello2() method specified in inheritance/Bar.java.

Note that this bean extends FooBean, so it does not implement SessionBean or
any of its methods, such as ejbRemove(0, ejbActivate(), and so on, which is
normally a requirement of a session bean. This is because BarBeam inherits the
implementation of these from FooBean.


Compiling and Running the Example
=================================


UNIX
----

Enter the command 'make all' or simply 'make' in the shell to compile,
load, and deploy the objects, and run the client program.  Other
targets are 'run' and 'clean'.

Make sure that a shell environment variable ORACLE_HOME is set to
point to the home location of the Oracle installation. This is
operating system dependent, so see the Installation documentation that
came with your system for the location. Also, review the README file
for the Oracle database, and the README file for the CORBA/EJB server
(the Oracle8i ORB), for additional up-to-date information.


Windows NT
----------

On Windows NT, run the batch file makeit.bat from a DOS command prompt
to compile, load, and deploy the objects. Run the batch file runit.bat
to run the client program, and see the results.


Make sure that the environment variables %ORACLE_HOME%, %CLASSPATH%,
and %SERVICE% are set appropriately for the DOS command window. You
can set these as either user or system environment variables from the
Control Panel. Double click on System in the Control Panel then on
the Environment tab to set these variables. Start a new DOS window
after setting environment variable values.


See the Installation documentation that came with your Oracle8i system
for the values of these variables. Also, review the README file for
the Oracle database, and the README file for the CORBA/EJB server (the
Oracle8i ORB), for additional up-to-date information.

You can also set an environment variable %JAVA_HOME% to point to the
root of your Java JDK. For example, SET JAVA_HOME=C:\JDK1.1.6.

client.java

import inheritanceServer.*;
import inheritance.*;

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 != 5) {
      System.out.println("usage: Client serviceURL fooBeanName "
			  + "barBeanName username password");
      System.exit(1);
    }

    String serviceURL = args [0];
    String fooBeanName = args [1];
    String barBeanName = args[2];
    String username = args[3];
    String password = args[4];

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


    // Get a foo object from a foo published bean
    FooHome home = (FooHome) ic.lookup(serviceURL + fooBeanName);
    Foo foo = home.create();
    System.out.println(foo.hello());

    // Get a bar object from a bar published bean
    BarHome barHome = (BarHome) ic.lookup(serviceURL + barBeanName);
    Bar bar = barHome.create();
    System.out.println(bar.hello());
    System.out.println(bar.hello2());


    // Get a foo object from a bar published bean
    BarHome fooBarHome = (BarHome)ic.lookup(serviceURL + barBeanName);
    Foo fooBar = (Foo) fooBarHome.create();
    System.out.println(fooBar.hello());
  }
}

foo.ejb

SessionBean inheritanceServer.FooBean
{
  BeanHomeName = "/test/foo";
  RemoteInterfaceClassName = inheritance.Foo;
  HomeInterfaceClassName = inheritance.FooHome;

  AllowedIdentities = { PUBLIC };
  RunAsMode = CLIENT_IDENTITY;
}

bar.ejb

SessionBean inheritanceServer.BarBean
{
  BeanHomeName = "/test/bar";
  RemoteInterfaceClassName = inheritance.Bar;
  HomeInterfaceClassName = inheritance.BarHome;

  AllowedIdentities = { PUBLIC };
  RunAsMode = CLIENT_IDENTITY;
}

inheritance/Foo.java

package inheritance;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Foo extends EJBObject  
{
  public String hello () throws RemoteException;
}

inheritance/FooHome.java

package inheritance;

import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import java.rmi.RemoteException;

public interface FooHome extends EJBHome
{
  public Foo create () throws RemoteException, CreateException;
}

inheritance/Bar.java

package inheritance;

import java.rmi.RemoteException;

public interface Bar extends inheritance.Foo
{
  public String hello2 () throws RemoteException;
}

inheritance/BarHome.java

package inheritance;

import java.rmi.RemoteException;
import javax.ejb.EJBHome;
import javax.ejb.CreateException;

public interface BarHome extends EJBHome {
  public Bar create () throws RemoteException, CreateException;
}

inheritanceServer/FooBean.java

package inheritanceServer;

import java.rmi.RemoteException;
import javax.ejb.*;
import oracle.aurora.jndi.sess_iiop.*;

public class FooBean implements SessionBean
{
  // Methods of the interface
  public String hello () throws RemoteException {
    return "Hello World";
  }

  // Methods of the SessionBean
  public void ejbCreate () throws RemoteException, CreateException {
  }

  public void ejbRemove() {
  }

  public void setSessionContext (SessionContext ctx) {
  }

  public void ejbActivate () {
  }

  public void ejbPassivate () {
  }
}
    

inheritanceServer/BarBean.java

package inheritanceServer;

import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;

public class BarBean extends FooBean
{
  // Methods of the SessionBean are all from ancestor
  public void ejbCreate () throws RemoteException, CreateException {
    super.ejbCreate();
  }

  public String hello () throws RemoteException {
    return "Hello World from bar";
  }

  public String hello2 () throws RemoteException {
    return "Hello World 2 from bar";
  }
}
    



Prev

Top

Next
Oracle
Copyright © 1999 Oracle Corporation.

All Rights Reserved.

Library

Product

Contents

Index