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

Part Number A90188-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

B
Example Code: EJB

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

README

Overview
========

This is the most basic program that you can create for the Orcale9i
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 Oracle9i 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
#If using Java 2, use classes12.zip instead of classes111.zip
$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 Oracle9i 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 Oracle9i 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 Oracle9i 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
Oracle9i 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

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 EjbPubname")
;
      System.exit (1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String ejbPubname = 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 home = (HelloHome) ic.lookup(GIOP_SERVICE + ejbPubname);
    HelloRemote hello = home.create();
    System.out.println (hello.helloWorld());
  }
}

Home Interface for Hello

package common;

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

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

Remote Interface for Hello

package common;

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

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

Bean Implementation for Hello

package server;

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

public class HelloBean implements SessionBean
{
  // Methods of the HelloRemote 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 () {}
}

Deployment Descriptors

Hello.xml

<?xml version = '1.0' encoding = '8859_1'?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <session>
         <description>**Hello Bean**</description>
         <ejb-name>HelloBean</ejb-name>
         <home>common.HelloHome</home>
         <remote>common.HelloRemote</remote>
         <ejb-class>server.HelloBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Container</transaction-type>
      </session>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>**Role Security**</description>
         <role-name>OraclePublicRole</role-name>
      </security-role>
      <method-permission>
         <description>**Hello Permissions**</description>
         <role-name>OraclePublicRole</role-name>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>**Hello Transaction**</description>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Supports</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

HelloMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBe
ans 1.1//EN" "oracle-ejb-jar.dtd">
<oracle-ejb-jar>
 <oracle-descriptor>
   <ejb-name>HelloBean</ejb-name>
   <mappings>
     <ejb-mapping>
       <ejb-name>HelloBean</ejb-name>
       <jndi-name>test/HelloBean</jndi-name>
     </ejb-mapping>
     <security-role-mapping>
        <security-role>
          <description>**Role Security**</description>
          <role-name>OraclePublicRole</role-name>
        </security-role>
        <oracle-role>PUBLIC</oracle-role>
     </security-role-mapping>
     <transaction-manager>
       <default-enlist>False</default-enlist>
     </transaction-manager>
   </mappings>
 </oracle-descriptor>
</oracle-ejb-jar>

SQLJ Example

README

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 Oracle9i 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 Oracle9i 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
Oracle9i 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

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 EjbPubname")
;
      System.exit (1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String ejbPubname = 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(GIOP_SERVICE + ejbPubname);
    EmployeeRemote testBean = home.create();
    Employee empRec = empRec = testBean.query(7499);
    System.out.println ("Emp name is " + empRec.ename);
    System.out.println ("Emp sal  is " + empRec.sal);
  }
}

Home Interface

package common;

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

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

Remote Interface

package common;

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

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

Bean Implementation

Employee.java

package common;

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

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

EmployeeBean.sqlj

package server;
import common.*;
import java.sql.*;
import java.rmi.RemoteException;
import javax.ejb.*;

public class EmployeeBean implements SessionBean
{
  //SessionContext ctx;
  public void setSessionContext(SessionContext ctx)
  {
    //this.ctx = ctx;
  }

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

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

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

  public void ejbCreate() throws CreateException, RemoteException {}
  public void ejbActivate() {}
  public void ejbPassivate() {}
  public void ejbRemove() {}
}

Deployment Descriptors

Employee.xml

<?xml version = '1.0' encoding = '8859_1'?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <session>
         <description>no description</description>
         <ejb-name>EmployeeBean</ejb-name>
         <home>common.EmployeeHome</home>
         <remote>common.EmployeeRemote</remote>
         <ejb-class>server.EmployeeBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Container</transaction-type>
      </session>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>no description</description>
         <role-name>SCOTT</role-name>
      </security-role>
      <method-permission>
         <description>no description</description>
         <role-name>SCOTT</role-name>
         <method>
            <ejb-name>EmployeeBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>no description</description>
         <method>
            <ejb-name>EmployeeBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

EmployeeMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-descriptor PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise Jav
aBeans 1.1//EN" "oracle-ejb-jar.dtd">
<oracle-descriptor>
  <mappings>
    <ejb-mapping>
      <ejb-name>EmployeeBean</ejb-name>
      <jndi-name>test/EmployeeBean</jndi-name>
    </ejb-mapping>
    <security-role-mapping>
       <security-role>
         <description>just a role</description>
         <role-name>SECURITY_CLERK</role-name>
       </security-role>
       <oracle-role>CLERK</oracle-role>
    </security-role-mapping>
    <transaction-manager>
      <default-enlist>TRUE</default-enlist>
    </transaction-manager>
  </mappings>
</oracle-descriptor>

Bean Inheritance Example

README

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 Oracle9i 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
#If using Java 2, use classes12.zip instead of classes111.zip
$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 Oracle9i 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 Oracle9i 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
Oracle9i 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

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 != 5) {
      System.out.println("usage: Client user password GIOP_SERVICE fooPubname ba
rPubname");
      System.exit(1);
    }
    String username = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String fooPubname = args[3];
    String barPubname = 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(GIOP_SERVICE + fooPubname);
    FooRemote foo = home.create();
    System.out.println(foo.hello());

    // Get a bar object from a bar published bean
    BarHome barHome = (BarHome) ic.lookup(GIOP_SERVICE + barPubname);
    BarRemote 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(GIOP_SERVICE + barPubname);
    FooRemote fooBar = (FooRemote) fooBarHome.create();
    System.out.println(fooBar.hello());
  }
}

Home Interface

BarHome.java

package common;

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

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

FooHome.java

package common;

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

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

Remote Interface

BarRemote.java

package common;

import java.rmi.RemoteException;

public interface BarRemote extends FooRemote
{
  public String hello2 () throws RemoteException;
}

FooRemote.java

package common;

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

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

Bean Implementation

BarBean.java

package server;

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";
  }
}

FooBean.java

package server;

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 () {}
}

Deployment Descriptors

FooBar.xml

<?xml version = '1.0' encoding = '8859_1'?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <session>
         <description>**Foo Bean**</description>
         <ejb-name>FooBean</ejb-name>
         <home>common.FooHome</home>
         <remote>common.FooRemote</remote>
         <ejb-class>server.FooBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Container</transaction-type>
      </session>
      <session>
         <description>**Bar Bean**</description>
         <ejb-name>BarBean</ejb-name>
         <home>common.BarHome</home>
         <remote>common.BarRemote</remote>
         <ejb-class>server.BarBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Container</transaction-type>
      </session>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>**Role Security**</description>
         <role-name>OraclePublicRole</role-name>
      </security-role>
      <method-permission>
         <description>**Foo Permissions**</description>
         <role-name>OraclePublicRole</role-name>
         <method>
            <ejb-name>FooBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <method-permission>
         <description>**Bar Permissions**</description>
         <role-name>OraclePublicRole</role-name>
         <method>
            <ejb-name>BarBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>**Foo Transaction**</description>
         <method>
            <ejb-name>FooBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Supports</trans-attribute>
      </container-transaction>
      <container-transaction>
         <description>**Bar Transaction**</description>
         <method>
            <ejb-name>BarBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Supports</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

FooBarMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBe
ans 1.1//EN" "oracle-ejb-jar.dtd">
<oracle-ejb-jar>
 <oracle-descriptor>
   <ejb-name>FooBean</ejb-name>
   <mappings>
     <ejb-mapping>
       <ejb-name>FooBean</ejb-name>
       <jndi-name>test/FooBean</jndi-name>
     </ejb-mapping>
     <security-role-mapping>
        <security-role>
          <description>**Role Security**</description>
          <role-name>OraclePublicRole</role-name>
        </security-role>
        <oracle-role>PUBLIC</oracle-role>
     </security-role-mapping>
     <transaction-manager>
       <default-enlist>False</default-enlist>
     </transaction-manager>
   </mappings>
 </oracle-descriptor>
 <oracle-descriptor>
   <ejb-name>BarBean</ejb-name>
   <mappings>
     <ejb-mapping>
       <ejb-name>BarBean</ejb-name>
       <jndi-name>test/BarBean</jndi-name>
     </ejb-mapping>
     <security-role-mapping>
        <security-role>
          <description>**Role Security**</description>
          <role-name>OraclePublicRole</role-name>
        </security-role>
        <oracle-role>PUBLIC</oracle-role>
     </security-role-mapping>
     <transaction-manager>
       <default-enlist>False</default-enlist>
     </transaction-manager>
   </mappings>
 </oracle-descriptor>
</oracle-ejb-jar>

Entity Bean Examples

The following two examples show how to implement entity beans either using bean-managed or container-managed options:

Bean-Managed Entity Bean Example

Client

package client;

import common.*;
import java.util.*;
import java.sql.*; 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.transaction.UserTransaction;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;
import oracle.jdbc.driver.*; 
import oracle.aurora.jndi.jdbc_access.jdbc_accessURLContextFactory; 

public class Client
{
  public static void main(String [] args) throws Exception
  {
    System.out.println("Running client");
    if (args.length != 6) {
      System.out.println("usage: Client user password GIOP_SERVICE ejbPubname JD
BC_SERVICE utName");
      System.exit(1);
    }

    String user = args [0];
    String password = args [1];
    String GIOP_SERVICE = args [2];
    String ejbPubname  = args [3];  
    String JDBC_SERVICE = args [4];
    String utName = args [5]; 

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

    DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); 
    // jdbc debug
    //DriverManager.setLogStream(System.out);

    Context ic = new InitialContext (env);

    PurchaseOrderHome home =
      (PurchaseOrderHome) ic.lookup(GIOP_SERVICE + ejbPubname);

    // Begin a transaction to create a new PO
    UserTransaction ut;
    ut = (UserTransaction) ic.lookup("jdbc_access:/" + utName);
    ut.begin();

    // Create a new PO and add items to it
    PurchaseOrderRemote po = home.create();
    po.addItem (111111, 2);
    po.addItem (333333, 4);

    // Price the PO
    System.out.println ("PO price $" + po.price ());

    // Get the po number for future reference
    String ponumber = (String)po.getPrimaryKey ();
    System.out.println ("Primary key = " + ponumber);

    // Commit the transaction
    ut.commit();

    // This is now the future:

    // Start another transaction
    ut.begin ();

    // Retrieve the PO from its primary key
    PurchaseOrderRemote po2 = home.findByPrimaryKey(ponumber);

    // Add another item
    po2.addItem (222222, 1);

    // Check the PO contents
    System.out.println ("Contents of the PO:");
    Vector items = po2.getContents ();
    Enumeration e = items.elements ();
    while (e.hasMoreElements ()) {
      LineItem item = (LineItem)e.nextElement ();
      System.out.println (item.quantity + " " + item.description + " at $"
                          + (int)item.price + " each");
    }

    // Compute the price again
    System.out.println ("PO price $" + po2.price ());

    // Rollback the change
    ut.rollback ();
  }

}

Home Interface

package common;

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

public interface PurchaseOrderHome extends EJBHome
{
  // Create a new PO
  public PurchaseOrderRemote create() throws CreateException, RemoteException;

  // Find an existing one
  public PurchaseOrderRemote findByPrimaryKey (String POnumber)
    throws FinderException, RemoteException;
}

Remote Interface

package common;

import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Vector;
import javax.ejb.EJBObject;

public interface PurchaseOrderRemote extends EJBObject
{
  // Price the PO
  public float price() throws RemoteException;

  // Manage contents

  // getContents returns a Vector of LineItem objects
  public Vector getContents() throws RemoteException;

  public void addItem(int sku, int count) throws RemoteException;
}

Exception

package common;

import java.rmi.RemoteException;

public class PurchaseException extends RemoteException
{
  public PurchaseException() {}

  public PurchaseException(Object o, String method, Exception e)
  {
    this (e.getClass() + "  in <" + o.getClass() + "> ( " + method + ") :: "
          + e.getMessage());
  }

  public PurchaseException(String msg)
  {
    super (msg);
  }
}

Bean Implementation

PurchaseOrderBean.sqlj

package server;

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

#sql iterator ItemsIter (int skunumber, int count, String description,
                         float price);

public class PurchaseOrderBean implements EntityBean
{
  EntityContext ctx;

  Vector items;         // The items in the PO (instances of LineItem)

  public void PurchaseOrderBean() {}
 
  // Bean Managed Persistence methods

  // The create methods takes care of generating a new PO and returns 
  // its primary key
  public String ejbCreate () throws CreateException, RemoteException
  {
    String ponumber = null;
    try {
      #sql { select ponumber.nextval into :ponumber from dual };
      #sql { insert into pos (ponumber, status) values (:ponumber, 'OPEN') };
    } catch (SQLException e) {
      throw new PurchaseException (this, "create", e);
    }
//    System.out.println ("in ejb-Create: primaryKey =" + ponumber);

    return ponumber;
  }

  // Nothing to do here
  public void ejbPostCreate () { 
    items = new Vector ();
  }

  // The remove method deletes all line items belonging to the PO
  public void ejbRemove() throws RemoteException {
    // Get the PO number and delete
    String ponumber = (String)ctx.getPrimaryKey();
    try {
      #sql { delete from lineitems where ponumber = :ponumber };
      #sql { delete from pos where ponumber = :ponumber };
    } catch (SQLException e) {
      throw new PurchaseException (this, "remove", e);
    }
//    System.out.println ("After ejbRemove: primaryKey =" + ponumber);
  }

  // The load method populates the items array with all the existing 
  // line items
  public void ejbLoad() throws RemoteException {
// System.out.println ("ejbLoad: begin");
// new Exception ().printStackTrace ();
    // Get the PO number 
    String ponumber = (String)ctx.getPrimaryKey();

    // Load all line items.  
    try {
      items = new Vector ();
      ItemsIter iter = null;
      try {
        #sql iter = { 
          select lineitems.skunumber, lineitems.count,
                 skus.description, skus.price 
            from lineitems, skus 
            where ponumber = :ponumber and lineitems.skunumber = skus.skunumber
        };

        while (iter.next ()) {
          LineItem item =
            new LineItem (iter.skunumber(), iter.count(), iter.description(),
                          iter.price());
          items.addElement (item);
        }
      } finally {
        if (iter != null) iter.close ();
      }
    } catch (SQLException e) {
      throw new PurchaseException (this, "load", e);
    }
//System.out.println ("ejbLoad: end");
  }
  
  // The store method replaces all entries in the lineitems table with the
  // new entries from the bean
  public void ejbStore() throws RemoteException {
// System.out.println ("ejbStore: begin");
// new Exception ().printStackTrace ();
    // Get the PO number
    String ponumber = (String)ctx.getPrimaryKey();

    try {
      // Delete old entries
      #sql { delete from lineitems where ponumber = :ponumber };

      // Insert new entries
      Enumeration e = items.elements ();
      while (e.hasMoreElements ()) {
        LineItem item = (LineItem)e.nextElement ();
        #sql { insert into lineitems (ponumber, skunumber, count)
                 values (:ponumber, :(item.sku), :(item.quantity))
        };
      }
    } catch (SQLException e) {
      throw new PurchaseException (this, "store", e);
    }
//System.out.println ("ejbStore: end");
  }
  
  // The findByPrimaryKey method verifies that the POnumber exists
  public String ejbFindByPrimaryKey (String ponumber)
    throws FinderException, RemoteException
  {
    try {
      int count;
      #sql { select count (ponumber) into :count from pos 
               where ponumber = :ponumber };

      // There has to be one
      if (count != 1)
        throw new FinderException ("Inexistent PO: " + ponumber);
    } catch (SQLException e) {
      throw new PurchaseException (this, "findByPrimaryKey", e);
    }
    // The ponumber is the primary key
    return ponumber;
  }

  // Business Methods

  // Price the PO
  public float price() throws RemoteException {
    float price = 0;
    Enumeration e = items.elements ();
    while (e.hasMoreElements ()) {
      LineItem item = (LineItem)e.nextElement ();
      price += item.quantity * item.price;
    }

    // 5% discount if buying more than 10 items
    if (items.size () > 10)
      price -= price * 0.05;

    // Shipping is a constant plus function of the number of items
    price += 10 + (items.size () * 2);

    return price;
  }

  // The getContents methods has to load the descriptions
  public Vector getContents() throws RemoteException {
    return items;
  }

  // The add Item method gets the price and description
  public void addItem (int sku, int count) throws RemoteException {
    try {
      String description;
      float price;
      #sql { select price, description into :price, :description 
             from skus where skunumber = :sku }; 
      items.addElement (new LineItem (sku, count, description, price));
    } catch (SQLException e) {
      throw new PurchaseException (this, "addItem", e);
    }
  }

  // EntityBean Methods
  public void setEntityContext(EntityContext ctx) { this.ctx = ctx; }
  public void unsetEntityContext() {}
  public void ejbActivate() {}
  public void ejbPassivate() {}
}

LineItem.java

package common;

public class LineItem implements java.io.Serializable
{
  public int sku;
  public int quantity;
  public String description;
  public float price;
  
  public LineItem (int sku, int quantity, String description, float price)
  {
    this.sku = sku;
    this.quantity = quantity;
    this.description = description;
    this.price = price;
  }
}

Deployment Descriptors

PurchaseOrder.xml

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <entity>
         <description>no description</description>
         <ejb-name>PurchaseOrderBean</ejb-name>
         <home>common.PurchaseOrderHome</home>
         <remote>common.PurchaseOrderRemote</remote>
         <ejb-class>server.PurchaseOrderBean</ejb-class>
         <persistence-type>Bean</persistence-type>
         <prim-key-class>java.lang.String</prim-key-class>
         <reentrant>False</reentrant>
      </entity>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
      </security-role>
      <method-permission>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
         <method>
            <ejb-name>PurchaseOrderBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>no description</description>
         <method>
            <ejb-name>PurchaseOrderBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

PurchaseOrderMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-descriptor PUBLIC "-//Oracle Corporation.//DTD Oracle 1.1//EN" 
"oracle-ejb-jar.dtd">
<oracle-descriptor>
<mappings>
  <ejb-mapping>
     <ejb-name>PurchaseOrderBean</ejb-name>
     <jndi-name>test/PurchaseOrderBean</jndi-name>
  </ejb-mapping>
  <transaction-manager>
    <default-enlist>TRUE</default-enlist>
  </transaction-manager>
</mappings>
</oracle-descriptor>

Database Table Updates

-- Cleanup
drop table lineitems;
drop sequence ponumber;
drop table pos;
drop table skus;

-- The sku table lists all the items available for purchase
create table skus (skunumber number constraint pk_skus primary key,
                   description varchar2(2000),
                   price number);

-- The pos table stores information about purchase orders
-- The status column is 'OPEN', 'EXECUTED' or 'SHIPPED'
create table pos (ponumber number constraint pk_pos primary key,
                  status varchar2(30));

-- The ponumber sequence is used to generate PO ids
create sequence ponumber;

-- The lineitems table stores the contents of a po
-- The skunumber is a reference into the skus table
-- The ponumber is a reference into the pos table 
create table lineitems (ponumber number constraint fk_pos references pos,
                        skunumber number constraint fk_skus references skus,
                        count number);

Container-Managed Entity Bean Example

Client

package client;

import common.*;

import java.util.Hashtable;
import java.util.Enumeration;
import java.rmi.RemoteException;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.ejb.RemoveException;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class Client
{
  public static void main(String[] argv)
  {
                
    System.out.println("client is running");
    try
      {
        if (argv.length != 4) {
          System.out.println("usage: Client user password 
GIOP_SERVICE ejbPubname"); System.exit(1); } String user = argv[0]; String password = argv[1]; String GIOP_SERVICE = argv[2]; String ejbPubname = argv[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); CustomerHome ch = (CustomerHome) ic.lookup(GIOP_SERVICE + ejbPubname); CustomerRemote cust = ch.create("Jake Terwilliger", "Pine Drive"); System.out.println("created " + cust.getName()); System.out.println (" address = " + cust.getAddress()); String pk = (String) cust.getPrimaryKey(); System.out.println("Primarykey = " + pk); //imagine that time passes here, or this program is //finished, and a later program wants to use the //primary key CustomerRemote cust1 = ch.create("Al Smith", "Sesame Street"); CustomerRemote cust2 = ch.create("Bob Davidson", "Elm Street"); CustomerRemote cust3 = ch.create("Carol Fernandez", "Cedar Blvd"); cust = null; cust = ch.findByPrimaryKey(pk); System.out.println("Found by primary key lookup"); System.out.println (" name = " + cust.getName()); System.out.println (" address = " + cust.getAddress()); cust.remove(); System.out.println("removed bean"); cust = ch.findByWhere("where cust_addr = 'Elm Street'"); System.out.println("Found by findByWhere"); System.out.println (" name = " + cust.getName()); System.out.println (" address = " + cust.getAddress()); cust.remove(); System.out.println("removed bean"); Enumeration e = ch.findAllCustomers(""); while(e.hasMoreElements()) { cust = (CustomerRemote) e.nextElement(); System.out.println (" name = " + cust.getName()); System.out.println (" address = " + cust.getAddress()); } } catch (RemoveException e) { System.out.println("RemoveException caught:" + e); e.printStackTrace(); } catch (NamingException e) { System.out.println("NamingException caught:" + e); e.printStackTrace(); } catch (FinderException e) { System.out.println("FinderException caught:" + e); e.printStackTrace(); } catch (CreateException e) { System.out.println("CreateException caught:" + e); e.printStackTrace(); } catch (RemoteException e) { System.out.println("RemoteException caught:" + e); e.printStackTrace(); } } }

Home Interface

package common;

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

public interface CustomerHome extends EJBHome
{
  public CustomerRemote findByPrimaryKey(String pk)
    throws RemoteException, FinderException;
  public CustomerRemote findByWhere(String whereString)
    throws RemoteException, FinderException;
  public java.util.Enumeration findAllCustomers(String whereString)
    throws RemoteException, FinderException;
  public CustomerRemote create(String custname, String custaddr)
    throws RemoteException, CreateException;
}

Remote Interface

package common;

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

public interface CustomerRemote extends EJBObject
{
  public String getName() throws RemoteException;
  public String getAddress() throws RemoteException;
  public void setAddress(String addr) throws RemoteException;
}

Bean Implementation

package server;

import common.*;
import java.sql.*;
import java.util.*;
import java.rmi.RemoteException;
import java.io.Serializable;
import javax.ejb.*;

public class CustomerBean implements EntityBean
{
  private transient EntityContext ctx;
  public String name;
  public String addr;
  public String hey;
  public int foo;
  public boolean bar;

  public String getName() throws RemoteException
  {
    return name;
  }
  public void setName(String name) throws RemoteException
  {
    this.name = name;
  }
  public String getAddress() throws RemoteException
  {
    return addr;
  }
  public void setAddress(String addr) throws RemoteException
  {
    this.addr = addr;
  }
  public void setEntityContext(EntityContext ctx)
  {
    this.ctx = ctx;
    Properties props = ctx.getEnvironment();

  }
  public void unsetEntityContext()
  {
    this.ctx = null;
  }

  public String ejbCreate(String custname, String custaddr) throws CreateExcepti
on, RemoteException
  {
    try {
      hey = "This is a test Hey";
      foo = 1234;
      bar = true;
      setName(custname);
      setAddress(custaddr);
    } catch (java.rmi.RemoteException e) {
      throw new CreateException();
    }
      return null;
  }

public String ejbFindByPrimaryKey(String pk) throws RemoteException, FinderExcep
tion
  {
    return null;
  }

  public void ejbPostCreate(String custname, String custaddr) throws CreateExcep
tion
  {
    // get primarykey
    String pk = (String)ctx.getPrimaryKey();
  }

  public void ejbLoad()
  {
    // You can get to the primary key
    String pk = (String)ctx.getPrimaryKey();
  }

  public void ejbActivate() {}
  public void ejbPassivate() {}
  public void ejbRemove() {}
  public void ejbStore() {}
}

Deployment Descriptors

Customer.xml

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <entity>
         <description>**Customer Bean**</description>
         <ejb-name>CustomerBean</ejb-name>
         <home>common.CustomerHome</home>
         <remote>common.CustomerRemote</remote>
         <ejb-class>server.CustomerBean</ejb-class>
         <persistence-type>Container</persistence-type>
         <prim-key-class>java.lang.String</prim-key-class>
         <reentrant>False</reentrant>
         <cmp-field><field-name>name</field-name></cmp-field>
         <cmp-field><field-name>addr</field-name></cmp-field>
         <cmp-field><field-name>hey</field-name></cmp-field>
         <cmp-field><field-name>foo</field-name></cmp-field>
         <cmp-field><field-name>bar</field-name></cmp-field>
         <primkey-field>name</primkey-field>
         <resource-ref>
           <res-ref-name>DataSource</res-ref-name>
           <res-type>javax.sql.DataSource</res-type>
           <res-auth>Application</res-auth>
         </resource-ref>
      </entity>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>**Customer Role**</description>
         <role-name>PUBLIC</role-name>
      </security-role>
      <method-permission>
         <description>**Customer Permissions**</description>
         <role-name>PUBLIC</role-name>
         <method>
            <ejb-name>CustomerBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>**Customer Transaction**</description>
         <method>
            <ejb-name>CustomerBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>RequiresNew</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

CustomerMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBe
ans 1.1//EN" "oracle-ejb-jar.dtd">
<oracle-ejb-jar>
  <oracle-descriptor>
    <mappings>
      <ejb-mapping>
        <ejb-name>CustomerBean</ejb-name>
        <jndi-name>test/CustomerBean</jndi-name>
      </ejb-mapping>
      <security-role-mapping>
         <security-role>
           <description>**Customer Role**</description>
           <role-name>OraclePublicRole</role-name>
         </security-role>
         <oracle-role>PUBLIC</oracle-role>
      </security-role-mapping>
      <resource-ref-mapping>
        <res-ref-name>DataSource</res-ref-name>
        <jndi-name>test/DataSource/testds</jndi-name>
      </resource-ref-mapping>
      <transaction-manager>
        <default-enlist>True</default-enlist>
      </transaction-manager>
    </mappings>
    <persistence-provider>
      <description>**Persistence Provider**</description>
      <persistence-name>psi-ri</persistence-name>
      <persistence-deployer>
oracle.aurora.ejb.persistence.ocmp.OcmpEntityDeployer
</persistence-deployer> </persistence-provider> <persistence-descriptor> <description>**Persistence Descriptor**</description> <ejb-name>CustomerBean</ejb-name> <persistence-name>psi-ri</persistence-name> <persistence-param>test param 1</persistence-param> <persistence-param>test param 2</persistence-param> <psi-ri> <schema>SCOTT</schema> <table>CUSTOMERS</table> <attr-mapping> <field-name>name</field-name> <column-name>CUST_NAME</column-name> </attr-mapping> <attr-mapping> <field-name>addr</field-name> <column-name>CUST_ADDR</column-name> </attr-mapping> <serialize-mapping> <field-name>hey</field-name> <field-name>foo</field-name> <field-name>bar</field-name> <column-name>CUST_SERIALIZE</column-name> </serialize-mapping> </psi-ri> </persistence-descriptor> </oracle-descriptor> </oracle-ejb-jar>

Database Table Updates

drop table CUSTOMERS;

create table CUSTOMERS (CUST_NAME VARCHAR(64) NOT NULL, CUST_ADDR VARCHAR(64), C
UST_SERIALIZE LONG RAW );

Session Example

Client

package client;

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

public class Client
{
  public static void main (String[] args) throws Exception
  {
    if (args.length != 4) {
      System.out.println ("usage: Client user password GIOP_SERVICE ejbPubname")
;
      System.exit (1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String ejbPubname = 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);

    // Activate a Hello in the 8i server
    // This creates a first session in the server
    HelloHome hello_home = (HelloHome)ic.lookup (GIOP_SERVICE + ejbPubname);
    HelloRemote hello = hello_home.create();
    hello.setMessage("Hello World!");
    System.out.println (hello.helloWorld());

    // Ask the first Hello to activate another Hello in the same server
    // This creates Another SESSION used by the first session
    hello.getOtherHello(user, password, GIOP_SERVICE + ejbPubname);
    System.out.println(hello.otherHelloWorld ());
  }
}

Home Interface

package common;

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

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

Remote Interface

package common;

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

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

  public void setMessage(String message) throws RemoteException;

  public void getOtherHello(String user, String password, String otherBeanURL)
       throws RemoteException, CreateException;

  public String otherHelloWorld() throws RemoteException;
}

Bean Implementation

package server;

import common.*;
import java.util.Hashtable;
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.naming.Context;
import javax.naming.InitialContext;
import oracle.aurora.jndi.sess_iiop.ServiceCtx;

public class HelloBean implements SessionBean
{
  String message;
  HelloRemote otherHello;

  // Methods of the Hello interface
  public String helloWorld() throws RemoteException
  {
    return message;
  }

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

  public void getOtherHello(String user, String password, String otherBeanURL)
       throws RemoteException, CreateException
  {
    try {
      // start a new session
      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);

      // create the other Bean instance
      HelloHome other_HelloHome = (HelloHome) ic.lookup(otherBeanURL);
      otherHello = other_HelloHome.create();
      otherHello.setMessage("Hello from the Other HelloBean Object");
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }

  public String otherHelloWorld() throws RemoteException
  {
    if (otherHello != null)
      return otherHello.helloWorld();
    else
      return "otherBean is not accessed yet";
  }

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

Deployment Descriptors

Hello.xml

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <session>
         <description>no description</description>
         <ejb-name>HelloBean</ejb-name>
         <home>common.HelloHome</home>
         <remote>common.HelloRemote</remote>
         <ejb-class>server.HelloBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Container</transaction-type>
         <env-entry>
           <env-entry-name>HelloBean.KPRB_SERVICE</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>jdbc:oracle:kprb:</env-entry-value>
         </env-entry>
         <env-entry>
           <env-entry-name>HelloBean.JDBCDriverName</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>oracle.jdbc.driver.OracleDriver</env-entry-value>
         </env-entry>
         <env-entry>
           <env-entry-name>HelloBean.JDBC_SERVICE</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>
              JDBC_URL=jdbc:oracle:thin:@localhost:5521:jismain
           </env-entry-value>
         </env-entry>
         <resource-ref>
           <res-ref-name>jdbc/HelloDS</res-ref-name>
           <res-type>javax.sql.DataSource</res-type>
           <res-auth>Application</res-auth>
         </resource-ref>
      </session>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
      </security-role>
      <method-permission>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>no description</description>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

HelloMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-descriptor PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise Jav
aBeans 1.1//EN" "oracle-ejb-jar.dtd">
<oracle-descriptor>
  <mappings>
    <ejb-mapping>
      <ejb-name>HelloBean</ejb-name>
      <jndi-name>test/HelloBean</jndi-name>
    </ejb-mapping>
    <security-role-mapping>
       <security-role>
         <description>just a role</description>
         <role-name>PUBLIC</role-name>
       </security-role>
       <oracle-role>PUBLIC</oracle-role>
    </security-role-mapping>
    <resource-ref-mapping>
      <res-ref-name></res-ref-name>
      <jndi-name></jndi-name>
    </resource-ref-mapping>
    <transaction-manager>
      <jndi-name></jndi-name>
      <default-enlist>True</default-enlist>
    </transaction-manager>
  </mappings>
</oracle-descriptor>

SSL Examples

Client-Side Authentication Example

README

Overview
========

This is the exact same example as under examples/ejb/basic/helloworld,
except that this example is using SSL client auth. So, except for the 
SSL details, please refer to the readme file under 
examples/ejb/basic/helloworld for other details.

The purpose of the example is to show how to use ssl client side 
authentication instead of username/password combination. 

Setup required
--------------

You need to open the encrypted wallet(ewallet.der) provided in this directory 
using the wallet manager tool provided by Oracle, and save it as clear
text wallet (cwallet.sso). The password is welcome12. 
Copy the generated cwallet.sso into TNS_ADMIN directory.

The encrypted wallet(ewallet.der) is only valid for Solaris platforms. For 
other platforms, you should generate the wallet using Oracle's owm tool.

This test also requires B64 encoded wallet(cert.txt) which is already present 
in this directory.  You can also generate your own using Oracle's owmgui tool
and using export option in the tool.

The parameter SSL_CLIENT_AUTHENTICATION in $TNSADMIN/sqlnet.ora should be set 
to TRUE.

Restart the database.

The setup also requires creation of a global user, say guest. The script to 
create 
global user is in this directory(create.sh).  This script prompts for username
and password of a privileged user as input to this script.

Client

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 credentialsFile password GIOP_SERVICE e
jbPubname");
      System.exit (1);
    }
    String credsFile = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String ejbPubname = args[3];

    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, password);
    // 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);

    Context ic = new InitialContext (env);

    HelloHome hello_home = (HelloHome) ic.lookup(GIOP_SERVICE + ejbPubname);
    HelloRemote hello = hello_home.create();
    System.out.println (hello.helloWorld());
  }
}

Home Interface

package common;

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

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

Remote Interface

package common;

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

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

Bean Implementation

package server;

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

public class HelloBean implements SessionBean
{
  // Methods of the HelloRemote 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() {}
}

Deployment Descriptors

Hello.xml

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <session>
         <description>no description</description>
         <ejb-name>HelloBean</ejb-name>
         <home>common.HelloHome</home>
         <remote>common.HelloRemote</remote>
         <ejb-class>server.HelloBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Container</transaction-type>
         <env-entry>
           <env-entry-name>HelloBean.KPRB_SERVICE</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>jdbc:oracle:kprb:</env-entry-value>
         </env-entry>
         <env-entry>
           <env-entry-name>HelloBean.JDBCDriverName</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>oracle.jdbc.driver.OracleDriver</env-entry-value>
         </env-entry>
         <env-entry>
           <env-entry-name>HelloBean.JDBC_SERVICE</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>
              JDBC_URL=jdbc:oracle:thin:@localhost:5521:jismain
           </env-entry-value>
         </env-entry>
         <resource-ref>
           <res-ref-name>jdbc/HelloDS</res-ref-name>
           <res-type>javax.sql.DataSource</res-type>
           <res-auth>Application</res-auth>
         </resource-ref>
      </session>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
      </security-role>
      <method-permission>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>no description</description>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

HelloMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-descriptor PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise Jav
aBeans 1.1//EN" "oracle-ejb-jar.dtd">
<oracle-descriptor>
  <mappings>
    <ejb-mapping>
      <ejb-name>HelloBean</ejb-name>
      <jndi-name>test/HelloBean</jndi-name>
    </ejb-mapping>
    <security-role-mapping>
       <security-role>
         <description>just a role</description>
         <role-name>PUBLIC</role-name>
       </security-role>
       <oracle-role>PUBLIC</oracle-role>
    </security-role-mapping>
    <resource-ref-mapping>
      <res-ref-name></res-ref-name>
      <jndi-name></jndi-name>
    </resource-ref-mapping>
    <transaction-manager>
      <jndi-name></jndi-name>
      <default-enlist>True</default-enlist>
    </transaction-manager>
  </mappings>
</oracle-descriptor>

Server-Side Authentication Example

README

Overview
========

This is the exact same example as under examples/ejb/basic/helloworld,
except that this example is using SSL server side auth. So, except for the 
SSL details, please refer to the readme file under 
examples/ejb/basic/helloworld for other details.

The purpose of the example is to show how to use ssl server side 
authentication. Since the client doesn't have certificate in this
case, it still passes username/password. 

Setup required
--------------

You need to open the encrypted wallet(ewallet.der) provided in this directory 
using the wallet manager tool provided by Oracle, and save it as clear
text wallet (cwallet.sso). The password is welcome12. 
Copy the generated cwallet.sso into TNS_ADMIN directory.

The encrypted wallet(ewallet.der) is only valid for Solaris platforms. For 
other platforms, you should generate the wallet using Oracle's owm tool.

The parameter SSL_CLIENT_AUTHENTICATION in $TNSADMIN/sqlnet.ora should be set 
to FALSE.

Restart the database.

Client

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

      System.exit (1);
    }
    String user = args[0];
    String password = args[1];
    String GIOP_SERVICE = args[2];
    String ejbPubname = 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.SSL_LOGIN);
    Context ic = new InitialContext (env);

    HelloHome hello_home = (HelloHome) ic.lookup(GIOP_SERVICE + ejbPubname);
    HelloRemote hello = hello_home.create();
    System.out.println (hello.helloWorld());
  }
}

Home Interface

package common;

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

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

Remote Interface

package common;

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

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

Bean Implementation

package server;

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

public class HelloBean implements SessionBean
{
  // Methods of the HelloRemote 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() {}
}

Deployment Descriptors

Hello.xml

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise JavaBeans 1.1
//EN" "ejb-jar.dtd">
<ejb-jar>
   <enterprise-beans>
      <session>
         <description>no description</description>
         <ejb-name>HelloBean</ejb-name>
         <home>common.HelloHome</home>
         <remote>common.HelloRemote</remote>
         <ejb-class>server.HelloBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Container</transaction-type>
         <env-entry>
           <env-entry-name>HelloBean.KPRB_SERVICE</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>jdbc:oracle:kprb:</env-entry-value>
         </env-entry>
         <env-entry>
           <env-entry-name>HelloBean.JDBCDriverName</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>oracle.jdbc.driver.OracleDriver</env-entry-value>
         </env-entry>
         <env-entry>
           <env-entry-name>HelloBean.JDBC_SERVICE</env-entry-name>
           <env-entry-type>java.lang.String</env-entry-type>
           <env-entry-value>
              JDBC_URL=jdbc:oracle:thin:@localhost:5521:jismain
           </env-entry-value>
         </env-entry>
         <resource-ref>
           <res-ref-name>jdbc/HelloDS</res-ref-name>
           <res-type>javax.sql.DataSource</res-type>
           <res-auth>Application</res-auth>
         </resource-ref>
      </session>
   </enterprise-beans>
   <assembly-descriptor>
      <security-role>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
      </security-role>
      <method-permission>
         <description>no description</description>
         <role-name>PUBLIC</role-name>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>
      <container-transaction>
         <description>no description</description>
         <method>
            <ejb-name>HelloBean</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>

HelloMap.xml

<?xml version="1.0"?>
<!DOCTYPE oracle-descriptor PUBLIC "-//Sun Microsystems Inc.//DTD Enterprise Jav
aBeans 1.1//EN" "oracle-ejb-jar.dtd">
<oracle-descriptor>
  <mappings>
    <ejb-mapping>
      <ejb-name>HelloBean</ejb-name>
      <jndi-name>test/HelloBean</jndi-name>
    </ejb-mapping>
    <security-role-mapping>
       <security-role>
         <description>just a role</description>
         <role-name>PUBLIC</role-name>
       </security-role>
       <oracle-role>PUBLIC</oracle-role>
    </security-role-mapping>
    <resource-ref-mapping>
      <res-ref-name></res-ref-name>
      <jndi-name></jndi-name>
    </resource-ref-mapping>
    <transaction-manager>
      <jndi-name></jndi-name>
      <default-enlist>True</default-enlist>
    </transaction-manager>
  </mappings>
</oracle-descriptor>


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