Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Applications
Student Guide Volume 2
D17247GC10
Production 1.0
May 2004
D39457
Authors
Lynn Munsinger
Sunitha Patel
Technical Contributors
and Reviewers
Anna Atkinson
Scott Brewton
Kenneth Cooper
Craig Hollister
Taj-ul Islam
Istvan Kiss
Peter Laseau
Glenn Maslen
Monica Motley-Mosser
Nagavalli Pataballa
Holger Dindler-Rasmussen
Glenn Stokol
Vasiliy Strelnikov
Venkat Tallapragada
Publisher
S. Domingue
Oracle and all references to Oracle Products are trademarks or registered trademarks
of Oracle Corporation.
All other products or company names are used for identification purposes only, and
may be trademarks of their respective owners.
Contents
Preface
1 Introduction
Course Objectives 1-2
Course Environment 1-4
Course Overview 1-5
About the Course Applications 1-8
Order Entry Schema 1-9
Human Resources (HR) Schema 1-10
HR Application Flow Diagram 1-11
Summary 1-12
2 J2EE OverviewObjectives
Objectives 2-2
Java 2, Enterprise Edition Platform 2-3
J2EE Platform 2-4
Benefits of the J2EE Platform 2-5
J2EE Components 2-7
J2EE 1.3 Components 2-8
J2EE Architecture 2-9
Client-Tier Components 2-10
J2EE Web-Tier Components 2-11
What Is a Servlet? 2-13
What Is a JavaServer Page (JSP)? 2-14
Web-Tier Components: Summary 2-15
Business-Tier Components 2-16
Enterprise JavaBeans (EJB) 2-17
J2EE Communication APIs 2-18
J2EE Server 2-19
Oracle Application Server 10g Containers for J2EE (OC4J) 2-21
J2EE Applications 2-22
Packaging J2EE Application Components 2-23
JARs 2-24
WARs 2-25
EJB JARs 2-26
EARs 2-27
EAR File Structure for a J2EE Application: Example 2-28
OC4J Architecture 2-29
OC4J Server Configuration Files 2-30
Relation of Configuration Files 2-31
Data Sources 2-32
Application Logging 2-33
J2EE Application Deployment to
Oracle Application Server 10g 2-34
iii
iv
SingleThreadModel 4-21
JDeveloper Environment 4-23
Servlet Mapping 4-24
Servlet Mapping in JDeveloper 4-25
Invoking a Servlet 4-26
Specifying J2EE Web Module Settings 4-27
Creating a Connection to Oracle Application Server 10g 4-28
Deploying to OC4J 4-29
Summary 4-30
Practices 4-1, 4-2, and 4-3: Overview 4-31
5 Accessing the Database with Servlets
Objectives 5-2
Review of JDBC 5-3
Querying in JDBC 5-4
JDBC and Servlets 5-5
Synchronizing Shared Resources 5-6
Transaction Handling 5-7
Connection Pooling 5-9
Data Sources 5-10
Data Source Definition 5-11
data-sources.xml: Example 5-12
Using Data Sources 5-13
Summary 5-14
Practice 5-1: Overview 5-15
6 Using Advanced Techniques in Servlets
Objectives 6-2
Overview 6-3
HTTP Headers 6-4
Request Headers 6-5
Sending a Response 6-6
Response Headers 6-7
Setting Status Codes 6-8
Example 6-9
Sending Multimedia Content 6-10
Cookies 6-12
Setting Cookies 6-13
Retrieving Cookies 6-14
About State Preservation 6-15
State Preservation: Example 6-16
ServletContext 6-17
RequestDispatcher 6-18
RequestDispatcher: Example 6-19
Servlet Filters 6-20
Using Filters 6-21
doFilter() Method 6-22
Using Filters 6-23
Configuring Filters 6-24
Application Lifecycle Events 6-25
ServletContext Events 6-26
HttpSession Events 6-27
Example of an Event Listener 6-28
Error Handling 6-29
Summary 6-30
Practices 6-1 and 6-2: Overview 6-31
vi
vii
viii
ix
xi
xii
xiii
xiv
xv
xvi
Entity EJBs
Objectives
13-2
Objectives
This lesson introduces the concept of entity beans and the different types of entity beans.
You learn about the different components of an entity bean and the differences between
entity beans and session beans.
Entity Beans
13-3
Entity Beans
Entity beans are objects that can be stored permanently. They represent data stored in the
database in the form of objects. Each object can represent a row in a table, and each field of
the table can be a variable of the object.
Why Data Should Be in the Form of Objects
Data in the form of objects is easier to handle and manage. Related data can be grouped
together. For example, all data related to a particular employee (employee ID, first name,
last name, and so on) can be grouped together in an object. You can also provide methods to
retrieve or manipulate the information that is associated with an object.
To summarize, entity beans are objects just like session bean objects. However, they
represent persistent data in the database. Entity beans are generally represented by nouns
such as names, departments, bank accounts, addresses, phone numbers, and so on.
int x
String s
float f
int y
double d
Entity bean object
Table
13-5
13-6
13-7
ejbLoad()loads the
data from the
persistent storage to
the bean.
ejbStore()saves the
data from the bean
instance to the
persistent storage.
13-11
BMP beans:
Contain code for managing data persistence
Provide flexibility for bean developers to manage
state
Are complicated to program
CMP beans:
Do not contain code for managing persistence
because the container manages the persistence
Use abstract persistence schema and define the
data retrieval/manipulation logic in the deployment
descriptor
Are easier to program and contain lesser code
13-12
13-14
13-15
13-17
Then, a reference to the home interface is obtained by looking up the home interface at that
context.
ProdHome pHome = (ProdHome)
javax.rmi.PortableRemoteObject.narrow
(initCtx.lookup("java:comp/env/ejb/product"),
ProdHome.class);
13-18
Note that the finder methods return a component interface reference, which is nothing but
the EJB object. A client can then find a bean instance as follows:
Product prod = productHome.findByDescription("Keyboard");
13-22
13-23
Remote interfaces:
Are referenced by remote clients
Extend the javax.ejb.EJBObject interface
Local interfaces:
Are referenced by local clients
Extend the javax.ejb.EJBLocalObject interface
13-24
Primary key:
Uniquely identifies each bean instance
Is used to find or remove an entity bean
Can be of any legal value type in RMI-IIOP
13-25
Implements:
Finder methods through ejbFindxxx() methods
Home methods through ejbHomexxx() methods
Callback methods from the EntityBean interface
Business and private methods
13-26
13-27
javax.ejb.EntityBean Interface
13-28
javax.ejb.EntityBean Interface
The slide shows the definition of the EntityBean interface. This interface contains
callback methods that are used during the life cycle of an entity bean.
After the entity bean is created through the ejbCreate() method, the data is inserted into
the database and is ready to be accessed by the client. When a client requests information,
the data must be retrieved from the database and stored into the database when there is data
manipulation such as update or delete of the entity bean. The container manages these
activities by using the callback methods that are described in the slide.
You have already learned that the ejbLoad()and ejbStore() methods are used to
transfer data between persistent storage and the bean instance. These are the callback
methods that are used for saving state during passivation and for loading state during
activation. The ejbActivate() and ejbPassivate() methods are called by the
container before and after an entity bean is swapped out and into the temporary storage.
The container invokes the ejbRemove() method when the client invokes the remove()
method. For a BMP bean, you must remove the data from the database that is associated
with the bean within this method. For a CMP bean, this method is automatically
implemented by the container.
unsetEntityContext()
Pooled
ejbCreate()
ejbPostCreate() ejbActivate()
ejbLoad()
ejbPassivate() ejbRemove()
Ready
ejbStore()
Clients invoke
business methods
13-30
Deployment Descriptor
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE >
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>...</ejb-name>
<home>...</home>
<remote>...</remote>
<ejb-class>...</ejb-class>
<persistence-type>...</persistence-type>
<prim-key-class>...</prim-key-class>
<reentrant>False</reentrant>
<abstract-schema-name>...</abstract-schema-name>
<cmp-field> <field-name>...</field-name> </cmp-field>
<primkey-field>...</primkey-field>
</entity>
</enterprise-beans>
...
13-32
Deployment Descriptor
The two main elements in the deployment descriptor of an entity bean are <enterprisebeans> and <assembly-descriptor>.
The <enterprise-beans> element contains the details of the bean class, primary key
class, and interfaces. This element contains a subelement called <entity>, which
indicates that the enterprise bean being described is an entity bean.
The <assembly-descriptor> element contains information about the security roles,
methods that are accessible for different roles on different beans, and so on. It is the bean
assemblers responsibility to define these roles and responsibilities.
The slide shows the elements in a deployment descriptor. <ejb-jar> is the root element
of the descriptor. Note the various tags in <entity>. The <home>, <remote>, and
<ejb-class> tags provide information about the elements of the entity bean. The
<persistence-type> tag is used to specify whether the bean is a BMP bean or a CMP
bean. <prim-key-class> contains the name of the primary class, which is used to
uniquely identify the entity bean.
Deployment Descriptor
...
<assembly-descriptor>
<security-role>
<description>Public</description>
<role-name>PUBLIC</role-name>
</security-role>
<method-permission>
<description>Public methods</description>
<role-name>PUBLIC</role-name>
<method>
<ejb-name>...</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
</assembly-descriptor>
</ejb-jar>
13-34
Summary
13-35
Summary
In this lesson, you should have learned about entity beans and different types of entity beans.
You have seen the differences between session beans and entity beans, and should now be
able to decide when to use entity beans. You should also have learned about the various
components that build an entity bean and the life cycle of the entity bean.
13-36
Practice 13-1
1. Which two of the following statements regarding entity beans are true?
a. Live for the lifetime of a client
b. Are long-lived and, therefore, are independent of a clients session
c. Model a process or workflow and, therefore, are represented by verbs
d. Contain complex business logic that is needed to process the workflow
e. Represent persistent data. They model data but not business process and,
therefore, are represented by nouns.
2. Which three of the following statements regarding finder methods are true?
a. An entity bean can have one or more finder methods.
b. Finder methods find one row at a time in the database table.
c. Finder methods find a row or rows in the database table.
d. These methods must throw FinderException but need not throw
RemoteException.
e. These methods must throw both FinderException and
RemoteException.
f. They return home interface reference or collection of objects of home interface
type.
3. For methods given in column A, choose appropriate statements from column B.
A
ejbFind()
ejbPassivate()
ejbRemove()
Does not create new database data but loads some existing
entity bean data. The developer must implement this
method for BMP beans, and the container implements this
for CMP beans.
ejbLoad()
ejbStore()
Objectives
14-2
Objectives
You have learned about different types of entity beans in the lesson titled Managing
Persistent Data in the Business Tier. This lesson provides an overview of BMP beans and
discusses CMP beans in detail. You learn to develop a CMP bean, deploy the bean, and
invoke the methods on the bean with a client application.
14-3
14-4
14-5
BMP
CMP
ejbFind()
ejbcreate()
ejbLoad()
ejbStore()
setXXX() and
getXXX()
14-7
abstract
14-9
14-10
14-11
...
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Departments extends EJBObject
{
// set and get methods for CMP fields
Long getDepartment_id() throws RemoteException;
void setDepartment_id(Long newDepartment_id)
throws RemoteException;
String getDepartment_name()throws
RemoteException;
void setDepartment_name(String
newDepartment_name) throws RemoteException;
...
}
14-12
import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;
public interface DepartmentsHome extends EJBHome
{
Departments create() throws RemoteException,
CreateException;
Departments findByPrimaryKey(Long primaryKey) throws
RemoteException, FinderException;
Collection findAll() throws RemoteException,
FinderException;
Departments create(Long department_id, String
department_name) throws RemoteException,
CreateException;
}
14-13
14-14
14-15
...
public void ejbActivate()
{ }
public void ejbLoad()
{ }
public void ejbPassivate()
{ }
public void ejbRemove()
{ }
public void ejbStore()
{ }
}
14-16
14-17
14-20
14-21
14-22
14-23
14-25
java.util.Hashtable;
javax.naming.Context;
javax.naming.InitialContext;
javax.rmi.PortableRemoteObject;
mypackage1.Departments;
mypackage1.DepartmentsHome;
java.util.Collection;
java.util.Iterator;
javax.naming.NamingException;
Note that the client application gets the initial context by invoking the
getInitialContext() method, which is a private method of the bean. The
implementation of this method is the same as in BMP beans. This method is not shown in
this example. The lookup()method returns the reference to the home object
(departmentsHome). This reference can now be used to create an EJB object. A variable
of type Departments is declared.
Oracle10g: Build J2EE Applications 14-25
14-26
14-27
Summary
14-28
Summary
In this lesson, you should have learned that:
The bean provider furnishes the logic to manage the persistence in case of BMP entity
beans
The container provides the persistence logic in CMP entity beans
You should have also learned how to develop a CMP bean and how to invoke the bean
methods from a client application.
14-29
Practice 14-1
The purpose of this practice is to create a CMP entity bean (UpdateEmployee) that
represents the EMPLOYEES table of the hr schema. The bean should contain the set()
and get() methods for the CMP fields. It should also contain a business method called
updateDetails() that updates the EMPLOYEES table.
Note: For this practice, you can use the database connection hr, which was created in step 1
of practice 12-2.
The workspace for this practice is practice14ske.jws. Open the
updateemployeeCMP project. This project contains the necessary skeleton files for this
practice. Note that these files are created by using the entity beans from the Tables option of
JDeveloper, which was demonstrated in this lesson.
1. Navigate to UpdateEmployee.java in the UpdateEmployee bean and open it
in the code editor. This is the remote interface:
Declare an updateDetails()method, which takes the following as parameters:
Long empid (this corresponds to employee_id, which is the primary key of the
table), String lname, String fname, String email, Timestamp hdate, and String
jid. This method should throw RemoteException.
2. Add code to the bean class. Open UpdateEmployeeBean.java in the code editor.
Implement the updateDetails() method declared in the remote interface:
- Invoke the set() methods for the CMP fields lname, fname, email,
hdate, and jid in the updateDetails() method.
3. Edit the UpdateEmployeeClient.java file:
a. Import java.sql.Timestamp.
b. Add code to the try block of the main() method. Use the second form of
create()method with parameters and add a new employee with the following
data: employee_id=600, last_name=shenoy, email=pshenoy,
hire_date=21-jul-2001, and job_id=ST_MAN
Note: Observe the code that creates a Calendar object with the hire_date.
Time in milliseconds is obtained with this object. Use this long value to create
the Timestamp object while invoking the create()and updateDetails()
methods. Pass the long value to the constructor of Timestamp. Other forms of
constructors are deprecated.
c. After the record is added, use the set() method to set the first name to
Preetham. Invoke the get() methods to display the first_name and
last_name.
d. Invoke the updateDetails()business method to update the details of the
employee. Change first_name to Joseph, last_name to Dsouza and
email to jdsouza. Display the first_name and last_name.
e. Find details of the employee whose employee_id=120.
Hint: Use findByPrimaryKey()method. Display the first_name and
last_name of this employee.
Objectives
15-2
Objectives
In a Java 2, Enterprise Edition (J2EE) application, it is not possible to implement the
business logic in a single entity bean. It is practical to identify the smaller tasks and
implement them using CMP entity beans. These entity beans may operate on persistent data
that is related. You can capture such relationships with Container-Managed Relationships
(CMR). This lesson introduces you to the steps of specifying a relationship between CMP
entity beans. In this lesson, you create CMP beans that contain relationships of different
cardinality and directionality.
Relationships
15-3
Relationships
Enterprise applications typically deal with data in multiple tables. These tables are related
and together constitute the complete data for the application. It is a challenging task to
model the relationship between objects and tables in the database. Enterprise JavaBeans
(EJB) 2.0 addresses this by introducing CMR.
The slide shows the relationship between two tables: DEPARTMENTS and EMPLOYEES.
Though only two tables are involved in the relationship, there can be multiple relationships
established between them. Some of the relationships shown in the slide are:
Departments may have one Employee
Departments may have many Employees
Employees may have one Departments
Implementing Relationships
15-4
Implementing Relationships
Data manipulation in the beans may involve a more complex data model, with relationships
between database tables or between entity beans. For example, more than one employee has
the same job ID, or more than one employee works for a department. The relationship is
specified through a foreign key in the database tables.
How do you represent the data model between two entity beans, each of which represents
one object within the relationship? In CMP beans, the container manages the relationship
based on the relationship definition that is defined in the deployment descriptor. In BMP
beans, the bean provider provides the logic for managing the relationship through callback
methods.
The important aspects of a relationship are cardinality and direction.
Cardinality:
One-to-one
One-to-many or many-to-one
Many-to-many
Directionality:
Unidirectional
Bidirectional
15-5
One-to-One Relationships
name
phone_num
100
Smith
111 1111
area_code
service
650
MCI
PHONE
phone_num
111 1111
15-7
One-to-One Relationships
Assume that each employee has only one mobile phone number and each mobile phone
number belongs to only one employee. The diagram in the slide shows this 1:1 relationship
between the EMP and PHONE tables. The phone_num column is the foreign key in the EMP
table that is referencing the PHONE table.
The association table helps in creating a relationship between nonassociated tables. You can
create an association table for a relationship with any cardinality. For CMP beans with a
one-to-many relationship, the server creates a default association table.
One-to-Many Relationships
Each department exists in only one location identified
by location_id, whereas each location can contain
many departments (1:M).
LOCATIONS
location_id
1700
DEPARTMENTS
department_id
15-8
city
Seattle
department_name
location_id
10
Administration
1700
30
Purchasing
1700
One-to-Many Relationships
In the example in the slide, each department exists only at one location. But, each location
can contain many departments. The diagram in the slide shows this 1:M relationship
between the DEPARTMENTS and LOCATIONS tables. The location_id column is the
foreign key in the DEPARTMENTS table that is referencing the LOCATIONS table. This
column is also the primary key of the LOCATIONS table. For each key value in the
LOCATIONS table, there may be more than one matching row in the DEPARTMENTS table.
Many-to-Many Relationships
Each employee may be assigned many jobs and each
job may be assigned to many employees.
EMPLOYEES
employee_id
176
Jonathon
ASSIGNMENTS
assign_pk
A1
JOBS_HISTORY
job_id
employee_id
job_id
176
SA_REP
...
SA_REP
15-9
Name
...
Many-to-Many Relationships
In many-to-many relationships, more than one row from entity A maps to more than one row
from entity B. For example, one employee can be assigned to more than one job and one job
can be assigned to more than one employee. This type of a relationship is the most difficult
to manage.
In relational database design, the many-to-many relationships are normalized by introducing
another table that contains foreign keys to both of the original tables. However, it is not
mandatory to define an entity corresponding to the associating table, such as
ASSIGNMENTS, when defining a many-to-many relationship between entity beans.
The example in the slide shows the additional ASSIGNMENTS table that contains foreign
keys that reference the EMPLOYEES table (employee_id column) and the
JOBS_HISTORY table (job_id column).
To understand this example better, consider an employee with employee_id 176. Check
the job_id of this employee from the JOBS_HISTORY table. You will see two job IDs:
SA_REP and SA_MAN. Now check the employees who have SA_REP as job_id in the
EMPLOYEES table. The query will return 30 rows. Therefore, one employee can be assigned
more than one job and each job can be assigned to more than one employee.
Oracle10g: Build J2EE Applications 15-9
Oracle TopLink
Oracle TopLink run-time framework:
Facilitates data integration with enterprise
applications
Facilitates rapid development, deployment, and
execution of all persistence-related aspects of any
Java application
SQL
TopLink
JDBC
Rows
Java
application
15-10
Oracle TopLink
Oracle TopLink (TopLink) allows Java applications to access data stored in relational
databases as objects. Application developers are able to work with relational databases much
as they would in any Java application regardless of persistence.
With TopLink, developers focus on the application and object model rather than the
infrastructure of the database. TopLink can map Java objects to an existing (legacy)
database or can suggest a new database schema from an object model (or vice versa). It
provides a rich set of features to read, write, delete, and manage objects efficiently.
The mature, robust persistence framework provided by TopLink significantly reduces the
risk of using a relational database in a Java application.
SQL server
J2EE
Application Server
EIS
Servlets/JSPs
Oracle
EJBs
XML
Data mapping and integration
DB2
15-11
15-12
Implementing Relationships
Relationship restrictions:
Define only for CMP 2.0 entity beans
Declare related CMP beans in one deployment
descriptor
Use only local interfaces to define the relationship
15-13
Implementing Relationships
You can define relationships only for CMP 2.0 entity beans. If you want to define
relationship between two entity beans, then the entries for the relationship must be in the
same deployment descriptor. The relationship between the CMP 2.0 entity beans is managed
by the container. You must define only local interfaces for entity beans that take part in
relationships.
Defining relationships: You define a relationship in the deployment descriptor of the beans.
There is only a single deployment descriptor for entity beans that take part in relationships.
The deployment descriptor includes tags for information such as cardinality, direction, field
name, field type, and so on. The methods that support the relationship defined in the
deployment descriptor are included in the local interface and the bean class.
The entity beans that take part in relationships can have only local interfaces. These local
interfaces must have setter and getter methods corresponding to name of the fields. For
example, consider a unidirectional one-to-one relation: an employee can have only one
address. You will design two beans: employee bean and address bean. To define the
relationship, the local interface of the employee bean should have the getAddress()and
setAddress(Address ad)methods. These methods must be included in the
implementation class as abstract methods. These methods are implemented by the container.
Oracle10g: Build J2EE Applications 15-13
Name:
get<cmrfieldname> and set<cmrfieldname>
Example: getDepartment(),
setEmployees(EmpLocal emp)
Return type:
Local interface of the target bean for single object
retrieval
Collection or set of local interface objects for multiple
object retrieval
15-14
...
public abstract class Phone implements EntityBean
{
...
public abstract EmpLocal getEmp_EmployeeID();
public abstract void setEmp_EmployeeID(EmpLocal e);
...
15-15
...
15-16
15-17
15-18
Implementing a Relationship in
the Deployment Descriptor
15-19
15-21
15-22
15-23
15-24
15-25
15-26
15-27
15-28
15-30
Using JDeveloper, you can create a containermanaged relationship between entity beans in the
following ways:
Create CMP beans from tables and generate
default relationships between entities.
Use the EJB Module Editor to specify the
relationship or use TopLink Mapping Editor.
Create an EJB Diagram for CMP beans and
generate default relationships.
15-31
Summary
15-32
Summary
In this lesson, you should have learned about the different types of relationships that can be
established between entity beans. You have also learned about the various tags of the
deployment descriptor that determine the relationship.
15-33
Practice 15-1
The purpose of this practice is to create Employees and Departments entity beans with
a one-to-many relationship. The workspace for this practice is practice15ske.jws.
Open the empdeptCMR project. This project contains the two entity beans: Employees
and Departments.
Note: You will use the database connection hr, which you have used for the lesson 14
practice.
1. Expand the empdeptCMR project and double click DepartmentsBean.java in
the Structure Pane to open it in the editor. Examine the various methods in this class
and observe that all the set() and get() methods are abstract methods. You will
use the following method in your application:
public abstract Collection getEmployees_departmentId();
return returnColl;
Oracle10g: Build J2EE Applications 15-35
10. Create the client application. Right-click the session bean and select New Sample Java
Client. Select Connect to OC4J Embedded in JDeveloper and click OK.
a. Edit the client and import java.util.*.
b. In the main()method, use the session bean instance to invoke the
getEmployeesInDept()to get the information of all employees working in
department 50. Note that this method in turn invokes the
getEmployees_departmentId()method of the Departments bean.
c. Create an Iterator to iterate through the collection that is returned by the
session bean. Typecast the object in the Iterator to EmployeesLocalDTO,
retrieve the values, and print the values. Repeat this for all the objects in the
collection.
d. Invoke the getDepartmentID()method to get the department ID of the
employee with employee_id 118. Note that this method in turn invokes the
getDepartments_departmentId() method of the Employees bean.
11. Right-click EmpdeptSession and select Run.
12. Right-click EmpdeptSessionClient and select Run.
Objectives
16-2
Objectives
This lesson explains the necessity of asynchronous message delivery, and shows how a
message-driven EJB can be developed, deployed, and used to process asynchronous
messages. This lesson also provides an introduction of JMS and different MOM types to
make the concept of message-driven beans more clear.
16-3
Asynchronously
Receiver listens for messages. When a message is
delivered, the listener message handler is invoked.
Receiver thread does not block.
There is loosely coupled interaction.
16-4
16-6
MOM
JMS client
Consumer
Application JMS
JMS Application
Queue/Topic
JMS client
16-7
JMS provider
JMS client
Point-to-Point Model
S1
Queue1
M2
M1
M2
S2
R1
R2
M3
Queue2
Messaging server
Queue sender
M* - Message
16-8
M3
Queues
(virtual destinations)
R3
Queue receiver
Point-to-Point Model
In the PTP model of communication, a sender sends messages to virtual destinations known
as queues.
A sender can send one or more messages. JMS clients who are interested in receiving the
messages subscribe to queues of interest and receive messages from those queues. The
sender does not wait for acknowledgment from the receiver after sending its messages.
One queue can have more than one sender sending the messages and more than one receiver
receiving the messages. However, one message can be delivered to only one receiver from
the queue. The receiver has to pull the message that arrived at this queue.
Note: The JMS specification does not define the method of distribution of messages among
the receivers for a queue. It only requires the guarantee of the message delivery. Therefore,
it is important to ensure that only eligible clients subscribe and receive messages from a
particular queue.
MDBs can make use of the PTP model of communication. However, they are more
commonly designed to use the publish-and-subscribe model that is discussed in subsequent
slides.
Publish-and-Subscribe Model
M1
S1
Topic1
S2
P2
Topic2
M2
Topic publisher
M* - Message
16-9
M2
Messaging server
S3
Topics
(virtual destinations)
Topic subscriber
Publish-and-Subscribe Model
In the publish-and-subscribe (pub/sub) model of communication, a publisher sends messages
to virtual destinations known as topics. A publisher can send one or more messages to a
topic. JMS clients who are interested in receiving the messages subscribe to the topics of
interest and receive messages from those topics. The publisher need not wait for
acknowledgment from the subscribers to publish its messages.
One topic can have more than one publisher and more than one subscriber. The messages
that arrive to this topic are automatically sent to the subscribers. The publisher is not
concerned whether there are any subscribers receiving the messages. A subscriber for a topic
can specify a filter (for example, to receive only messages of priority 1).
A topic subscriber may request either a durable or nondurable subscription. A durable
subscription ensures that the message is delivered to the subscriber whenever it is active.
That is, if a subscriber is not connected to the system when the message was broadcast, the
message broker ensures that the subscriber receives the message whenever it is active.
Examples for pub/sub model communication are stock quote broadcasting and airline arrival
and departure information.
JMS-administered objects:
Connection Factory: Creates connections
Destination: Target/source of messages
16-10
16-12
Receiving Messages
16-15
Receiving Messages
The slide indicates the sequence of steps involved in receiving a message. The following are
the code lines for each step:
1. Context ctx = new InitialContext();
2. TopicConnectionFactory tcf = (TopicConnectionFactory)
ctx.lookup("...");
Topic t = (Topic) ctx.lookup("...");
3. TopicConnection tc = tcf.createTopicConnection();
4. TopicSession tsess = tc.createTopicSession(
false, Session.AUTO_ACKNOWLEDGE);
5. TopicSubscriber tsub = tsess.createSubscriber(t);
6. TextListener tl = new TextListener();
// TextListener implements MessageListener
tsub.setMessageListener(tl);
7. Write the code to process the message contents in the onMessage() method of the
TextListener class.
16-16
Message-Driven Beans
MDBs:
Are programmed for receiving and processing
asynchronous messages through the JMS
Destination
Are stateless, server-side, transaction-aware
components
Are not accessible directly by any client
Do not contain home and component interfaces
Are triggered by a container when a message
arrives
Implement the javax.ejb.MessageDrivenBean
and javax.jms.MessageListener interfaces
16-17
Message-Driven Beans
You have learned that any Java application can be a consumer for the messages that arrive
from the JMS publishers. Web applications are accessible through HTTP, and session or
entity EJBs are accessible through RMI/IIOP. If a Web application or a session bean
contains a method that listens for a message from a topic (or queue), the method looks up
the connection factory and creates a connection, a session, and a subscriber. The method
then waits to receive the message from the publisher. If there are no messages to be
received, then the methods thread is blocked and the client has to wait until the message is
received, and the wait may never end. Therefore, it is not good practice to block a thread
while listening for JMS messages in a Web application, or a session or an entity EJB.
A solution to avoid infinite waiting in the message listener is to call the receive()
message method with a timeout, or to implement the receiveNoWait() method. The
EJB 2.0 specification defines the MDB as a new EJB type designed to receive and process
messages delivered asynchronously through the JMS architecture.
MDBs are stateless. They reside in the server and can participate in transactions. MDBs are
invoked through JMS and not RMI/IIOP, and they are never directly accessed from any
client application. Therefore, MDBs do not contain home and remote interfaces. They are
triggered by the container when a message is received at its destination.
Oracle10g: Build J2EE Applications 16-17
MDB Architecture
OC4J
Client
JMS resource
provider
MDB
Queue/Topic
16-18
MDB Architecture
The diagram in the slide shows an overview of MDBs with the OC4J JMS resource provider.
MDBs can use OC4J JMS or Oracle JMS as resource providers.
To configure OC4J JMS as a resource provider, specify the following in the jms.xml file:
<log>: The file name or e-mail address to send log messages for the OC4J queue
The MDB is declaratively associated with the OC4J JMS provider destination in the J2EE
and OC4J deployment descriptors. A JMS session is established to receive messages from
the destination in the onMessage() method of the MDB.
orion-ejb-jar.xml:
<enterprise-beans>
<message-driven-deployment max-instances="-1"
name="MessageProcessor" connection-factorylocation="jms/QueueConnectionFactory" destinationlocation="jms/demoQueue" min-instances="0"/>
</enterprise-beans>
16-19
Container invokes
ejbRemove()
Method-ready pool
Container invokes
onMessage()
16-20
Developing MDBs
4. Create the EJB JAR file that contains the bean and
the deployment descriptors.
5. Create the .ear file and deploy the bean.
16-22
Developing MDBs
The slide lists the sequence of steps that are involved in creating an MDB. To configure
OC4J with the JMS provider details, configure the jms.xml file with the destination object
information.
Implement the bean class for an MDB, where you define how the message received by the
bean should be processed.
Configure the deployment descriptors for the JMS Destination:
Specify the destination type used for the MDB in the EJB deployment descriptor
(ejb-jar.xml).
Specify the details of the destination used for the MDB in the OC4J-specific
deployment descriptor (orion-ejb-jar.xml). Some of the details about
destination are located in the application.xml configuration file.
Package the message-driven bean with its deployment descriptor and other supporting files.
Create an Enterprise Archive file and deploy the bean to the OC4J instance. These steps are
discussed in detail in the following pages.
MessageDrivenBean interface:
package javax.ejb;
public interface MessageDrivenBean extends
javax.ejb.EnterpriseBean
{
public void setMessageDrivenContext
(MessageDrivenContext context) throws EJBException;
public void ejbRemove() throws EJBException;
MessageListener interface:
package javax.jms;
public interface MessageListener {
public void onMessage(Message message);
}
16-23
16-24
16-25
ejb-jar.xml: Example
...
<enterprise-beans>
<message-driven>
<ejb-name>MessageLogger</ejb-name>
<ejb-class>btier.impl.MessageLogger</ejb-class>
<acknowledge-mode>Auto-acknowledge
</acknowledge-mode>
<message-driven-destination>
<destination-type> javax.jms.Queue
</destination-type>
<subscription-durability>Durable
</subscription-durability>
</message-driven-destination>
</message-driven>
...
16-28
ejb-jar.xml: Example
The slide shows the <message-driven> element of the ejb-jar.xml file for the
sample MDB. The MDB specifies its destination type as Topic and a durable subscription
for the messages. The following code shows the complete deployment descriptor:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE ejb-jar PUBLIC '//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
<ejb-jar><enterprise-beans><message-driven>
<ejb-name>MessageLogger</ejb-name>
<ejb-class>btier.impl.MessageLogger</ejb-class>
<acknowledge-mode>Auto-acknowledge</acknowledge-mode>
<message-driven-destination>
<destination-type>javax.jms.Queue</destination-type>
<subscription-durability>Durable</subscription-durability>
</message-driven-destination>
</message-driven></enterprise-beans></ejb-jar>
Mapping in OC4J-Specific
Deployment Descriptor
In the orion-ejb-jar.xml file, associate a JMS
Destination with the MDB in the <message-drivendeployment> element by using the following
attributes:
Name: MDB name as defined in the <ejb-name>
connection-factory-location: JMS
Destination Connection Factory
destination-location: JMS Destination
subscription-name: Subscription name
(required only if the JMS Destination is a topic)
16-29
orion-ejb-jar.xml: Example
<enterprise-beans>
<message-driven-deployment
name="MessageLogger"
connection-factory-location=
"jms/QueueConnectionFactory">
destination-location=
"jms/demoQueue"
</message-driven-deployment>
...
</enterprise-beans>
16-30
orion-ejb-jar.xml: Example
The code in the slide is the orion-ejb-jar.xml deployment descriptor for the
MessageLogger example. It maps a JMS Queue to the MessageLogger MDB,
providing information in the following attributes:
The name of the MDB is MessageLogger as defined in the ejb-jar.xml file.
The connection-factory-location attribute specifies the name of the OC4J
JMS Destination connection factory location.
The destination-location attribute sets the OC4J JMS Destination location.
After these attributes are specified in the <message-driven-deployment> element,
the container associates the MDB with the OC4J JMS Destination, based on how the
attribute values are mapped to the JMS resources.
16-31
ejb-jar.xml
16-32
orion-ejb-jar.xml
16-33
16-34
Summary
16-35
Create an MDB
Compare a stateless session EJB and an MDB
Describe JMS
Configure a JMS resource provider in the OC4J
jms.xml file
Summary
In this lesson, you should have learned the concepts of JMS. You should have also learned
how to create and access MDBs.
16-36
Practice 16-1
In this practice, you create a simple message-driven bean to receive messages from an OC4J
JMS queue, and modify a JSP to send messages to the EJB. Open the practice16.jws
workspace in the practice16 directory. The workspace contains the two projects
webtier and businesstier, along with their respective solution projects
webtiersoln and businesstiersoln.
1. Create the log message table used by the Logmessages entity to store messages that
are sent to the MDB that you create. Use SQL*Plus to execute logmessages.sql f
rom the directory: E:\jdev9051\jdev\mywork\practice16
2. Now modify some OC4J configuration files to use OC4J JMS.
a.
Create a new queue and data source reference. Open a browser and navigate to
http://localhost:1810. Enter the username ias_admin and the
password welcome1. Click on the home instance page.
b. Click the Administration tab and the Advanced Properties link. Click the
jms.xml link to add a queue and queue connection factory.
c.
Create a new queue named "jms/Queue/Queue1" with a location of
"jms/Queue/Queue1". Provide the queue connection factory location as
"jms/Queue/QCF". It is important that you type these entries and do not copy
and paste from another location. Click Apply and then click OK.
d.
Next create a new data source. From the home instance page, click the Data
Sources link. Click Create and enter these details:
Name: LogDS
Description: log
Data Source Class:
com.evermind.sql.DriverManagerDataSource
JDBC URL: The URL provided to you by your instructor
JDBC Driver: oracle.jdbc.driver.OracleDriver
In Datasource Username:
Username: oraxx (as provided to you by your
instructor)
Use a cleartext password of oracle
In JNDI Locations:
Location: jdbc/LogCoreDS
Transactional location: jdbc/xa/LogXADS
EJB location: jdbc/LogDS
Leave all other fields blank or set to the default.
e.
Click Create and restart the server when prompted.
3.
Create a simple MDB to accept a message from an OC4J JMS queue, and store the
message text as a record in a log table by using the Logmessages entity bean
provided.
a.
In the businesstier project, create a new Enterprise JavaBean of the MDB
type. Define the bean name as MessageLogger.
King
102
de Haan
203
Mavris
Objectives
17-2
Overview
Web tier
JSP
HttpServlet
Request
EJB tier
Controller
servlet
To EIS
HttpServlet
Response
17-3
Employees
JSP
Employees
EJB
Overview
The slide shows a sample application that adheres to the Model-View-Controller (MVC)
framework. In this application, a JSP accesses EJBs through a Controller servlet, which
forwards the users request to the appropriate JSP. The Employees JSP acts as a client to the
EJB. This lesson teaches you how to access EJBs from JSP, and how to deploy an
application such as the one shown in the slide.
17-4
17-5
mypackage.Employees.*;
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
javax.naming.*;
class EJBClientServlet extends HttpServlet
17-6
17-7
17-8
17-9
ejb-local-ref Element
17-10
ejb-local-ref Element
Instead of creating an ejb-ref element for remote EJBs, create an ejb-local-ref
element in the web.xml file by right-clicking it. Select EJB Local References, and then add
a reference as shown in the slide.
EJB Tags
17-11
EJB Tag
Purpose
useHome
useBean
createBean
iterate
EJB Tags
You can retrieve references to EJBs by using the EJB tags that are provided in the OJSP
(OC4J JSP) library. Use the useHome bean to look up a home interface for the EJB. The
useBean tag instantiates the EJB. You can specify either the value attribute or a nested
createBean tag to create the EJB instance. The iterate tag iterates through EJB
instances. This is commonly used for entity beans, because standard finder methods for
entity beans return collections.
useHome Tag
17-12
useHome Tag
Define three attributes in the useHome tag. First, specify the id, which is a name for the
home interface instance. Next, specify the name of the home interface in the type attribute.
Lastly, provide the Java Naming and Directory Interface (JNDI) location that is used to look
up the home interface of the EJB. This should correspond to your <ejb-ref> element
entry in the web.xml file. The local attribute should be false when the type class
name refers to the remote home interface of the bean, and true when using the Local
Home interface.
useBean Tag
17-13
useBean Tag
First, specify an instance name for the EJB in the id attribute. Next, specify the class name
of the EJB in the type attribute. You can use the value attribute or a nested
createBean tag to create the instance, as shown below. Lastly, specify the scope of the
instance. This can be page, session, request, or application, similar to
specifying the scope in JSPs for JavaBeans.
<EJB:useBean id="bean" type="mypackage.EmployeesBean" scope="session">
<EJB:createBean instance="<%=empHome.create()%>" />
</EJB:useBean>
createBean Tag
17-14
createBean Tag
instance is a required attribute of createBean, which returns the EJBObject
instance. In the example given in the slide, the create() method of the EJB home
interface creates the instance.
iterate Tag
17-15
17-16
Note that although you can specify any prefix value, EJB is conventionally used.
17-17
17-18
17-19
17-20
Summary
17-21
17-22
Practice 17-1
The purpose of this practice is to create JSP clients for the EJBs that you have written in
previous practices. Within practice17ske.jws, there are two projects,
businesstier.jpr and webtier.jpr (the solution files are contained in
practice17soln.jws). businesstier.jpr contains the Employee session EJB
that you developed in practice 12, as well as the UpdateEmployee entity EJB that you
created in practice 14. The webtier project contains the LoginServlet that you
created in practice 5. In this practice, you put together all the knowledge to create a
complete J2EE application.
1. Modify LoginServlet to test a user who logs in. In this practice, because company
employees are using the application, change the LoginServlet to verify the login
for an employee, rather than for a customer.
a. In the init() method, change the data source lookup to jdbc/hrDS.
b. In the doGet() method, change the heading for the human resources
application and change the forms fields to accept the employee ID and employee
name.
2. Modify the verifyCustomer() and getOrders() methods to
verifyEmployee() and getRoles(). Only employees who have a valid login
will be accepted, and only employees who have an administrator role will be allowed
to insert new employees (who will be added later).
a. Change verifyCustomer() to verifyEmployee(), and return a jobid
from this method. Pass in a connection, employee_id, and employee_name as
arguments to this method. The jobid will be used to check for the administrator
roles in the getRoles() method.
b. Change the statement to select the employee_id, last_name, and job_id
from the EMPLOYEES table where the last_name is the employee_name
that is passed to this method, and where employee_id is the employee ID that
is passed to this method.
c. In the while loop, set the value of jobid to the job_id from the query.
Remove the code for checking the custid value.
d. Change getOrders() to getRoles(). This method will return a Boolean
value, indicating whether the employee is an administrator. It will accept the
connection and the jobid from the verifyEmployee() method.
e. Create a variable for this method, initialized to null, to store the value of the
string that is returned from the query.
f. Change the prepareStatement() method (in the init() method) to select
job_id from the JOBS table where job_id is equal to the argument passed to
the method. In the getRoles() method, use the setString() method to
pass in the argument.
g. In the while loop, set the value of the variable created in step e. to the jobid that
is returned from the query.
h. If the value equals HR_REP, AD_PRES, or AD_VP, return true. Otherwise,
return false.
3. Create a new method to forward the request to a JSP in the application.
a. Name the method gotoPage(). It should accept an address (as string) and the
HttpServletRequest and HttpServletResponse objects, and then
throw the ServletException and IOException exceptions.
Oracle10g: Build J2EE Applications 17-23
Last Name
100
King
101
Kochhar
102
de Haan
203
Mavris
Practice 17-2
In this practice, you deploy the application that you created in Oracle Application Server
10g.
1. Create an EJB JAR file for the businesstier project.
a. Right-click businesstier and select New.
b. From the Deployment Profiles category, select EJB JAR File.
c. Accept the default deployment profile name.
d. Specify the enterprise application name as hrejb.
e. Right-click the deployment profile and select Deploy to JAR file.
2. Create a WAR file for the webtier project.
a. Right-click webtier and select New.
b. From the Deployment Profiles category, select WAR File.
c. Accept the default deployment profile name and click OK.
d. Specify the context root as /hrapp.
e. Right-click the deployment profile and select Deploy to WAR file.
3. Create an EAR file for the application.
a. Right-click webtier and select New.
b. From the Deployment Profiles category, select EAR File.
c. Accept the default deployment profile name and click OK.
d. Name the application hr.
e. In the Application Assembly category, include the deployment profiles that you
created in steps 1 and 2 and click OK.
f. Right-click the deployment profile and select Deploy to EAR file.
4. Deploy the application by using Oracle Enterprise Manager.
a. Navigate to http://localhost:1810 and supply the username as
ias_admin and the password as welcome1.
b. Select home to open the OC4J home instance page.
c. Click the Applications tab and click the Deploy EAR File button.
d. Browse for the application1.ear file. By default, this will be in
practice17ske\webtier\deploy. Supply a name of practice17 for
the application name and click Continue.
e. Verify whether the URL binding for this application is /hrapp, and click Next.
This means that you can access the application by using this shortened name.
f. Enter jdbc/hrCoreDS for the JNDI location name and click Next. In practice
2, you have already mapped this data source in OC4J.
g. Click Next at the following page because there is no user security defined for this
application.
h. Click Deploy to deploy the application.
5. Test the application by accessing the following URL:
http://localhost/hrapp/loginservlet
Objectives
18-2
Objectives
This lesson provides an overview of Web services. This lesson also discusses some of the
de facto industry standards such as Simple Object Access Protocol (SOAP), Web Services
Description Language (WSDL), and Universal Description, Discovery, and Integration
(UDDI). In addition, you learn about the benefits of Web services.
HTML
Web
presentation
HTTP client
Business
logic
XML
External
applications
18-3
Web
service
Databases
Application Server
Web Service
18-4
Web Service
Need for Web Services
Several businesses today have become e-businesses. The greatest challenge for the
successful transformation is application-to-application communication. An enterprise
solution usually has multiple applications, each running on different hardware and
sometimes implemented in different languages. There is often a need to communicate and
exchange data between applications. To achieve this, developers spend time writing the
plumbing application. Web service is a technology based on a set of standards that provides
a solution for application-to-application communication and enterprisewide application
integration.
Standards for Interoperable Distributed Applications
Enterprise solutions are developed with a variety of languages such as C++, Java, Visual
Basic (VB), and so on. A main requirement of such applications is the need to integrate and
exchange data with other applications. By using Web services, clients and servers can
communicate over standard Internet protocols regardless of the platform or the programming
language. Developers can write their business functionality in any language and on any
preferred platform. The applications that are developed must adhere to the standards so that
they can be exposed and accessed as Web services.
Oracle10g: Build J2EE Applications 18-4
Service-Oriented Architecture
Service
registry
Publish
Find
Service
provider
18-6
Invoke
Service
requestor
Service-Oriented Architecture
During development of Web services, a new pattern called Service Oriented Architecture
(SOA) evolved. SOA has a service provider, a service requestor, and a service registry.
Service Provider
Web services perform a specific task or a set of tasks. For example, a Web service can be
used to obtain the weather report of a given place. A service provider is responsible for
developing a Web service, creating the service description, and publishing that description
to one or more registries.
Service Requestor
A consumer of a Web service is considered a service requestor. A service requestor finds the
service description in one or more registries to invoke a service.
Service Registry
A service registry contains descriptions of the services that are published by service
providers. Service requestors use this registry to find a service.
18-7
18-9
2
Find
Web services
directory
(UDDI)
Invoke
Publish
18-11
18-12
18-13
Oracle Application
Server 10g is the
infrastructure for:
Describing Web
services
Deploying Web
services
Publishing Web
services
Invoking Web
services
18-14
18-15
Request
Response
SOAP client
18-16
Firewall
Web server
SOAP Messages
A SOAP message is an
XML document that
consists of:
A mandatory
envelope as a toplevel element
An optional header
A mandatory body
18-17
An optional fault
HTTP headers
SOAP envelope
SOAP header
Headers
SOAP body
Message name, data,
and fault element
SOAP Messages
SOAP is the second generation XML protocol that uses XML schema for data types.
Therefore, it is highly extensible. First generation XML protocols rely on XML1.0 and are
not extensible.
SOAP does not define any application semantics such as a programming model or
implementation-specific semantics; instead, it defines a simple mechanism for expressing
application semantics.
The slide shows a SOAP message over HTTP protocol that contains the following elements:
HTTP headers: When a SOAP protocol is used over HTTP, the packet starts with an
HTTP header, which contains information about the operation, method, Content-Type,
Content-Length, error codes, and the recipient of the message.
Header: The Header is optional. If present, Header is the first child element of
Envelope. Header is included to add features to a SOAP message without prior
agreement between the communicating parties. A Header can in turn have any
number of headers. These headers are included to provide additional information that
is handled by infrastructure services. In a real-world scenario, login information,
session information, security, transactional information, and so on, can be included in
the body. However, this approach makes the SOAP message more complicated.
Instead, this information can be included as multiple headers.
Body: The Body element provides a simple mechanism for exchanging mandatory
information with the ultimate recipient of the message. This element includes RPCs
and error reporting. In case of request messages, the body section contains the methodspecific information that is required to invoke the method. In the response message,
the body section contains the return message from the Web service. In case of an error
condition, the Body element can contain a Fault element.
Fault: Fault element is used to indicate that an error has occurred and provides
information about the error. This element is used to carry error or status information
within a SOAP message. Fault elements appear as a body entry and must not appear
more than once within a Body element.
A SOAP application should include the proper SOAP namespaces on all elements that are
defined in messages. SOAP messages should not contain Document Type Definition (DTD)
and Processing Instructions (PI).
18-19
WSDL
SOAP provides a standard way of transporting messages for use by Web services, whereas
WSDL provides a standard way to describe Web services. WSDL is an XML format for
describing Web services. WSDL describes what functionality a Web service offers, how it
communicates, and where it is accessible. Because it is in the standard XML format, the
services developed can easily be made available to thousands of users. Users must invoke
the correct services with the appropriate parameters. WSDL defines an XML grammar to
specify the location of the service and to describe the operations of a service.
A WSDL file contains the following information about an operation:
Service interface
Implementation details
Access protocol
Contact endpoints
WSDL
<?xml version=1.0 encoding=UTF-8 ?>
<definitions name=Hello ...
targetNamespace=http://tempuri.org/Hello.wsdl ...>
<types>
<schema targetNamespace=http://tempuri.org/Hello.xsd
...
xmlns:xsd=http://www.w3.org/2001/XMLSchema />
</types>
<message name=sayHelloOutput>... </message>
<message name=sayHelloInput> ... </message>
<portType name=HelloPortType>
<operation name=sayHello> .... </operation>
</portType>
<binding name=HelloBinding>
<operation> <input>..</input> <output>..</output>
</operation> </binding>
<service ..> <port> <soap:address location=.. />
</port>
</service>
</definitions>
18-20
WSDL (continued)
The slide shows the various tags in a WSDL file.
<types>: The <types> element encloses data type definitions for the exchanged
messages. This element contains the xsd schema namespace. This schema is where
you define custom types to use with messages. For interoperability and platform
neutrality, WSDL uses data types as defined in the XML Schema specification.
Therefore, the data types that are used to pass parameters and obtain return values
must conform to xsd.
WSDL (continued)
<binding>: The <binding> element is used to specify that SOAP protocol is used
over HTTP. It also shows whether it is an RPC-style invocation or a document-style
invocation of Web service.
<service>: The <service> element contains the name of the Web service, the
location of the Web service, and the context with which it can be accessed. A service
groups a set of related ports together. It can contain zero or more port elements. The
port elements specify how this service can be accessed. A port contains a network
address and the binding of the Web service.
Note that the WSDL file is automatically generated and, therefore, each tag of the WSDL
file is not explained in detail.
UDDI Registry
18-22
UDDI Registry
You have been introduced to Web services and their benefits. You have also learned that
WSDL is used to describe Web services, and that the SOAP protocol is used to invoke them.
To invoke a Web service, the service requestor should first discover the service and then
send the SOAP message. The UDDI is a registry where businesses and Web services are
registered. The requestor can use UDDI to discover a Web service.
What Is UDDI?
UDDI Project is an industry initiative that provides standards for publishing and discovering
information about Web services. The UDDI community, which is established by several
leading software vendors including IBM, Microsoft, and Oracle, runs the UDDI Project and
makes its results available to the public through http://www.uddi.org/.
UDDI is a directory service where businesses can register and search for Web services. It is
a platform-independent framework for describing services, discovering businesses, and
integrating business services.
The UDDI registry can be used at a business level to discover if there are any Web service
interfaces with a given type of service. UDDI serves as a mechanism for businesses to reach
their customers and partners. It is used to locate information about how the service is
exposed and to learn the technical details required to interact with that service.
Oracle10g: Build J2EE Applications 18-22
UDDI Business
Registry
UDDI Registry
Business
descriptions
Business user
18-24
Service
types
Software developer
Provider info
Contact Info
Directory of
names
White pages
Search using
context such as
location, service
type. Point to
White pages for
details.
Information about
business model
Technical details
of provided
service
Information on
business process
Yellow pages
18-25
Green pages
UDDI Specification
18-26
tModel
18-27
tModel
A <tModel> is an abstract description of a particular specification of the Web service. A
<tModel> is a type of digital fingerprint for determining the specifics of how to interact
with a particular Web service. The <tModel> structure does not provide the Web services
specification directly. Instead, it contains pointers to the locations of the actual
specifications. Companies can use the information pointed to by a <tModel> to determine
whether a Web service is compatible with their business requirements.
The relation between businessService and tModel is described as follows:
<businessService> has a <bindingTemplate> that contains one or more
<tModelInstanceInfo> documents. Each <tModelInstanceInfo> document
contains a tModelKey attribute that is the Universal Unique Identifier (UUID) of a
<tModel> document, representing information about the supporting specification.
When businesses want to make their specification-compliant services available to the
registry, they include a reference to the tModelKey attribute for that service type in their
<bindingTemplate>.
tModel
<tModel
tModelKey="uuid:7716711A-1231-483F-A4B936104341BA78" operator= authorizedName=>
<name>Airport Weather</name>
<description xml:lang="en">
Web Service to check weather on intl. airports
</description>
<overviewDoc>
<description ></description>
<overviewURL>
http://live.capescience.com/wsdl/AirportWeather.wsdl
</overviewURL>
</overviewDoc>
...
</tModel>
18-28
tModel (continued)
The slide shows a fragment of the tModel structure. Each <tModel> contains a UUID as
a tmodelKey attribute. UUIDs are unique hexadecimal strings that are generated when the
data structure is first inserted into the UDDI registry. The tModel name identifies the
service. In this example, Airport Weather is the service. The description supplies
explanatory information.
The tModel also contains an <overwiewDoc> entry which in turn contains an
<overviewURL> entry. This URL points to the service WSDL description.
A <tModel> has several uses in the UDDI registry. The most common use is to represent a
technical specification or concept. The designer of a specification or a concept publishes
information about the specification by registering it in an UDDI registry as a tModel.
Thus, a tModel identity is defined in the registry, but the actual specification or set of
documents that describes the concept of a tModel is not a part of the registry. Instead, it is
remotely referenced by the <overviewDoc> structure.
<overviewDoc>
<description xml:lang="en"/>
<overviewURL>
http://ws.cdyne.com/psaddress/addresslookup.asmx?wsdl
</overviewURL>
</overviewDoc>
<categoryBag>
<keyedReference
tModelKey="UUID:C1ACF26D-9672-4404-9D7039B756E62AB4"
keyName="uddi-org:types"
keyValue="wsdlSpec" />
</categoryBag>
</tModel>
18-31
18-32
18-33
Summary
18-34
Summary
In this lesson, you should have learned about Web services. You should have also learned
about standards such as SOAP, WSDL, and UDDI. This lesson discussed the benefits of
Web services and the different styles of Web services.
18-35
Practice 18-1
Paper-Based Questions
1. Identify three features of Web services.
a. Self-describing business function
b. Interfaces for a client to invoke a business function
c. Service oriented
d. Component based
e. Language dependent
2. Which three of the following can be exposed as Web services with Oracle Application
Server 10g?
a. Stateless/stateful Java classes
b. C programs
c. PL/SQL stored procedures
d. Stateless session EJBs
e. Stateful session EJBs
3. SOAP is: (Choose two correct answers.)
a. A heavyweight protocol
b. An XML-based protocol
c. Always layered over HTTP
d. Request oriented and response oriented
4. Which three of the following statements regarding a SOAP message are true?
a. It should have Envelope as top-level element.
b. If Envelope is not present, Header should be the top-level element.
c. If Header is present, then it should immediately follow the Envelope
element.
d. It should have a Body, but need not have a Header element.
e. It should have an Envelope, Body, and Header, irrespective of their order.
5. Match the elements of a SOAP message in column A to the appropriate statements
given in column B.
A
1. Envelope
2. Header
3. Body
Objectives
19-2
Objectives
This lesson describes how to expose a stateless Java class as a Web service. You learn to use
Oracle JDeveloper 10g to develop and deploy a stateless Java Web service. This lesson
shows you how to create a client to invoke a Web service. It also discusses the steps
involved in exposing a PL/SQL stored procedure as a Web service.
19-4
Define an interface.
Define a stateless Java class.
Generate an .ear file.
Deploy the generated .ear file to Oracle
Application Server 10g.
Defining an Interface
19-5
Defining an Interface
The example used is a stateless Java class that is exposed as a Web service. The Hello
Web service contains a sayHello() method, which takes a String as parameter and
returns a String when it is invoked.
Why Define an Interface?
Writing an interface is optional. If an interface is not defined for a class, then the Web
service deployment exposes all public methods that are defined in the Java class as Web
services. You define an interface to limit the exposure of methods to a subset of the public
methods within a class. Although a class can contain n number of public methods, it is not
necessary to expose them all as Web services to clients. Therefore, an interface can contain
declarations of methods that can be exposed as Web services.
Creating the Interface Using JDeveloper 10g
Create a workspace and a project. Right-click the project and select New Java Interface as
shown in the slide. Provide a name for the new interface. Observe that the name Hello is
used for this example. The interface will be created. You have to define the methods of the
interface.
The slide shows the interface called Hello. It declares a single method, sayHello(),
that takes a String as parameter and returns a String.
Oracle10g: Build J2EE Applications 19-5
Defining an Interface
19-6
19-7
19-8
Object Types
java.lang.Boolean
java.lang.Byte
java.lang.Double
java.lang.Float
java.lang.Integer
java.lang.Long
java.lang.Short
java.lang.String
java.util.Date
org.w3c.dom.Element
org.w3c.dom.Document
org.w3c.dom.DocumentFragment
JavaBeans
Single-dimension arrays of types mentioned in the
table
19-10
19-11
19-12
19-13
19-14
19-15
19-16
19-17
19-18
19-19
19-20
Database
19-21
JPublisher
Java classes
19-22
19-23
Send operation
Receive operation
19-24
Summary
19-26
Summary
In this lesson, you should have learned how to expose a stateless Java class as a Web
service, and how to develop and deploy Web services from Java classes by using Oracle
JDeveloper 10g. You should have also learned how to use Web services home page to test
the deployed Web service, and how to write a client application to invoke the Web service.
You have learned that a PL/SQL stored procedure can be exposed as a Web service by:
1. Creating Java wrapper classes by using Jpublisher.
2. Creating an EAR file.
3. Deploying the EAR file to Oracle Application Server 10g or stand-alone OC4J.
19-27
Practice 19-1
The purpose of this practice is to expose a stateless session EJB as a Web service. You
expose the ValidateCard session bean created in practice 12 as a Web service.
Perform the following steps to expose the validate(String s) method of the
ValidateCard session bean as a Web service.
1. Expose the ValidateCard session bean as a Web service:
a. Open the workspace practice12oneske.jws . You can use this workspace
if you have successfully completed practice 12-1. Otherwise, use
practice12onesoln.jws.
b. Right-click the project; select New. Choose Web Services from the Business
node of Categories and select Java Web Service from Items.
c. Click OK. You see the Web Service Publishing Wizard. Click Next.
d. Browse to select the ValidateCard remote interface. Click Next.
e. Select the validate(java.lang.String) method and click Next. In the
Web Service Endpoint change the Web Server Port to 8988, because the
embedded OC4J runs on port 8988. JDeveloper picks the port number from here
and generates the WSDL file. The endpoint in the WSDL file has the same port
number. Click Next and then click Finish.
f. Note that the Web service, MyWebService1, and the
Webservices.deploy files are generated.
2. Generate a client to test the Web service with embedded OC4J.
a. Right-click the Web service and select Generate Sample Java Client.
b. The sample client is generated. Check the port number in the String endpoint in
the client application.
c. Edit the client and add the following line to the try block of the main method:
System.out.println(stub.validate(BN349672A));
Note: If you see any SOAP exceptions when you run the client application, then
it is because of port conflicts.
Objectives
20-2
Objectives
In this lesson, you learn how to configure security for your Java 2, Enterprise Edition (J2EE)
applications, because different clients can access your Web applications and EJB
components. You also examine how to edit the deployment descriptor to declaratively
(instead of programmatically) control access to Web applications and EJB components so
that only authorized clients can access the required functionality.
20-3
20-4
20-6
Authorization of a Client
20-8
Authorization of a Client
The security roles that are defined by the application assembler provide the deployer with a
logical and simplified security view of the Web application, or the EJB. The deployer is
responsible for mapping the logical security roles to principals or to groups of principals that
are defined in the target operational environment.
At run time, a client is allowed to access a URL or invoke a business method only if the
principal making the request is authenticated and authorized (by being associated with an
appropriate security role) to access the requested resource. The container provider enforces
the security policies at run time and provides the tools for managing security during
deployment and at run time.
The security view defines the various types of users of the application and their rights to
invoke a URL request or methods in the enterprise bean interfaces.
Note: The security roles define the logical security view of an application. They should not
be confused with the user groups, users, principals, and other concepts that exist in the target
enterprises operational environment.
The security roles and information are configured and mapped in configuration files and
deployment descriptors, as discussed in the following slides.
Oracle10g: Build J2EE Applications 20-8
Configuring Security
20-10
Map logical roles to users and groups in OC4Jspecific deployment descriptor (orion-web.xml
or orion-ejb-jar.xml).
Configuring Security
The configuration of the security environment involves:
Defining users and groups in a configuration file, that is, in the jazn-data.xml (or
principals.xml) file
Defining logical roles in the J2EE application deployment descriptor
Mapping the logical roles to users and groups in the Oracle-specific deployment
descriptor
The other methods of authorization and authentication include the LDAP-based OID and the
use of single sign-on features of the Oracle Application Server 10g architecture. You can use
the JAAS API to build custom providers. The jazn-data.xml file is used in the course
examples and labs because it is the default provider and it is easy to configure.
To allow a client access to the JNDI namespace, the OC4J application.xml file must
be modified by adding a user or group element in a <security-role-mapping>
element. For example, allow read access to the JNDI namespace for the
administrators group:
<namespace-access><read-access><namespace-resource root="">
<security-role-mapping><group name="administrators" />
</security-role-mapping>
</namespace-resource></read-access> ... </namespace-access>
Oracle10g: Build J2EE Applications 20-10
<jazn-realm>
<realm><name>jazn.com</name>
<users>
<user><name>admin</name>
<display-name>OC4J Administrator</display-name>
<description>OC4J Administrator</description>
<credentials>{903}5NwtZOAJa2Ty7Ksbmu3IUOfK9PgK/Kxi
</credentials>
</user>
<user><name>user</name>
<description>The default user</description>
<credentials>{903}/pQcVBQ6+AN+NNF2MzYb/0+gR4lOVwwh
</credentials>
</user> ...
20-11
Note: In this sample XML file, the <member> element whose <type> is role shows
how one role (in this case administrators) can belong to another role, that is, the
users role. This is the implementation of a role-based hierarchical structure.
To run the Admintool, open a Console window and change the directory to the OC4J home
directory, for example, JDEV_HOME\j2ee\home. You can enter the following command
for help: java jar jazn.jar help
The help command does not prompt for a username or a password.
The first example on the slide shows how to add a user to a realm. The first parameter after
the adduser option is the realm name (jazn.com is the default) followed by the
username and password. The password is encrypted in the XML file.
Note: The Enterprise Manager Web interface of Oracle Application Server 10g can also
manage J2EE security.
Oracle10g: Build J2EE Applications 20-13
The result text is: jazn.com. The JAZN Admintool has several command-line options.
Some of the useful options are:
Listing the realms:
java jar jazn.jar -listrealms
Note: This adds the managers role as a member of the users role.
If you intend to execute multiple commands with the JAZN Admintool in one session, then
it is recommended that you invoke the command shell feature of the JAZN Admintool. In
this way, you need to log in only once for the shell session. To start a JAZN Admintool shell
session, use the following command:
java jar jazn.jar shell
RealmLoginModule username: admin
RealmLoginModule password:********
JAZN:> listusers
jazn.com/user
...
JAZN:> adduser jazn.com ora1 oracle
JAZN:> exit
For more information about JAZN Admintool, refer to Oracle Application Server 10g
Containers for Java: Service Guide.
20-15
20-16
<assembly-descriptor>
<security-role>
<description>HR Manager</description>
<role-name>hr_managers</role-name>
</security-role>
<method-permission>
<role-name>hr_managers</role-name>
<method><ejb-name>HrApp</ejb-name>
<method-name>incrementSalary</method-name>
<method-params><method-param>int</method-param>
<method-param>int</method-param></method-params>
</method></method-permission> ...
<assembly-descriptor> ...
20-18
20-19
The impliesAll attribute that is set to true includes all the users with the
hr_managers role that are mapped as managers in the J2EE environment.
To define the default access permissions for all methods in an EJB component, you define
the security role mappings in the <default-method-access> element.
Oracle10g: Build J2EE Applications 20-19
20-20
Client Authentication
20-21
Client Authentication
The authentication of Web clients can be managed by using Oracle Application Server 10g
HTTP Server capabilities, such as basic or digest authentication, HTML form fields, or
Single Sign-On services managed by an LDAP-based service, such as Oracle Internet
Directory (OID).
Alternatively, you can use similar services from within the OC4J container. For example,
you can enable basic authentication for a J2EE Web application by adding the following
<login-config> element details to the Web application deployment descriptor
(web.xml):
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
The container then requests a username and password from the Web browser.
When you access EJBs in a remote container, you must pass valid credentials to this
container.
Stand-alone clients define their credentials in initial context. The credentials can then
be initialized by using the jndi.properties file deployed with the Enterprise
Archive (EAR) file, or the Hashtable.
Servlets or JavaBeans running within the container pass their credentials in the
InitialContext, which is created to look up the remote EJBs.
Oracle10g: Build J2EE Applications 20-21
20-22
20-23
20-24
20-25
20-26
20-27
20-28
20-29
20-30
Note: Explicit method access settings in the J2EE deployment descriptor (ejb-jar.xml)
have precedence over the specified default method access settings.
20-31
20-32
20-33
20-34
20-35
Summary
20-36
20-37
Practice 20-1
In this practice, you are provided with most of the application code. The goal of this practice
is to use J2EE declarative security mechanisms to protect access to different parts of the
application. You use programmatic techniques to limit the information about an employees
salary displayed to the application user (depending on the role of the user).
Note: The application in this practice originates from the practice in lesson 17.
Understanding the Application
Open the practice20.jws workspace in the practice20 directory. There are two
projects:
The secure project, containing the files you will modify
The securesoln project, containing the solutions for this practice
Expand the secure project, and take approximately two minutes to examine the content of
the following files used to configure the application security credentials:
The orion-application.xml file is an OC4J applicationspecific deployment
descriptor that identifies the location of the application-specific user and group data in
the jazn-data.xml file. It also grants read access to the namespace to the staff
role.
The jazn-data.xml file contains all the users and roles for this application. This
file was created using the JAZN Admintool provided with OC4J, where each
username is derived from the EMAIL column of the EMPLOYEES table, and their
passwords are all set to oracle. This file defines two roles:
- The managers role, which is granted to only those employees in the database
who have the following job IDs: AD_PRES, AD_VP, HR_REP, FI_MAN
- The staff role, which is granted to all other employees. The managers role
has been added as a member of the staff role, because all managers are also
staff.
The application provides a default index.html page that is not protected, allowing users
to access a common welcome page. The only hypertext link on the index page leads to the
GetEmployee.jsp page, which must be password protected.
The user should log in using a valid name and the password oracle. The
GetEmployee.jsp uses an entity bean to retrieve information about that employee, and
presents a page that allows users to add new employees or to query employees by
department. When employees are queried, the user is able to update or delete the employee
record.
Your task is to declaratively allow only managers to create and delete employees and update
employee salaries. This is achieved through a combination of using Web and EJB
authorization techniques covered in this lesson.
Practice Steps
1. Deploy the application to observe the default behavior.
a. Compile the secure project, and then right-click EmployeesWeb.deploy
and deploy the application to your OracleAS10g connection.
EmployeesWeb.deploy has a profile dependency on
EmployeesEJB.deploy to ensure that the EJB is deployed as part of the
enterprise application.
Oracle10g: Build J2EE Applications 20-38
Replace the HTML comment line <! Enter code here --> with
output that resembles the following four lines of information, each with a JSP
expression after the word shown:
<b>Principal:</b> <%= %><br>
<b>Staff:</b> <%= %><br>
<b>Manager:</b> <%= %><br>
<b>User :</b> <%= %><br>
b. In the JSP expression for Principal, display the string information about the
java.security.Principal object.
Hint: Use request.getUserPrincipal().
c. In the JSP expression for Staff, display true if the user making the request is a
member of the staff role; otherwise display false.
Hint: Use request.isUserInRole(...).
d. In the JSP expression for Manager, display true if the user making the request
is a member of the managers role; otherwise display false.
Hint: Use request.isUserInRole(...).
e. In the JSP expression for the User information, display the remote username.
Hint: Use request.getRemoteUser().
f. Compile the GetEmployee.jsp file to eliminate syntax errors.
10. Programmatically prevent the current user from seeing another employees salary
when obtaining the result list after finding employees by department ID.
a. Edit GetEmployeeByDept.jsp in the Code Editor.
b. Search for the following JSP code: <td><%= emp.getSalary()
%></td> in the file and modify this line to display the salary as a string if the
current user has the managers role. Otherwise, display the string n/a (not
available).
c. Compile the GetEmployeeByDept.jsp file to eliminate syntax errors.
11. Finally, deploy the EmployeesWeb.deploy application profile to the
OracleAS10g connection. Test the application changes starting with the following
URL: http://localhost/secure.
Hint: Close the browser windows between the staff and managers user login
sessions.
Objectives
21-2
Objectives
Java 2, Enterprise Edition (J2EE) containers provide a transaction service. Enterprise
JavaBeans use Java Transaction API (JTA) 1.0.1 for managing transactions. This lesson
discusses the method for using JTA in OC4J.
What Is a Transaction?
A transaction:
Is a single logical unit of work or a set of tasks
that are executed together
May access one or more shared resources, such
as databases
Must be atomic, consistent, isolated, and durable
(ACID)
21-3
Overview
Transactions manage changes to multiple databases in a single application as a unit of work..
A transaction must be:
Atomic: A transaction must execute completely or not execute at all. For example, in
an account transfer transaction, both debit and credit must be successful as a unit, or
both must fail.
Consistent: This refers to the integrity of the underlying database. In an account
transfer example, the amount of debit to one account must equal the credit to the other
account.
Isolated: The steps during a transaction cannot be affected by or be visible to any
other part of the system until the transaction is complete.
Durable: All data changes that are made during a transaction must be written to some
physical storage before the transaction is successfully completed, so that even if the
system crashes, the changes are not lost.
21-4
21-5
Demarcating Transactions
21-6
Container-Managed Transactions
<session>
<ejb-name>hrApp</ejb-name>
<home>demos.hrAppHome</home> ...
<transaction-type>Container</transaction-type>
<resource-ref>
<res-ref-name>jdbc/hrCoreDS</res-ref-name> ...
</session>
<assembly-descriptor> ...
<container-transaction>
<description>no description</description>
<method>
<ejb-name>HrApp</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>RequiresNew</trans-attribute>
</container-transaction>
</assembly-descriptor> ...
21-7
Container-Managed Transactions
A container-managed transaction is also known as a declarative transaction because you
specify the method of transactional management in the J2EE deployment descriptor.
Specifying Container for the <transaction-type> in the XML deployment
descriptor indicates that the container demarcates the transactions of the bean. That is, the
container manages the transactions by providing begin, commit, and rollback statements.
Before a bean can be deployed, its transaction attributes must be specified in the deployment
descriptor. The transaction attributes can be specified by the bean provider, the application
assembler, or the deployer.
21-8
NotSupported
Required
Supports
RequiresNew
Mandatory
Never
NotSupported: The existing transaction context is not propagated to the bean. This
attribute applies to stateless session bean (SLSB) and MDB.
Required: The bean always runs in a transaction. This attribute applies to all types
of beans.
Supports: The bean runs in a transaction if the client has one. Otherwise, it runs
without a transaction. This attribute applies to SLSB only.
RequiresNew: The bean always needs a new transaction. This attribute applies to all
types of beans except MDB.
Never: The bean is not allowed in a transaction. This attribute applies to SLSB only.
Generally, you do not need to change the bean code for implementing CMT. However, for
some of the transaction attributes above, you need to change the bean class implementation.
For example, for using the RequiresNew transaction attribute, you must code the
statements to begin and end a new transaction in the bean code.
Oracle10g: Build J2EE Applications 21-8
21-9
A client has:
No transaction: The bean does not start one.
A transaction: The bean suspends it. The
transaction resumes when the client gains control.
Client
(bean or servlet)
Threads of
execution
No transactional context
No transactional context
Client
(bean or servlet)
Suspended
Bean
Resumed
Transactional context
21-10
Bean
No transactional context
A client has:
No transaction: The bean starts a new one.
A transaction: The bean uses it.
Client
(bean or servlet)
No transactional context
Client
(bean or servlet)
Transactional context
21-11
Threads of
execution
Bean
Bean
A client has:
No transaction: The bean does not start new one.
A transaction: The bean uses it.
Client
(bean or servlet)
No transactional context
Client
(bean or servlet)
Transactional context
21-12
Threads of
execution
Bean
No transactional context
Threads of
execution
Bean
A client has:
No transaction: The bean starts a new one.
A transaction: It is suspended, the bean starts a
new one and commits it, and then the old one
resumes.
Client
(bean or servlet)
Threads of
execution
No transactional context
Client
(bean or servlet)
Suspended
Bean
Bean
Resumed
Bean transactional context
A client has:
No transaction: The bean requires one. It throws the
javax.transaction.TransactionRequiredException
exception.
A transaction: The bean uses it.
Client
(bean or servlet)
No transactional context
Client
(bean or servlet)
Transactional context
21-14
Threads of
execution
Bean
EXCEPTION THROWN
Threads of
execution
Bean
A client has:
No transaction: The container calls the method in
an unspecified transaction context.
A transaction: The container throws the
java.rmi.RemoteException exception.
Client
(bean or servlet)
Transactional context
21-15
Threads of
execution
Bean
java.rmi.RemoteException
21-16
Container-Managed Transactions
In a CMT bean, the bean cannot, and must not, directly invoke the commit() or
rollback() methods to end the transactions.
Typically, an enterprise bean marks a transaction for rollback to protect data integrity before
throwing an application exception, because an application exception does not automatically
cause the container to roll back the transaction. A CMT bean can invoke the
javax.ejb.EJBContext.setRollbackOnly() method to set the current
transaction to rollback. The bean can use the
javax.ejb.EJBContext.getRollbackOnly() method to detect if it has been
marked for rollback.
21-17
21-18
21-19
abstract
abstract
abstract
abstract
21-20
21-21
21-22
21-23
Client-Demarcated Transactions
Using UserTransaction
For Web applications (or EJB client) demarcation:
Get an InitialContext object
Look up java:comp/UserTransaction, and cast
to javax.transaction.UserTransaction
Context ctx = new InitialContext ();
// Retrieve the UserTransaction object.
// Use its methods for transaction demarcation
UserTransaction ut = (UserTransaction)
ictx.lookup("java:comp/UserTransaction");
ut.begin(); //Start the transaction
//Look up bean & access logic to perform sql
// If everything went well, commit the transaction
ut.commit();
21-24
Session and message-driven EJBs can have beanmanaged transactions if their <transactiontype> element is set to Bean.
21-25
A local transaction:
Is started and coordinated internally by the
resource manager
Has a single-phase commit
A global transaction:
Is controlled by a transaction manager external to
the resources involved
Has a two-phase commit
21-26
Single-Phase Commit
21-27
Single-Phase Commit
Configure the DataSource in data-sources.xml. For a single-phase commit JTA
transaction, use the emulated default data source. Modify this data source url attribute with
your database URL information. You retrieve the data source in your code by using a JNDI
lookup with the JNDI name configured in the ejb-location attribute. Configure a
DataSource for each database that is involved in the transaction.
To enlist a single resource in single-phase commit, you must retrieve a connection to that
database (the configured data source) before you execute any SQL statements against tables
in the database. For these updates to be included in the JTA transaction, you must perform
one of the following tasks in your bean implementation after the transaction has begun.
After the transaction has begun (demarcated), look up the DataSource from the
JNDI namespace. You can perform a JNDI lookup on a DataSource definition (as
defined in data-sources.xml and ejb-jar.xml) or by using the environment
(mapped in orion-ejb-jar.xml). These are discussed later in this lesson.
Retrieve a connection from this DataSource object by using the
getConnection() method.
21-28
Default data-sources.xml
<data-source
class="com.evermind.sql.DriverManagerDataSource"
name="OracleDS"
location="jdbc/OracleCoreDS"
xa-location="jdbc/xa/OracleXADS"
ejb-location="jdbc/OracleDS"
connectiondriver="oracle.jdbc.driver.OracleDriver"
username="scott"
password="tiger"
url="jdbc:oracle:thin:@localhost:5521:oracle"
inactivity-timeout="30"
/>
21-29
Default data-sources.xml
The code in the slide shows the default data source configuration.
The class attribute defines the type of data source that you want to use.
The location, xa-location, and ejb-location attributes are JNDI names
that the data source is bound to in the JNDI namespace, where:
- location identifies a basic data source with no added services.
- xa-location identifies a data source with additional support for pooling and
distributed transactions (XA).
- ejb-location, used by EJBs, adds support for container-managed
transactions in addition to services provided by the xa-location data source.
Note: Always use ejb-location in JNDI lookup requests for a data source for
access to all services. In addition, location and xa-location are now obsolete.
The connection-driver attribute defines the type of connection you expect to be
returned to you from the data source.
The url, username, and password identify the database, its default username,
and password.
The data source in the slide example is extremely fast and efficient, because it does not
require any JTA or XA operations. To use the OC4J default data source file, modify the data
source name, username, password, and connection details with your database information.
Oracle10g: Build J2EE Applications 21-29
21-30
data-sources.xml
<resource-ref-mapping
name="jdbc/HumanResourcesDS"
location="jdbc/hrCoreDS"/>
orion-ejb-jar.xml
<resource-ref>
<res-ref-name>jdbc/HumanResourceDS </res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
ejb-jar.xml
Bean Code
Context ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("jdbc/HumanResourceDS");
21-32
21-33
Client
Application
(Bean)
4
8
OC4J
Transaction
manager
(Oracle10g DB)
21-34
Resource
adapter
6. The container enlists the resource to the transaction manager by using the statement
Transaction.enlistResource(xaRes);
7. The transaction manager invokes the XAResource.start()method to associate
the current transaction to the resource.
8. The container invokes the getConnection() method and returns the
Connection object reference to the bean.
9. The bean performs operations on the connection by using the JDBC statements such as
conn.createStatement();. After the operations are performed, the bean closes
the connection by using the statement conn.close();.
The resource adapter notifies the container that the connection is closed, and then the
container enlists the resource. The transaction manager then invokes
XAResource.end() to dissociate the transaction from the XAResource. The container
asks the transaction manager to commit the transaction by using the statement
TransactionManager.commit(). The transaction manager invokes
XAResource.prepare() to inform the resource manager to prepare the transaction
work for commit. The transaction manager then invokes the statement
XAResource.commit() to commit the transaction.
The transaction is now complete and the client has the control.
21-36
Summary
21-38
21-39
Practice 21-1
The goal of this practice is to get some experience working with container-managed
transactional attributes. The application you are using here is identical to the one that you
used in the previous lesson, without all the security constraints. You still require a valid
login, but all users have access to all functions, because security is not the objective of this
lab.
1. Open practice21.jws in the practice21 directory, and test the application
with default transaction attributes:
a. Deploy the application by using ManageTxApp.deploy file
b. Start your browser and enter the URL http://localhost/managetx to
run the application. Log in as any user, for example jchen, ngreenbe, or
ldehaan, with the password oracle.
c. Create a new employee in department 10. Use an employee ID of 900, enter your
first name and last name in the first and last name fields, respectively, and enter a
job type of IT_PROG. Enter values for all fields.
d. Return to the Welcome employee page, and find all employees in department 10.
e. Click the Update link and make a change to the first name and last name, and
delete the last letter from the job type. This job type is invalid and generates an
exception for the operation of changing the job type. But what happens to the
changes to the first name and last name?
2. Edit the EJB and mark all methods with a transaction attribute of Required.
a. Right-click ejb-jar.xml and select Properties. Click Container Transactions
and click the Add button to add a transaction entry. In the Create Container
Transaction Entry window select the Required transaction attribute. Click Add
Method, select Employees in EJB Name and click * in the methods area. Click
OK. Click OK again to close the window.
b. Select Preview XML to observe the <assembly-descriptor> element
inside <container-transaction>. Click OK to close the window.
c. Redeploy the application.
d. Run the application, search for employees in department 10. Attempt to update
your record again. What happens this time?
3. Edit the EJB and mark all methods with a transaction attribute of NotSupported.
a. Right-click ejb-jar.xml and select Properties. Select Container Transactions
and click the Transaction Attribute field value in the existing entry. Pick the
NotSupported entry from the drop-down list.
b. Select Preview XML to observe the <assembly-descriptor> element
inside <container-transaction>. Click OK to close the window.
c. Redeploy the application.
d. Run the application, search for employees in department 10. Attempt to update
your record again. What happens this time?
4. Edit the EJB module and change the existing transaction attribute entry to mark only
the setXXX() methods with an attribute value of Mandatory. Select Preview XML
and note the changes. Click OK to close the window. Hint: Select all the setXXX()
methods.
a. Redeploy the application.
Oracle10g: Build J2EE Applications 21-40
Appendix B
Schema Descriptions
NUMBER(6)
VARCHAR2(20)
VARCHAR2(20)
CUST_ADDRESS_TYP
PHONE_LIST_TYP
VARCHAR2(3)
VARCHAR2(30)
NUMBER(9,2)
VARCHAR2(30)
NUMBER(6)
MDSYS.SDO_GEOMETRY
VARCHAR2(10)
ORDERS
ORDER_ID
ORDER_DATE
ORDER_MODE
CUSTOMER_ID
ORDER_STATUS
ORDER_TOTAL
SALES_REP_ID
PROMOTION_ID
To Product
Media
Schema
PRODUCT_INFORMATION
NUMBER(12)
TIMESTAMP(6)
VARCHAR2(8)
NUMBER(6)
NUMBER(2)
NUMBER(8,2)
NUMBER(6)
NUMBER(6)
NUMBER(6)
PRODUCT_ID
VARCHAR2(50)
PRODUCT_NAME
PRODUCT_DESCRIPTION VARCHAR2(2000)
NUMBER(2)
CATEGORY_ID
NUMBER(1)
WEIGHT_CLASS
INTERVAL
WARRANTY_PERIOD
NUMBER(6)
SUPPLIER_ID
VARCHAR2(20)
PRODUCT_STATUS
NUMBER(8,2)
LIST_PRICE
NUMBER(8,2)
MIN_PRICE
VARCHAR2(50)
CATALOG_URL
ORDER_ITEMS
ORDER_ID
LINE_ITEM_ID
PRODUCT_ID
UNIT_PRICE
QUANTITY
DISCOUNT_UNIT_PRICE
NUMBER(12)
NUMBER(3)
NUMBER(6)
NUMBER(8,2)
NUMBER(8)
NUMBER(8,2)
NUMBER(6)
DATE
DATE
VARCHAR2(10)
NUMBER(4)
JOBS
JOB_ID
JOB_TITLE
MIN_SALARY
MAX_SALARY
VARCHAR2(10)
VARCHAR2(35)
NUMBER(6)
NUMBER(6)
EMPLOYEES
DEPARTMENTS
DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
LOCATION_ID
NUMBER(4)
VARCHAR2(30)
NUMBER(6)
NUMBER(4)
EMPLOYEE_ID
FIRST_NAME
LAST_NAME
EMAIL
PHONE_NUMBER
HIRE_DATE
JOB_ID
SALARY
COMMISSION_PCT
MANAGER_ID
DEPARTMENT_ID
NUMBER(6)
VARCHAR2(20)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(20)
DATE
VARCHAR2(10)
NUMBER(8,2)
NUMBER(2,2)
NUMBER(6)
NUMBER(4)
COUNTRIES
LOCATIONS
LOCATION_ID
STREET_ADDRESS
POSTAL_CODE
CITY
STATE_PROVINCE
COUNTRY_ID
NUMBER(4)
VARCHAR2(40)
VARCHAR2(12)
VARCHAR2(30)
VARCHAR2(25)
CHAR(2)
COUNTRY_ID
COUNTRY_NAME
REGION_ID
CHAR(2)
VARCHAR2(40)
NUMBER
REGIONS
REGION_ID
REGION_NAME
NUMBER
VARCHAR2(25)
D-2
D-3
D-4
D-6
User-Defined Exception:
JobSalException
public class JobSalException extends Exception
{
public JobSalException()
{ super(); }
public JobSalException(Exception e)
{ super(e.toString()); }
public JobSalException(String s)
{ super(s); }
}
D-7
D-8
D-9
2 ejbCreate()
create()
Home
object
EJB Object
Client
primary key
Entity Bean
instance
EJB
object
Table in database
D-10
D-11
D-12
D-13
D-14
D-15
D-16
D-17
D-18
(double salLimit)
{
Vector v = null;
try {
v = new Vector();
conn = getConnection();
ps = conn.prepareStatement ("SELECT job_id
FROM jobs WHERE max_salary > ? ");
ps.setDouble(1,salLimit);
rset = ps.executeQuery();
while (rset.next()) {
String id = rset.getString("job_id");
v.addElement(new JobsBMPPK(id));
}
} catch (Exception e) {...}
finally { closeConnection(); }
return v;
}
}
D-19
Deployment Descriptor
...
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>JobsBMP</ejb-name>
<home> demos.JobsBMPHome</home>
<remote>demos.JobsBMP</remote>
<ejb-class>demos.JobsBMPBean</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>demos.JobsBMPPK
</prim-key-class>
<reentrant>False</reentrant>
<resource-ref>
<res-ref-name>jdbc/hrDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Application</res-auth>
</resource-ref> </entity> ...
D-20
Deployment Descriptor
The slide shows the <entity> tag of the deployment descriptor for the JobsBMP
example. The <entity> tag indicates that the deployment descriptor is for an entity bean.
The logical name for the EJB is given as JobsBMP in the <ejb-name> element. The
remote home and remote interface names are given along with their packages names. If the
bean has local interfaces (can be in addition to the remote interfaces), those references
should also be added to the <entity> tag. The value Bean for the <persistencetype> element indicates that the entity bean is a bean-managed persistence bean. The
<prim-key-class> element shows that JobsBMPPK is the primary key class. The
<reentrant> flag is set to false because the JobsBMP bean does not call itself.
The <resource-ref> element indicates that the SQL data source hrDS is authenticated
by the container. This data source specified in the <res-ref-name> element is generally
the value of an <ejb-location> element in the data-sources.xml file. The value
for the <res-auth> element can be either container or Application. This element
specifies whether authorization to the resource must be performed by the container or
programmatically through the application.
Deployment Descriptor
...
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>JobsBMP</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
D-21
D-22
D-24
D-25
D-26
OC4J
Resource
Adapter
J2EE Application
Component
D-27
System
Contracts
(Quality of
Service)
Enterprise
Information
System
D-28
D-29
Deploying Stand-Alone
Resource Adapters
When deploying stand-alone adapters:
Give the resource adapter a unique name, to
simplify future operations such as removal of a
deployed resource adapter
Deploy in one of the following two ways:
Using the Admin command-line tool (admin.jar)
Manually through directory manipulation, by
expanding the .rar file contents into a userspecified directory name <connector-name> below
the ORACLEAS_HOME/j2ee/home/<connector
directory> (which defaults to
ORACLEAS_HOME/j2ee/home/connectors)
D-30
OC4J decompresses the .rar file into a <connector-directory>/<connectorname> directory below the ORACLEAS_HOME/j2ee/home directory for the OC4J
instance. If the directory does not exist, it will be created. A new attribute connectordirectory should be added to the <application-server> element in the
application-server.xml file to specify the path used for the storage of stand-alone
resource adapters. The default directory is ../connectors relative to the OC4J config
directory. In the above example, OC4J decompresses myconnector.rar into a directory
called ORACLEAS_HOME/j2ee/home/connectors/myname. The deployment tool
must also verify the transaction levels, and whether the authentication specified in the
deployment descriptor of the resource adapter (ra.xml) is supported by OC4J.
Oracle10g: Build J2EE Applications D-30
D-31
ConnectionFactory
Connection
Interaction
RecordFactory
Record