1. Trang chủ
  2. » Công Nghệ Thông Tin

The j2eetm tutorial - phần 9 ppt

35 226 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề J2EE™ Connector Technology
Tác giả Dale Green, Beth Stearns
Trường học Not Available
Chuyên ngành Not Available
Thể loại Not Available
Năm xuất bản 2025
Thành phố Not Available
Định dạng
Số trang 35
Dung lượng 1,06 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

About Resource Adapters 284Resource Adapter Contracts 284Administering Resource Adapters 285The Black Box Resource Adapters 287Transaction Levels 287 Properties 288Configuring JDBC™ Driv

Trang 1

J2EE™Connector

Technology

by Dale Green and Beth Stearns

THEother chapters in this book are intended for business application ers, but this chapter is for advanced users such as system integrators and toolsdevelopers The examples in this chapter demonstrate the J2EE™ ConnectorTechnology by accessing relational databases However, this technology is not asubstitute for the JDBC API Business application developers should continue touse the JDBC™ API to access relational databases

develop-The J2EE Connector Technology enables J2EE components such as enterprisebeans to interact with Enterprise Information Systems (EIS) EIS softwareincludes various types of systems: Enterprise Resource Planning (ERP), main-frame transaction processing, non-relational database, among others The J2EEConnector Technology simplifies the integration of diverse EIS systems EachEIS requires just one implementation of the J2EE Connector Technology

Because an implementation adheres to the J2EE Connector Specification, it is

portable across all compliant J2EE servers

About Resource Adapters 284Resource Adapter Contracts 284Administering Resource Adapters 285The Black Box Resource Adapters 287Transaction Levels 287

Properties 288Configuring JDBC™ Drivers 289

Trang 2

Resource Adapter Tutorial 290Setting Up 290

Deploying the Resource Adapter 290Testing the Resource Adapter 291Common Client Interface (CCI) 293Overview of the CCI 293Programming with the CCI 295Writing a CCI Client 304CCI Tutorial 304

About Resource Adapters

A resource adapter is a J2EE component that implements the J2EE ConnectorTechnology for a specific EIS It is through the resource adapter that a J2EEapplication communicates with an EIS (See Figure 20.)

Stored in a RAR (Resource adapter ARchive) file, a resource adapter may bedeployed on any J2EE server, much like the EAR file of a J2EE application ARAR file may be contained in a EAR file or it may exist as a separate file

A resource adapter is analagous to a JDBC driver Both provide a standard APIthrough which an application can access a resource that is outside of the J2EEserver For a resource adapter, the outside resource is an EIS; for a JDBC driver,

it is a DBMS Resource adapters and JDBC drivers are rarely created by tion developers In most cases, both types of software are built by vendors whosell products such as tools, servers, or integration software

applica-Resource Adapter Contracts

Figure 20 shows the two types of contracts implemented by a resource adapter.The application contract defines the API through which a J2EE component such

as an enterprise bean accesses the EIS This API is the only view that the nent has of the EIS The resource adapter itself and its system contracts are trans-parent to the J2EE component

compo-The system contracts link the resource adapter to important tion, transaction, and security—that are managed by the J2EE server

services—connec-The connection management contract supports connection pooling, a techniquethat enhances application performance and scalability Connection pooling istransparent to the application, which simply obtains a connection to the EIS

Trang 3

A BOUT R ESOURCE A DAPTERS 283

Because of the transaction management contract, calls to the EIS may beenclosed in a XA transactions XA transactions are global—they may containcalls to multiple EISs, databases, and enterprise bean business methods

Although often appropriate, XA transactions are not mandatory Instead, anapplication may use local transactions, which are managed by the individualEIS, or it may use no transactions at all

To protect the information in an EIS, the security management contract providesthese mechanisms: authentication, authorization, and secure communicationbetween the J2EE server and the EIS

Figure 20 Accessing an EIS Through a Resource Adapter

Administering Resource Adapters

Installing a resource adapter is a two-step process:

1 Deploy the RAR file containing the resource adapter onto a server

J2EE Server

Enterprise Bean

EIS Resource

Adapter

Web Component

Transaction Connection Security

Managers:

System Contracts

Application Contract

Application Contract

Trang 4

The following command, for example, deploys a sample black box resourceadapter onto the local host (For Windows, in the following commands omitthe backslash character, change$J2EE_HOME to%J2EE_HOME%, and enter theentire command on a single line.)

deploytool -deployConnector \

$J2EE_HOME/lib/connector/cciblackbox-tx.rar \ localhost

2 Add a connection factory for the resource adapter

Suppose that you wanted to add a connection factory for the resourceadapter in thecciblackbox-tx.rarfile The JNDI name of the connectionfactory will beeis/MyCciBlackBoxTx To override the default value of theproperty named ConnnectionURL, you specify the URL of a database (Aproperty is a name-value pair used to configure a connection factory.) To addthe connection factory, you might enter the followingj2eeadmin command:j2eeadmin -addConnectorFactory \

eis/MyCciBlackBoxTx \ cciblackbox-tx.rar \ -props \

ConnectionURL=jdbc:oracle:thin:@myhost:1521:ACCTDBFor the full syntax of the deploytool and j2eeadmin commands, seeJ2EE™SDK Tools (page 309) These commands also list and remove resourceadapters and connection factories

To list the resource adapters that have been deployed:

deploytool -listConnectors localhost

To list the connection factories that have been added:

j2eeadmin -listConnectorFactory

To uninstall the resource adapter deployed in step 1:

deploytool -undeployConnector \

$J2EE_HOME/lib/connector/cciblackbox-tx.rar \ localhost

To remove the connection factory added in step 2:

j2eeadmin -removeConnectorFactory eis/MyCciBlackBoxTx

Trang 5

T HE B LACK B OX R ESOURCE A DAPTERS 285

The Black Box Resource Adapters

The J2EE SDK includes several black box resource adapters for performing to-end and compatibility testing The underlying EIS of these adapters is a rela-tional DBMS The client API is the JDBC 2.0 API and the javax.sql.Data- Source interface Underneath, the black box adapters use JDBC drivers tocommunicate with relational databases For more information, see ConfiguringJDBC™ Drivers (page 287)

end-Note: Although the black box adapters use JDBC, resource adapters are not meant

to replace JDBC for accessing relational databases The black box adapters are fortesting purposes only Because they use JDBC, they can be plugged into existingtests that also use JDBC

Transaction Levels

The black box resource adapters reside in the $J2EE_HOME/lib/connector(Unix) or %J2EE_HOME%\lib\connector (Windows) subdirectory The follow-ing table lists the blackbox RAR files and the different transaction levels thatthey support:

For theXA_TRANSACTIONlevel, the underlying JDBC driver must support the XArequirements as defined by the JDBC 2.0 API

Table 33 Black Box Transaction Levels

Trang 6

A resource adapter may contain properties, name-value pairs containing mation specific to the resource adapter and its underlying EIS These propertiesare defined in the deployment descriptor of each blackbox RAR file Because theEIS of a blackbox adapter is a relational database, the properties contain infor-mation required for connecting to a database The following table lists the prop-erties of the black box adapter files

infor-The next table shows the default values for the black box properties

To override a default property value, you set the value when adding a connectionfactory with thej2eeadmincommand See the section, Administering ResourceAdapters (page 283)

Table 34 Black Box Properties

blackbox-notx.rar ConnectionURL URL of database

blackbox-tx.rar ConnectionURL URL of database

blackbox-xa.rar XADataSourceName JNDI name of

XADataSource

cciblackbox-tx.rar ConnectionURL URL of database

cciblackbox-xa.rar XADataSourceName JNDI name of

XADataSource

Table 35 Default Values for Black Box Properties

Property Name Description

ConnectionURL jdbc:cloudscape:rmi:CloudscapeDB;create=true XADataSourceName jdbc/XACloudscape_xa

Trang 7

T HE B LACK B OX R ESOURCE A DAPTERS 287

Configuring JDBC™ Drivers

If you are running the black box adapters against a Cloudscape database, youmay skip this section If you are using a database other than Cloudscape, youshould perform the steps that follow

The Non-XA Black Box Adapters

1 Set the JDBC driver class Use the j2eeadmin tool with the cDriver option and specify the driver class name The syntax for thisoption is:

-addJdb-j2eeadmin -addJdbcDriver <class name>

2 Edit the bin/userconfig.sh (UNIX) or bin\userconfig.bat dows) file, setting the J2EE_CLASSPTH variable to the location of theJDBC driver classes

(Win-3 Restart the J2EE server

The XA Black Box Adapters

1 Set theXADatasourceproperty With thej2eeadmintool and the bcXADatasource option, specify the JNDI name and class name for theXADatasourceproperty Optionally, you may specify the XA user nameand password and you may override the default property value The syntaxfollows:

addJd-j2eeadmin -addJdbcXADatasource <jndi name> <class name>

[<xa user name> <xa password>]

Trang 8

Resource Adapter Tutorial

This tutorial shows you how to deploy the black box resource adapter stored inthe blackbox-tx.rar file To test the resource adapter, you will modify theexamples/src/ejb/account/AccountEJB.java file so that it accesses theCloudscape database through the resource adapter TheAccountEJB.javafile isalso used in another example For more information, see Tips for Running theAccountEJB Example (page 94)

3 Follow the instructions in the section, Setting Up the Database (page 94)

Deploying the Resource Adapter

1 Deploy a black box resource adapter that is packaged in the tx.rar file

blackbox-UNIX:

deploytool -deployConnector \

$J2EE_HOME/lib/connector/blackbox-tx.rar localhostWindows:

(Enter the following command on a single line.)deploytool -deployConnector

Trang 9

R ESOURCE A DAPTER T UTORIAL 289

Windows:

(Enter the following command on a single line.)j2eeadmin -addConnectorFactory

eis/MyBlackBoxTx blackbox-tx.rar

3 Verify that the resource adapter has been deployed

deploytool -listConnectors localhostThedeploytool displays these lines:

Installed connector(s):

Connector Name: blackbox-tx.rar Installed connection factories:

Connection Factory JNDI Name: eis/MyBlackBoxTx

Testing the Resource Adapter

1 If you are new to the J2EE SDK, you may want to review the instructions

in Getting Started (page 43)

2 Locate the AccountEJB.java source code, which resides in the ples/src/ejb/account directory

exam-3 Edit theAccountEJB.javasource code, changing the value assigned to thedbName variable as follows:

private String dbName = “java:comp/env/MyEIS”;

4 Compile the source code in theaccount directory:

a Go toexamples/src.

b Typeant account

5 Run the New Enterprise Bean Wizard of thedeploytoolby selecting

File-> New Enterprise Bean Although the wizard displays many dialog boxes,for this example only the following dialog boxes require input

6 General Dialog Box

c Select the Entity radio button

d In the Enterprise Bean Name field, enterAccountBean

Trang 10

7 Entity Settings Dialog Box

a Select the radio button for bean-managed persistence

8 Resource References Dialog Box:

a Click Add

b Enter the values specified in the following table

Theeis/MyBlackBoxTx JNDI name matches the name of the connectionfactory that you added in step 2 of Deploying the ResourceAdapter (page 288) The MyEIS value of the Coded Name field corre-sponds to this line in theAccountEJB.java source code:

private String dbName = “java:comp/env/MyEIS”;

Although it is included in the source code, thejava:comp/env/text is implicit in the Coded Name field of the Resource References dialogbox

subcon-9 Transaction Management Dialog Box:

a For the business methods, in the Transaction Type column selectRequired The business methods are debit, credit, getFirstName,getLastName, andgetBalance

10.Exit the wizard by clicking Finish

11.Create a J2EE application client

a Select New->Application Client

b Name the clientAccountClient

c Add theejb/SimpleAccount enterprise bean reference

Table 36 Resource References Values

Trang 11

C OMMON C LIENT I NTERFACE (CCI) 291

12.Select Tools->Deploy Application

a In the Introduction dialog box, select Return Client Jar

b In the JNDI Names dialog box, verify that the JNDI names in the lowing table have been specified

fol-13.To run the application, follow the directions in Running the J2EEApplication (page 96)

Common Client Interface (CCI)

This section describes how components use the Connector architecture CommonClient Interface (CCI) API and a resource adapter to access data from an EIS

Overview of the CCI

Defined by the J2EE Connector Specification, the CCI defines a set of interfacesand classes whose methods allow a client to perform typical data access opera-

Table 37 JNDI Names

Trang 12

tions Our exampleCoffeeEJBsession bean includes methods that illustrate how

to use the CCI, in particular, the following CCI interfaces and classes:

• ConnectionFactory: Provides an application component with a tion instance to an EIS

Connec-• Connection- Represents the connection to the underlying EIS

• ConnectionSpec: Provides a means for an application component to passconnection request-specific properties to the ConnectionFactory whenmaking a connection request

• Interaction: Provides a means for an application component to executeEIS functions, such as database stored procedures

• InteractionSpec: Holds properties pertaining to an application nent’s Interaction with an EIS

compo-• Record: The superclass for the different kinds of record instances Recordinstances may be MappedRecord, IndexedRecord, or ResultSetinstances, which all inherit from the Recordinterface

• RecordFactory: Provides an application component with a Recordinstance

• IndexedRecord: Represents an ordered collection of Record instancesbased on thejava.util.List interface

A client or application component that uses the CCI to interact with an ing EIS does so in a prescribed manner The component must establish a connec-tion to the EIS’s resource manager, and it does so using theConnectionFactory.TheConnectionobject represents the actual connection to the EIS and it is usedfor subsequent interactions with the EIS

underly-The component performs its interactions with the EIS, such as accessing datafrom a specific table, using anInteractionobject The application componentdefines the Interaction object using an InteractionSpec object When theapplication component reads data from the EIS (such as from database tables) orwrites to those tables, it does so using a particular type ofRecordinstance, either

a MappedRecord, IndexedRecord, orResultSet instance Just as the tionFactory creates Connection instances, a RecordFactory creates Recordinstances

Connec-Our example shows how a session bean uses a resource adapter to add and readrecords in a relational database The example shows how to invoke stored proce-dures, which are business logic functions stored in a database and specific to anenterprise’s operation Stored procedures consist of SQL code to perform opera-tions related to the business needs of an organization They are kept in the data-

Trang 13

C OMMON C LIENT I NTERFACE (CCI) 293

base and can be invoked when needed, just as you might invoke a Java™

method In addition to showing how to use the CCI to invoke stored procedures,we’ll also explain how to pass parameters to stored procedures and how to mapthe parameter data types from SQL to those of the Java programming language

Programming with the CCI

The code for the following example is in the examples/src/connector/ccidirectory

To illustrate how to use a CCI resource adapter, we’ve written a session bean and

a client of that bean These pieces of code illustrate how clients invoke the ent CCI methods that resource adapters built on CCI might make available Ourexample uses the two sample CCI-specific resource adapters:

differ-cciblackbox_tx.rar and cciblackbox_xa.rar.The Coffee session bean is much like any other session bean It has a homeinterface (CoffeeHome), a remote interface (Coffee), and an implementationclass (CoffeeEJB) To keep things simple, we’ve called the clientCoffeeCli- ent

Let’s start with the session bean interfaces and classes The home interface, feeHome, is like any other session bean home interface It extendsEJBHomeanddefines acreate method to return a reference to theCoffee remote interface

Cof-TheCoffeeremote interface defines the bean’s two methods that may be called

by a client

public void insertCoffee(String name, int quantity) throws RemoteException;

public int getCoffeeCount() throws RemoteException;

Now let’s examine theCoffeeEJBsession bean implementation class to see how

it uses the CCI

To begin with, notice that CoffeeEJB imports the javax.resourceCCI faces and classes, along with the javax.resource.ResourceException, andthe samplecciblackbox classes

Trang 14

Prior to obtaining a database connection, the session bean does some set up work

in itssetSessionContext method (See the following code example.) cally, the setSessionContext method sets the user and password values, andinstantiates aConnectionFactory These values and objects remain available tothe other session bean methods

Specifi-(In this and subsequent code examples, the numbers in the left margin spond to the explanation that follows the code.)

public void setSessionContext(SessionContext sc) { try {

this.sc = sc;

1 Context ic = new InitialContext();

2 user = (String) ic.lookup(“java:comp/env/user”); password = (String) ic.lookup

(“java:comp/env/password”);

3 cf = (ConnectionFactory) ic.lookup (“java:comp/env/CCIEIS”);

} catch (NamingException ex) { ex.printStackTrace();

} }

1 Establish a JNDIInitialContext

2 Use the JNDIInitialContext.lookupmethod to find the user and word values

pass-3 Use the lookup method to locate the ConnectionFactory for the CCIblack box resource adapter and obtain a reference to it

CoffeeEJB uses its private method getCCIConnection method to establish aconnection to the underlying resource manager or database A client of theCof- fee session bean cannot invoke this method directly Rather, the session beanuses this method internally to establish a connection to the database The follow-ing code uses the CCI to establish a database connection

private Connection getCCIConnection() { Connection con = null;

try {

1 ConnectionSpec spec = new CciConnectionSpec(user, password);

2 con = cf.getConnection(spec);

} catch (ResourceException ex) {

Trang 15

C OMMON C LIENT I NTERFACE (CCI) 295

ex.printStackTrace();

} return con;

}

1 Instantiate a newCciConnectionSpecobject with the user and passwordvalues obtained by the setSessionContext method The CciConnec- tionSpec class is the implementation of theConnectionSpec interface

2 Call theConnectionFactory.getConnectionmethod to obtain a tion to the database (The reference to the ConnectionFactory wasobtained in the setSessionContext method.) Use the CciConnection- Spec object to pass the required properties to the ConnectionFactory.ThegetConnection method returns aConnection object

connec-The CoffeeEJBbean also includes a private method,closeCCIConnection, toclose a connection The method invokes theConnectionobject’sclosemethodfrom within a try/catch block Like thegetCCIConnectionmethod, this is aprivate method intended to be called from within the session bean

private void closeCCIConnection(Connection con) { try {

con.close();

} catch (ResourceException ex) { ex.printStackTrace();

} }

Database Stored Procedures

The sample CCI black box adapters call database stored procedures It is tant to understand stored procedures before delving into how to read or writedata using the sample CCI black box adapters The methods of these sample CCIadapters do not actually read data from a database or update database data

impor-Instead, these sample CCI adapters enable you to invoke database stored dures, and it is the stored procedures that actually read or write to the database

proce-A stored procedure is a business logic method or function that is stored in a base and is specific for the enterprise’s business Typically, stored proceduresconsist of SQL code, though in certain cases (such as with Cloudscape) they mayconsist of code written in the Java™ programming language Stored proceduresperform operations related to the business needs of an organization They arekept in the database and applications can invoke them when needed

Trang 16

data-Stored procedures are typically SQL statements Our example calls two storedprocedures: COUNTCOFFEE and INSERTCOFFEE The COUNTCOFFEE proceduremerely counts the number of coffee records in theCoffee table, as follows:SELECT COUNT(*) FROM COFFEE

TheINSERTCOFFFEEprocedure adds a record with two values, passed to the cedure as parameters, to the sameCoffee table, as follows:

pro-INSERT INTO COFFEE VALUES (?,?)

Mapping to Stored Procedure Parameters

When you invoke a stored procedure from your application component you mayhave to pass argument values to the procedure For example, when you invoketheINSERTCOFFEEprocedure, you pass it two values for theCoffeerecord ele-ments Likewise, you must be prepared to receive values that a stored procedurereturns

The stored procedure, in turn, passes its set of parameters to the database agement system (DBMS) to carry out its operation and may receive values backfrom the DBMS Database stored procedures specify, for each of their parame-ters, the SQL type of the parameter value and the mode of the parameter Modecan be input (IN), output (OUT), or both input and output (INOUT) An inputparameter only passes data in to the DBMS while an output parameter onlyreceives data back from the DBMS AINOUTparameter accepts both input andoutput data

man-When you use the CCIexecutemethod to invoke a database stored procedureyou also create an instance of anInputRecord,provided that you’re passing aparameter to the stored procedure and the stored procedure you’re executingreturns data (possibly anOutputRecordinstance) TheInputRecord andOut- putRecord are instances of the supported Record types: IndexedRecord,MappedRecord, orResultSet In our example, we instantiate anInputRecordand anOutputRecord that are bothIndexedRecord instances

Note: The CCI black box adapters only supportIndexedRecord types

TheInputRecordmaps the INand INOUTparameters for the stored procedure,while theOutputRecordmaps theOUT andINOUTparameters Each element of

an input or output record corresponds to a stored procedure parameter That is,there is an entry in theInputRecord for eachINandINOUTparameter declared

Trang 17

C OMMON C LIENT I NTERFACE (CCI) 297

in the stored procedure Not only does theInputRecord have the same number

of elements as the procedure’s input parameters, they are declared in the sameorder as in the procedure’s parameter list The same holds true for the Outpu- tRecord, though its list of elements matches only theOUTandINOUTparameters

For example, suppose you have a stored procedureXthat declares three ters The first parameter is anINparameter, the second is anOUTparameter, andthe third is anINOUTparameter The following figure shows how the elements of

parame-anInputRecord and anOutputRecord map to this stored procedure

Figure 21 Mapping Stored Procedure Parameters to CCI Record Elements

When you use the CCI black box adapter, you designate the parameter type andmode in the same way, though the underlying Oracle or Cloudscape DBMSdeclare the mode differently Oracle designates the parameter’s mode in thestored procedure declaration, along with the parameter’s type declaration Forexample, an OracleINSERTCOFFEEprocedure declares its twoINparameters asfollows:

procedure INSERTCOFFEE (name IN VARCHAR2, qty IN INTEGER)

An OracleCOUNTCOFFEEprocedure declares its parameterNas anOUTparameter:

procedure COUNTCOFFEE (N OUT INTEGER)Cloudscape, which declares stored procedures using standard a Java method sig-nature, indicates anINparameter using a single value and anINOUTparameter as

an array The method’s return value is the OUT parameter For example,

Ngày đăng: 13/08/2014, 08:21

TỪ KHÓA LIÊN QUAN