Skip Headers

Oracle® Application Server Containers for J2EE Enterprise JavaBeans Developer's Guide 10g Release 2 (10.1.2) Part No. B15505-02 |
| Library |  | Contents | Index

Previous | Next |

# 10 Understanding Environment, Deployment, and Packaging

Part of development includes setting up the environment, as well as packaging and deploying your applications.

- Directory Structure Recommendations for EJB Development

- Create the Deployment Descriptor

- Archive the EJB Application

- Prepare the EJB Application for Assembly

- Deploy the Enterprise Application to OC4J

- Sharing Classes

- Configuring Environment References

## Directory Structure Recommendations for EJB Development

Although you can develop your application in any manner, we encourage you to use consistent naming for locating your application easily. One method would be to implement your enterprise Java application under a single parent directory structure, separating each module of the application into its own subdirectory.

The hello example was developed using the directory structure mentioned in the Oracle Application Server Containers for J2EE User's Guide. Notice in Figure 10-1 that the EJB and Web modules exist under the `hello` application parent directory and are developed separately in their own directory.

Figure 10-1 Hello Directory Structure

Description of the illustration packaging1.gif

Note: For EJB modules, the top of the module (`ejb_module`) represents the start of a search path for classes. As a result, classes belonging to packages are expected to be located in a nested directory structure beneath this point. For example, a reference to a package class '`myapp.Hello.class`' is expected to be located in "`...hello/ejb_module/myapp/Hello.class`".

## Create the Deployment Descriptor

After implementing and compiling your classes, you must create the standard J2EE EJB deployment descriptor for all beans in the module. The XML deployment descriptor (defined in the `ejb-jar.xml` file) describes the EJB module of the application. It describes the types of beans, their names, and attributes. The structure for this file is mandated in the DTD file, which is provided at " `http://java.sun.com/dtd/ejb-jar_2_0.dtd`".

Any EJB container services that you want to configure is also designated in the deployment descriptor. For information about data sources and JTA, see the Oracle Application Server Containers for J2EE Services Guide. For information about security, see the Oracle Application Server Containers for J2EE Security Guide.

After creation, place the deployment descriptors for the EJB application in the `META-INF` directory that is located in the same directory as the EJB classes. See Figure 10-2 for more information.

The following example shows the sections that are necessary for the `Hello` example, which implements both a remote and a local interface.

Example 10-1 XML Deployment Descriptor for Hello Bean

The following is the deployment descriptor for a version of the Hello example that uses a stateless session bean. This example defines both the local and remote interfaces. You do not have to define both interface types; you may define only one of them.

    <?xml version="1.0"?>
    <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">

    <ejb-jar>
       <display-name>hello</display-name>
       <description>
          An EJB app containing only one Stateless Session Bean
       </description>
       <enterprise-beans>
          <session>
             <description>no description</description>
             <display-name>HelloBean</display-name>
             <ejb-name>HelloBean</ejb-name>
             <home>hello.HelloHome</home>
             <remote>hello.Hello</remote>
             <local-home>hello.HelloLocalHome</local-home>
             <local>hello.HelloLocal</local>
             <ejb-class>hello.HelloBean</ejb-class>
             <session-type>Stateless</session-type>
             <transaction-type>Container</transaction-type>
          </session>
       </enterprise-beans>

       <assembly-descriptor>
          <container-transaction>
             <method>
                <ejb-name>HelloBean</ejb-name>
                <method-name>*</method-name>
             </method>
             <trans-attribute>Supports</trans-attribute>
          </container-transaction>
          <security-role>
             <role-name>users</role-name>
          </security-role>
       </assembly-descriptor>
    </ejb-jar>

Note: You can download this example on OTN from the OC4J sample code page at `http://www.oracle.com/technology/tech/java/oc4j/demos/` on the OTN Web site.

## Archive the EJB Application

After you have finalized your implementation and created the deployment descriptors, archive your EJB application into a JAR file. The JAR file should include all EJB application files and the deployment descriptor.

Note: If you have included a Web application as part of this enterprise Java application, follow the instructions for building the Web application in the Oracle Application Server Containers for J2EE User's Guide.

For example, to archive your compiled EJB class files and XML files for the `Hello` example into a JAR file, perform the following in the `../hello/ejb_module` directory:

    % jar cvf helloworld-ejb.jar .

This archives all files contained within the `ejb_module` subdirectory within the JAR file.

## Prepare the EJB Application for Assembly

To prepare the application for deployment, you do the following:

1. Modify the `application.xml` file with the modules of the enterprise Java application.

2. Archive all elements of the application into an EAR file.

These steps are described in the following sections:

- Modify the Application.XML File

- Create the EAR File

### Modify the Application.XML File

The `application.xml` file acts as the manifest file for the application and contains a list of the modules that are included within your enterprise application. You use each `<module>` element defined in the `application.xml` file to designate what comprises your enterprise application. Each module describes one of three things: EJB JAR, Web WAR, or any client files. Respectively, designate the `<ejb>`, `<web>`, and `<java>` elements in separate `<module>` elements.

- The `<ejb>` element specifies the EJB JAR filename.

- The `<web>` element specifies the Web WAR filename in the `<web-uri>` element, and its context in the `<context>` element.

- The `<java>` element specifies the client JAR filename, if any.

As Figure 10-2 shows, the `application.xml` file is located under a `META-INF` directory under the parent directory for the application. The JAR, WAR, and client JAR files should be contained within this directory. Because of this proximity, the `application.xml` file refers to the JAR and WAR files only by name and relative path—not by full directory path. If these files were located in subdirectories under the parent directory, then these subdirectories must be specified in addition to the filename.

Figure 10-2 Archive Directory Format

Description of the illustration primer3.gif

For example, the following example modifies the `<ejb>`, `<web>`, and `<java>` module elements within `application.xml` for the Hello EJB application that also contains a servlet that interacts with the EJB.

    <?xml version="1.0"?>
    <!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN" "http://java.sun.com/j2ee/dtds/application_1_2.dtd">
    <application>
      <display-name>helloworld j2ee application</display-name>
      <description>
         A sample J2EE application that uses a Helloworld Session Bean
         on the server and calls from java/servlet/JSP clients.
      </description>
      <module>
        <ejb>helloworld-ejb.jar</ejb>
      </module>
      <module>
        <web>
          <web-uri>helloworld-web.war</web-uri>
          <context-root>/helloworld</context-root>
        </web>
      </module>
      <module>
        <java>helloworld-client.jar</java>
      </module>
    </application>

### Create the EAR File

Create the EAR file that contains the JAR, WAR, and XML files for the application. Note that the `application.xml` file serves as the EAR manifest file.

To create the `helloworld.ear` file, execute the following in the `hello` directory contained in Figure 10-2:

    % jar cvf helloworld.ear .

This step archives the `application.xml`, the `helloworld-ejb.jar`, the `helloworld-web.war`, and the `helloworld-client.jar` files into the `helloworld.ear` file.

## Deploy the Enterprise Application to OC4J

After archiving your application into an EAR file, deploy the application to OC4J. See the Oracle Application Server Containers for J2EE User's Guide for information on how to deploy your application.

### Out Of Memory Error During Deployment

If the deployment process is interrupted for any reason, you may need to clean up the temp directory, which by default is `/var/tmp`, on your system. The deployment wizard uses 20 MB in swap space of the temp directory for storing information during the deployment process. At completion, the deployment wizard cleans up the temp directory of its additional files. However, if the wizard is interrupted, it may not have the time or opportunity to clean up the temp directory. Thus, you must clean up any additional deployment files from this directory yourself. If you do not, this directory may fill up, which will disable any further deployment. If you receive an Out of Memory error, check for space available in the temp directory.

To change the temp directory, set the command-line option for the OC4J process to java.io.tmpdir=<new_tmp_dir>. You can set this command-line option in the Server Properties page. Drill down to the OC4J Home Page. Scroll down to the Administration Section. Select Server Properties. On this page, Scroll down to the Command Line Options section and add the java.io.tmpdir variable definition to the OC4J Options line. All new OC4J processes will start with this property.

## Sharing Classes

If you want to share classes between EJBs, you can do one of the following:

- If two EJBs use the same classes, include all classes and the EJBs in the same JAR file. After deployment, both EJBs can use the common classes.

- Place the shared classes in its own JAR file in the application. Reference the shared JAR file in the `class-path` of the EJB JAR `manifest.mf` file, as follows:

      class-path:shared_classes.jar

  The location of the `shared_classes.jar` is relative to where the JAR that references is located in the EAR file. In this example, the `shared_classes.jar` file is at the same level as the EJB JAR.

- If all applications reference these classes, archive the shared classes in a JAR file and place this JAR file in the shared library directory of the default application. The `home/lib` is a default shared library. However, you can set shared library directories using Enterprise Manager in the General Properties page of the "default" application.

- If you want only certain applications to reference these classes, archive the shared classes in its own application, deploy the EAR for the application, and have the applications that reference the shared classes declare the shared classes application as its parent. The default parent in Oracle9iAS is the "default" application.

  The children see the namespace of its parent application. This is used in order to share services such as EJBs among multiple applications. See the Oracle Application Server Containers for J2EE User's Guide for directions on how to specify a parent application.

If you want to share classes between EJB and Web applications, you should place the referenced classes in a shared JAR.

If you receive a `ClassCastException`, then you probably have the following situation:

- You copied EJB interfaces into the WAR where the servlet resides for ease in development and forgot to delete them before creating the WAR file AND

- You turned on the `search_local_classes_first` attribute of the `<web-app-class-loader>` element in the `orion-web.xml` file.

To solve this problem, either eliminate the copied classes out of the WAR file or turn off the search_local_classes_first attribute. This attribute tells the class loader to load in the classes in the WAR file before loading in any other classes, including the classes within the EJB JAR file. For more information on this attribute, see the "Loading WAR File Classes Before System Classes in OC4J" section in the "Servlet Development" chapter of the Oracle Application Server Containers for J2EE Servlet Developer's Guide.

### Out of Memory During Execution

If you see that the OC4J memory is growing consistently while executing, then you may have invalid symbolic links in your application.xml file. OC4J loads all resources using the links in the application.xml file. If these links are invalid, then the C heap continues to grow causing OC4J to run out of memory. Ensure that all symbolic links are valid and restart OC4J.

In addition, keep the number of JAR files to a minimum in the in the directories where the symbolic links point. Eliminate all unused JARs from these directories. OC4J searches all JARs for classes and resources; thus, taking time and memory consumption by the file cache, as well as being mapped into the address space.

### ClassCastException

When you have an EJB or Web application that references other shared EJB classes, you should place the referenced classes in a shared JAR. In certain situations, if you copy the shared EJB classes into WAR file or another application that references them, you may receive a ClassCastException because of a class loader issue. To be completely safe, never copy referenced EJB classes into the WAR file of its application or into another application.

### Static Block in an EJB

During EJB deployment in OC4J, you load the bean class to find out its methods so that you can generate EJB wrappers. Because the code in the static block is executed as the class is being loaded, the JNDI environment context is not yet set up. Even during runtime, the bean is in the "does not exist" stage. In this stage of the life cycle, the JNDI environment context is undefined, and the bean provider cannot rely on it to be available. To work around this problem, set up and cache the context during the construction of the bean, in the `ejbCreate()` method, or in the `setSessionContext()` method.

### OC4J Instances Terminating Due To ping Timeout

Under some conditions, the OPMN process monitoring software in Oracle Application Server may lose contact with an OC4J process. This can occur because of unexpected delays in the hearbeat protocol used by OPMN and OC4J to verify the proper functioning of the OC4J instance.

If this problem occurs sporadically, you can try increasing the ping timeout parameters as described in the following instructions.

However, if this occurs regularly, due to a consistent resource shortage, then you must increase the available hardware resources to solve the problem.

The following conditions can cause this problem:

- An overloaded host processor

- One or more computation-intensive applications running in the OC4J instance.

- Deployment of applications with large numbers (hundreds) of EJBs. Full garbage collections of large heaps can cause the OC4J process to become less responsive during the garbage collection phase. Although this should not occur during normal usage, deployment of large applications with many EJBs in a memory-constrained environment can trigger this behavior.

You can configure the behavior of the "ping protocol" between OPMN and OC4J in the opmn.xml configuration file.

When OC4J exceeds the timeout intervals specified for the ping protocol, the process monitoring software decides that the OC4J process has stopped responding and, therefore, terminates the OC4J process.

If you suspect this behavior in an Oracle Application Server installation, then use the following steps to troubleshoot and work around:

1. When OC4J instances are "mysteriously" terminating, first increase diagnostic logging to determine if ping failures are triggering the termination:

   1. Increase the OPMN logging level to 5 so that you can see the pings.

      In the opmn/conf/opmn.xml file, edit the following line:

          log-file path="$ORACLE_HOME/opmn/logs/ipm.log" level="5" ...

   2. Reload the daemon.

          opmn/bin/opmnctl reload

2. Look in `opmn/logs/ipm.log` for the following line :

       Process Ping Failed:  OC4J~<instance name>~default_island~1 (opmnid)

3. The line above indicates that the memory and CPU resources of the current host are probably not sufficient to perform the operation within the currently specified ping timeout interval (used by OPMN to determine OC4J "responsiveness").

   Change the settings as follows:

   1. Increase the timeout and interval. For example:

          <ping timeout="60" interval="60"/>"
          <data id="reverseping-failed-ping-limit" value="5" />

   2. Reload the daemon.

          opmn/bin/opmnctl reload

   3. Restart the appropriate OC4J instance.

4. Repeat the top-level operation that caused the timeout failure.

## Configuring Environment References

You can create three types of environment elements that are accessible to your bean during runtime: environment variables, EJB references, and resource managers. These environment elements are static and can not be changed by the bean.

ISVs typically develop EJBs that are independent from the EJB container. In order to distance the bean implementation from the container specifics, you can create environment elements that map to one of the following: defined variables, entity beans, or resource managers. This indirection enables the bean developer to refer to existing variables, EJBs, and a JDBC `DataSource` without specifying the actual name. These names are defined in the deployment descriptor and are linked to the actual names within the OC4J-specific deployment descriptor.

### Environment Variables

You can create environment variables that your bean accesses through a lookup on the `InitialContext`. These variables are defined within an `<env-entry>` element and can be of the following types: `String`, `Integer`, `Boolean`, `Double`, `Byte`, `Short`, `Long`, and `Float`. The name of the environment variable is defined within `<env-entry-name>`, the type is defined in `<env-entry-type>`, and its initialized value is defined in `<env-entry-value>`. The `<env-entry-name>` is relative to the "`java:comp/env"` context.

For example, the following two environment variables are declared within the XML deployment descriptor for `java:comp/env/minBalance` and `java:comp/env/maxCreditBalance`.

    <env-entry>
         <env-entry-name>minBalance</env-entry-name>
         <env-entry-type>java.lang.Integer</env-entry-type>
         <env-entry-value>500</env-entry-value>
    </env-entry>
    <env-entry>
         <env-entry-name>maxCreditBalance</env-entry-name>
         <env-entry-type>java.lang.Integer</env-entry-type>
         <env-entry-value>10000</env-entry-value>
    </env-entry>

Within the bean's code, you would access these environment variables through the `InitialContext`, as follows:

    InitialContext ic = new InitialContext();
    Integer min = (Integer) ic.lookup("java:comp/env/minBalance");
    Integer max = (Integer) ic.lookup("java:comp/env/maxCreditBalance"));

Notice that to retrieve the values of the environment variables, you prefix each environment element with "`java:comp/env/`", which is the location that the container stored the environment variable.

If you wanted the value of the environment variable to be defined in the OC4J-specific deployment descriptor, you can map the `<env-entry-name>` to the `<env-entry-mapping>` element in the OC4J-specific deployment descriptor. This means that the value specified in the `orion-ejb-jar.xml` file overrides any value that may be specified in the `ejb-jar.xml` file. The type specified in the EJB deployment descriptor stays the same.

Figure 10-3 shows how the `minBalance` environment variable is defined as 500 within the OC4J-specific deployment descriptor.

Figure 10-3 Environment Variable Mapping

Description of the illustration packaging3.gif

### Environment References To Other Enterprise JavaBeans

You can define an environment reference to an EJB through either its local or remote interface within the deployment descriptor. If your bean calls out to another bean, you can enable your bean to invoke the second bean using a reference defined within the deployment descriptors. You create a logical name within the EJB deployment descriptor, which is mapped to the concrete name of the bean within the OC4J-specific deployment descriptor.

Declaring the target bean as an environment reference provides a level of indirection: the originating bean can refer to the target bean with a logical name.

A reference to the local interface of a bean is defined in an `<ejb-local-ref>` element; a reference to the remote interface of a bean is defined in an `<ejb-ref>` element.

To define a reference to another EJB within the JAR or in a bean declared as a parent, you provide the following:

1. Name—provide a name for the target bean. This name is what the bean uses within the JNDI location for accessing the target bean. The name should begin with "`ejb/`", such as "`ejb/myEmployee`", and will be available within the "`java:comp/env/ejb`" context.

   - This name can be the actual name of the bean; that is, the name defined within the `<ejb-name>` element in the `<session>` or `<entity>` elements.

   - This name can be a logical name that you want to use in your implementation. But it is not the actual name of the bean. If you use a logical name, the actual name must either be specified in the `<ejb-link>` element or `<ejb-ref-mapping>` element in the OC4J-specific deployment descriptor.

2. Type—define whether the bean is a session or an entity bean. Value should be either "`Session`" or "`Entity`".

3. Home—provide the fully qualified home interface name.

4. Remote—provide the fully qualified remote interface name.

5. Link—provide the EJB name of the target bean. This is optional and only used if you used a logical name in the `name` attribute.

#### Examples of References to a Local Interface

If you have two beans in the JAR: `BeanA` and `BeanB`. If `BeanB` creates a reference to the local interface of `BeanA`, you can define this reference in one of three methods:

- Provide the actual name of the bean. `BeanB` would define the following `<ejb-local-ref>` within its definition:

      <ejb-local-ref>
       <ejb-ref-name>myBeans/BeanA</ejb-ref-name>
       <ejb-ref-type>Session</ejb-ref-type>
       <local-home>myBeans.BeanALocalHome</local-home>
       <local>myBeans.BeanALocal</local>
      </ejb-local-ref>

  Since the EJB name of the target is specified in the `<ejb-ref-name>` element, no `<ejb-link>` is necessary for this method. However, the `BeanB` implementation must refer to `BeanA` in the JNDI retrieval, which would use `java:comp/env/myBeans/BeanA` for retrieval within an EJB or Java client and use "`myBeans/BeanA`" within a servlet.

  Note: Servlets do not require the prefix of "`java:comp/env`" in the JNDI lookup. Thus, they will always either reference just the actual JNDI name or the logical name of the EJB.

- Provide the EJB name of the bean in the `<ejb-link>` element. You can use any logical name in your bean implementation for the JNDI retrieval by defining a logical name in the `<ejb-ref-name>` element and then map it to the target bean by specifying the target EJB name in the `<ejb-link>` element. The following defines a logical name of `ejb/nextVal` that this bean can use in its code in the JNDI retrieval. The container maps it to the target bean, `myBeans/BeanA`, which is specified in the `<ejb-link>` element.

      <ejb-local-ref>
       <ejb-ref-name>ejb/nextVal</ejb-ref-name>
       <ejb-ref-type>Session</ejb-ref-type>
       <local-home>myBeans.BeanALocalHome</local-home>
       <local>myBeans.BeanALocal</local>
       <ejb-link>myBeans/BeanA</ejb-link>
      </ejb-local-ref>

  `BeanB` would use `java:comp/env/ejb/nextVal` in the JNDI retrieval of `BeanA`.

- Provide the logical name of the bean in the `<ejb-ref-name>` and the actual name of the bean in the `<ejb-ref-mapping>` element in the OC4J-specific deployment descriptor.

  The reference in the EJB deployment descriptor would be as follows:

      <ejb-local-ref>
       <ejb-ref-name>ejb/nextVal</ejb-ref-name>
       <ejb-ref-type>Session</ejb-ref-type>
       <local-home>myBeans.BeanALocalHome</local-home>
       <local>myBeans.BeanALocal</local>
      </ejb-local-ref>

  The "`ejb/nextVal`" logical name is mapped to an actual name in the OC4J-deployment descriptor as follows:

      <ejb-ref-mapping name="ejb/nextVal" location="myBeans/BeanA"/>

  `BeanB` would use `java:comp/env/ejb/nextVal` in the JNDI retrieval of `BeanA`.

As shown in Figure 10-4, the logical name for the bean is mapped to the JNDI name by providing the same name, "`ejb/nextVal`", in both the `<ejb-ref-name>` in the EJB deployment descriptor and the `name` attribute within the `<ejb-ref-mapping>` element in the OC4J-specific deployment descriptor.

Figure 10-4 EJB Reference Mapping

Description of the illustration packaging4.gif

#### Accessing EJBs Using Environment References

To access a bean from within your implementation using a reference, use the <`ejb-ref-name`> defined in the EJB deployment descriptor in the JNDI lookup.

If you are using the default context when you retrieve the `InitialContext`, then you can do one of the following:

- Prefix the logical name defined within the `<ejb-ref-name>` element with "`java:comp/env/ejb/`", which is where the container places the EJB references defined in the deployment descriptor.

- Do not prefix the logical name with any string and supply only the logical name defined in the `<ejb-ref-name>`.

The following is a lookup from an EJB client, using the `java:comp/env` prefix, assuming that the logical name is "`ejb/HelloWorld`."

    InitialContext ic = new InitialContext();
    HelloHome hh = (HelloHome)ic.lookup("java:comp/env/ejb/HelloWorld");

The following is a lookup using only the logical name of "`ejb/HelloWorld`."

    InitialContext ic = new InitialContext();
    HelloHome hh = (HelloHome)ic.lookup("ejb/HelloWorld");

However, if you are not using the default context, but are specifically using another context, such as the `RMIInitialContext` object, you can only use the logical name, as follows:

    InitialContext ic = new InitialContext();
    HelloHome hh = (HelloHome)ic.lookup("ejb/HelloWorld");

Example 10-2 Defining a Local EJB Reference Within the Environment

The following example defines a reference to the local interface of the `Hello` bean, as follows:

1. The logical name used for the target bean within the originating bean is "`java:comp/env/ejb/HelloWorld`".

2. The target bean is a session bean.

3. Its local home interface is `hello.HelloLocalHome`; its local interface is `hello.HelloLocal`.

4. The `<ejb-ref-name>` attribute is the logical name used within the originating bean. This is optional. In this example, this bean is defined in the EJB deployment descriptor under the "`ejb/HelloWorld`" name.

       <ejb-local-ref>
          <description>Hello World Bean</description>
          <ejb-ref-name>ejb/HelloWorld</description>
          <ejb-ref-type>Session</ejb-ref-type>
          <local-home>hello.HelloLocalHome</local-home>
          <local>hello.Hello.Local</local>
       </ejb-local-ref>

   The `<ejb-ref-name>` element in the EJB deployment descriptor is mapped to the `name` attribute within the `<ejb-ref-mapping>` element in the OC4J-specific deployment descriptor by providing the same logical name in both elements. The Oracle-specific deployment descriptor would have the following definition to map the logical bean name of "`java:comp/env/ejb/HelloWorld`" to the JNDI location "`/test/myHello`":

       <ejb-ref-mapping
          name="ejb/HelloWorld"
          location-"/test/myHello"/>

   To invoke this bean from within your implementation, you use the <`ejb-ref-name`> defined in the EJB deployment descriptor. In EJB or pure Java clients, you prefix this name with "`java:comp/env/ejb/`", which is where the container places the EJB references defined in the deployment descriptor. Servlets only require the logical name defined in the `<ejb-ref-name>`.

   The following is a lookup from an EJB, acting as a client:

       InitialContext ic = new InitialContext();
       HelloHome hh = (HelloHome)ic.lookup("java:comp/env/ejb/HelloWorld");

   Alternatively, you could lookup the name, as follows:

       InitialContext ic = new InitialContext();
       HelloHome hh = (HelloHome)ic.lookup("ejb/HelloWorld");

#### Examples of References to a Remote Interface

Defining a reference to a remote interface uses exactly the same rules as the local interface, as described in "Examples of References to a Local Interface". The only difference is as follows:

- Use the `<ejb-ref>` instead of the `<ejb-local-ref>` element.

- Use the `<home>` and `<remote>` elements instead of the `<local-home>` and `<local>` elements.

Everything else is the same.

The following uses an example with two beans in the JAR: `BeanA` and `BeanB`. If `BeanB` creates a reference to `BeanA`, you can define this reference in one of three methods:

- Provide the actual name of the bean.

      <ejb-ref>
       <ejb-ref-name>myBeans/BeanA</ejb-ref-name>
       <ejb-ref-type>Session</ejb-ref-type>
       <home>myBeans.BeanAHome</home>
       <remote>myBeans.BeanA</remote>
      </ejb-ref>

- Provide the EJB name of the bean in the `<ejb-link>` element.

      <ejb-ref>
       <ejb-ref-name>ejb/nextVal</ejb-ref-name>
       <ejb-ref-type>Session</ejb-ref-type>
       <home>myBeans.BeanAHome</home>
       <remote>myBeans.BeanA</remote>
       <ejb-link>myBeans/BeanA</ejb-link>
      </ejb-ref>

- Provide the logical name of the bean in the `<ejb-ref-name>` and the actual name of the bean in the `<ejb-ref-mapping>` element in the OC4J-specific deployment descriptor.

      <ejb-ref>
       <ejb-ref-name>ejb/nextVal</ejb-ref-name>
       <ejb-ref-type>Session</ejb-ref-type>
       <home>myBeans.BeanAHome</home>
       <remote>myBeans.BeanA</remote>
      </ejb-ref>

  The "`ejb/nextVal`" logical name is mapped to an actual name in the OC4J-deployment descriptor as follows:

      <ejb-ref-mapping name="ejb/nextVal" location="myBeans/BeanA"/>

Refer to "Examples of References to a Local Interface" for more description and a code example.

### Environment References To Resource Manager Connection Factory References

The resource manager connection factory references can include resource managers such as JMS, Java mail, URL, and JDBC `DataSource` objects. Similar to the EJB references, you can access these objects from JNDI by creating an environment element for each object reference. However, these references can only be used for retrieving the object within the bean that defines these references. Each is fully described in the following sections:

- JDBC DataSource

- Mail Session

- URL

#### JDBC DataSource

You can access a database through JDBC either using the traditional method or by creating an environment element for a JDBC `DataSource`. In order to create an environment element for your JDBC `DataSource`, you must do the following:

1. Define the `DataSource` in the `data-sources.xml` file.

2. Create a logical name within the `<res-ref-name>` element in the EJB deployment descriptor. This name should always start with "`jdbc`". In the bean code, the lookup of this reference is always prefaced by "`java:comp/env/jdbc`".

3. Map the logical name within the EJB deployment descriptor to the JNDI name, created in step 1, within the OC4J-specific deployment descriptor.

4. Lookup the object reference within the bean with the "`java:comp/env/jdbc`" preface and the logical name defined in the EJB deployment descriptor.

As shown in Figure 10-5, the JDBC `DataSource` uses the JNDI name "`test/OrderDataSource`". The logical name that the bean knows this resource as is "`jdbc/OrderDB`". These names are mapped together within the OC4J-specific deployment descriptor. Thus, within the bean's implementation, the bean can retrieve the connection to `OrderDataSource` by using the "`java:comp/env/jdbc/OrderDB`" environment element.

Figure 10-5 JDBC Resource Manager Mapping

Description of the illustration packaging5.gif

Example 10-3 Defining an environment element for JDBC Connection

The environment element is defined within the EJB deployment descriptor by providing the logical name, "`jdbc/OrderDB`", its type of `javax.sql.DataSource`, and the authenticator of "`Application`":

    <resource-ref>
       <res-ref-name>jdbc/OrderDB</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Application</res-auth>
    </resource-ref>

The environment element of "`jdbc/OrderDB`" is mapped to the JNDI bound name for the connection, "`test/OrderDataSource`" within the Oracle-specific deployment descriptor.

    resource-ref-mapping
       name="jdbc/OrderDB"
          location="test/OrderDataSource"/>

Once deployed, the bean can retrieve the JDBC `DataSource` as follows:

    javax.sql.DataSource db;
    java.sql.Connection conn;
    .
    .
    .
    db = (javax.sql.DataSource) initCtx.lookup("java:comp/env/jdbc/OrderDB");
    conn = db.getConnection();

Note: This example assumes that a `DataSource` is specified in the `data-sources.xml` file with the JNDI name of "`/test/OrderDataSource`".

#### Mail Session

You can create an environment element for a Java mail `Session` object through the following:

1. Bind the `javax.mail.Session` reference within the JNDI name space in the `application.xml` file using the `<mail-session>` element, as follows:

       <mail-session location="mail/MailSession"
          smtp-host="mysmtp.oraclecorp.com">
          <property name="mail.transport.protocol" value="smtp"/>
          <property name="mail.smtp.from" value="emailaddress@oracle.com"/>
       </mail-session>

   The location attribute contains the JNDI name specified in the location attribute of the `<resource-ref-mapping>` element in the OC4J-specific deployment descriptor.

2. Create a logical name within the `<res-ref-name>` element in the EJB deployment descriptor. This name should always start with "`mail`". In the bean code, the lookup of this reference is always prefaced by "`java:comp/env/mail`".

3. Map the logical name within the EJB deployment descriptor to the JNDI name, created in step 1, within the OC4J-specific deployment descriptor.

4. Lookup the object reference within the bean with the "`java:comp/env/mail`" preface and the logical name defined in the EJB deployment descriptor.

As shown in Figure 10-6, the `Session` object was bound to the JNDI name "`/test/myMailSession`". The logical name that the bean knows this resource as is "`mail/testMailSession`". These names are mapped together within the OC4J-specific deployment descriptor. Thus, within the bean's implementation, the bean can retrieve the connection to the bound `Session` object by using the "`java:comp/env/mail/testMailSession`" environment element.

Figure 10-6 Session Resource Manager Mapping

Description of the illustration packaging6.gif

This environment element is defined with the following information:

Element | Description
--- | ---
`<res-ref-name>` | The logical name of the `Session` object to be used within the originating bean. The name should be prefixed with "`mail`/". In our example, the logical name for our mail session is "`mail/testMailSession`".
`<res-type>` | The Java type of the resource. For the Java mail `Session` object, this is `javax.mail.Session`.
`<res-auth>` | Define who is responsible for signing on to the database. The value can be "`Application`" or "`Container`" based on who provides the authentication information.

Example 10-4 Defining an environment element for Java mail Session

The environment element is defined within the EJB deployment descriptor by providing the logical name, "`mail/testMailSession`", its type of `javax.mail.Session`, and the authenticator of "`Application`":

    <resource-ref>
       <res-ref-name>mail/TestMailSession</res-ref-name>
       <res-type>javax.mail.Session</res-type>
       <res-auth>Application</res-auth>
    </resource-ref>

The environment element of "`mail/testMailSession`" is mapped to the JNDI bound name for the connection, "`test/myMailSession`" within the OC4J-specific deployment descriptor:

    <resource-ref-mapping
       name="mail/TestMailSession"
       location="/test/myMailSession"/>

Once deployed, the bean can retrieve the `Session` object reference as follows:

    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup("java:comp/env/mail/testMailSession");

    //The following uses the mail session object
    //Create a message object
    MimeMessage msg = new MimeMessage(session);

    //Construct an address array
    String mailTo = "whosit@oracle.com";
    InternetAddress addr = new InternetAddress(mailto);
    InternetAddress addrs[] = new InternetAddress[1];
    addrs[0] = addr;

    //set the message parameters
    msg.setRecipients(Message.RecipientType.TO, addrs);
    msg.setSubject("testSend()" + new Date());
    msg.setContent(msgText, "text/plain");

    //send the mail message
    Transport.send(msg);

#### URL

You can create an environment element for a Java `URL` object through the following:

1. Create a logical name within the `<res-ref-name>` element in the EJB deployment descriptor. This name should always start with "`url`". In the bean code, the lookup of this reference is always prefaced by "`java:comp/env/url`".

2. Map the logical name within the EJB deployment descriptor to the URL within the OC4J-specific deployment descriptor.

3. Lookup the object reference within the bean with the "`java:comp/env/url`" preface and the logical name defined in the EJB deployment descriptor.

As shown in Figure 10-7, the `URL` object was bound to the URL "`http://www.myURL`.`com`". The logical name that the bean knows this resource as is "`url/testURL`". These names are mapped together within the OC4J-specific deployment descriptor. Thus, within the bean's implementation, the bean can retrieve a reference to the URL object by using the "`java:comp/env/url/testURL`" environment element.

Figure 10-7 URL Resource Manager Mapping

Description of the illustration packaging7.gif

This environment element is defined with the following information:

Element | Description
--- | ---
`<res-ref-name>` | The logical name of the `URL` object to be used within the originating bean. The name should be prefixed with "`url`/". In our example, the logical name for our URL is "`url/testURL`".
`<res-type>` | The Java type of the resource. For the Java URL object, this is `java.net.URL`.
`<res-auth>` | Define who is responsible for signing on to the database. At this time, the only value supported is "`Application`". The application provides the authentication information.

Example 10-5 Defining an Environment Element for a URL

The environment element is defined within the EJB deployment descriptor by providing the logical name, "`url/testURL`", its type of `java.net.URL`, and the authenticator of "`Application`":

    <resource-ref>
       <res-ref-name>url/testURL</res-ref-name>
       <res-type>java.net.URL</res-type>
       <res-auth>Application</res-auth>
    </resource-ref>

The environment element of "`url/testURL`" is mapped to the URL "`http://www.myURL.com`" within the OC4J-specific deployment descriptor:

    <resource-ref-mapping
       name="url/testURL"
       location="http://www.myURL.com"/>

Once deployed, the bean can retrieve the `URL` object reference as follows:

    InitialContext ic = new InitialContext();
    URL url = (URL) ic.lookup("java:comp/env/url/testURL");

    //The following uses the URL object
    URLConection conn = url.openConnection();