REDHAT APPLICATION SERVER User Manual

Page 1
Red Hat Application Server
JOnAS User Guide
Page 2
Red Hat Application Server: JOnAS User Guide
Copyright © 1999-2004 by ObjectWeb Consortium
ObjectWeb Consortium INRIA - ZIRST, 655 avenue de l’Europe Montbonnot 38334 SAINT-ISMIER Cedex FRANCE
Additional information copyright © Red Hat, Inc., 2003-2004.
1801 Varsity Drive Raleigh NC 27606-2072 USA Phone: +1 919 754 3700 Phone: 888 733 4281
Fax: +1 919 754 3701 PO Box 13588 Research Triangle Park NC 27709 USA
Manual identifier:
PDF: rhel-jonas-EN-3-PDF-RHI (2003-09-24T01:08)
HTML: rhel-jonas-EN-3-HTML-RHI (2003-09-24T01:08)
Red Hat is a registered trademarkand the Red Hat Shadow Man logo, RPM, and theRPM logo are trademarks of Red Hat, Inc. JOnAS is copyright © ObjectWeb Consortium. The JOnAS logo is copyright© Bruno Bellamy. Tomcat is copyright © The Apache Software Foundation (ASF). IntelTM, PentiumTM, ItaniumTM, and CeleronTMare registered trademarks of Intel Corporation. EJBTM, J2EETM, JCATM, JCEETM, JDBCTM, JDOTM, JMSTM, RMITM, and SunTM, and Sun Microsystems® are registered trademarks of Sun Microsystems,Inc. Linux is a registered trademark of Linus Torvalds. All other trademarks and copyrights referredto are the property of their respectiveowners. The GPG fingerprint of the security@redhat.comkey is: CA 20 86 86 2B D6 9D FC 65 F6 EC C4 21 91 80 CD DB 42 A6 0E
Page 3
Table of Contents
I. Introductory JOnAS Documentation ..........................................................................................vii
1. Java Open Application Server (JOnAS): a J2EE Platform ...................................................1
1.1. Introduction to Red Hat Application Server .......................................................... 1
1.2. JOnAS Features ..................................................................................................... 2
1.3. JOnAS Architecture............................................................................................... 4
1.4. JOnAS Development and Deployment Environment ..........................................10
1.5. Clustering and Performance................................................................................. 11
1.6. Future Development............................................................................................. 13
2. Getting Started with JOnAS................................................................................................ 15
2.1. Running the First EJB Application ......................................................................15
2.2. More Complex Examples .................................................................................... 16
3. JOnAS Configuration..........................................................................................................21
3.1. JOnAS Configuration Rules................................................................................. 21
3.2. Configuring the JOnAS Environment ..................................................................22
3.3. Configuring the Communication Protocol and JNDI........................................... 23
3.4. Configuring Logging System (monolog) ............................................................. 24
3.5. Configuring JOnAS Services ...............................................................................26
3.6. Configuring the DB Service (hsql) ......................................................................44
3.7. Configuring JMS Resource Adapters...................................................................44
4. Configuring JDBC DataSources .........................................................................................51
4.1. Configuring DataSources .....................................................................................51
4.2. CMP2.0/JORM ....................................................................................................52
4.3. ConnectionManager Configuration......................................................................53
4.4. Tracing SQL Requests Through P6Spy ...............................................................53
5. JOnAS Class Loader Hierarchy .......................................................................................... 55
5.1. Understanding the Class Loader Hierarchy .........................................................55
5.2. Commons Class Loader .......................................................................................55
5.3. Application Class Loader..................................................................................... 55
5.4. Tools Class Loader............................................................................................... 55
5.5. Tomcat Class Loader............................................................................................ 56
5.6. JOnAS Class Loaders ..........................................................................................56
5.7. JOnAS Class Loader Hierarchy ........................................................................... 56
6. JOnAS Command Reference .............................................................................................. 59
6.1. jonas ..................................................................................................................... 59
6.2. jclient.................................................................................................................... 62
6.3. newbean ...............................................................................................................62
6.4. registry .................................................................................................................65
6.5. GenIC...................................................................................................................65
6.6. JmsServer............................................................................................................. 67
6.7. RAConfig .............................................................................................................68
II. Enterprise Beans Programmer’s Guide.....................................................................................71
7. Developing Session Beans ..................................................................................................73
7.1. Introduction to Session Beans..............................................................................73
7.2. The Home Interface ............................................................................................. 73
7.3. The Component Interface ....................................................................................74
7.4. The Enterprise Bean Class ................................................................................... 74
7.5. Tuning the Stateless-Session Bean Pool .............................................................. 77
8. Developing Entity Beans .................................................................................................... 79
8.1. Introduction to Entity Beans ................................................................................79
8.2. The Home Interface ............................................................................................. 80
8.3. The Component Interface ....................................................................................81
8.4. The Primary Key Class ........................................................................................82
8.5. The Enterprise Bean Class ................................................................................... 84
8.6. Writing Database Access Operations (Bean-Managed Persistence) ................... 89
Page 4
8.7. Configuring Database Access for Container-Managed Persistence..................... 91
8.8. Using CMP2.0 Persistence...................................................................................94
8.9. Standard CMP2.0 Aspects ...................................................................................94
8.10. JOnAS Database Mappers ................................................................................. 95
8.11. JOnAS Database Mapping (Specific Deployment Descriptor)..........................97
8.12. Tuning a Container for Entity Bean Optimizations ......................................... 115
9. Developing Message-Driven Beans..................................................................................119
9.1. Description of a Message-Driven Bean .............................................................119
9.2. Developing a Message-Driven Bean.................................................................. 119
9.3. Administration Aspects......................................................................................121
9.4. Running a Message-Driven Bean ...................................................................... 122
9.5. Transactional Aspects ........................................................................................ 124
9.6. Message-Driven Beans Example .......................................................................124
9.7. Tuning the Message-Driven Bean Pool .............................................................126
10. Defining the Deployment Descriptor .............................................................................. 129
10.1. Principles.......................................................................................................... 129
10.2. Example of Session Descriptors ...................................................................... 130
10.3. Example of Container-managed Persistence Entity Descriptors (CMP 1.1) ... 131
10.4. Tips...................................................................................................................133
11. Transactional Behavior of EJB Applications ..................................................................135
11.1. Declarative Transaction Management.............................................................. 135
11.2. Bean-managed Transactions ............................................................................ 136
11.3. Distributed Transaction Management .............................................................. 137
12. Enterprise Bean Environment .........................................................................................141
12.1. Introduction......................................................................................................141
12.2. Environment Entries ........................................................................................141
12.3. Resource References ........................................................................................ 141
12.4. Resource Environment References ..................................................................142
12.5. EJB References ................................................................................................ 142
13. Security Management ..................................................................................................... 145
13.1. Introduction......................................................................................................145
13.2. Declarative Security Management ...................................................................145
13.3. Programmatic Security Management...............................................................146
14. EJB Packaging ................................................................................................................149
14.1. Enterprise Bean Principles ............................................................................... 149
15. Application Deployment and Installation Guide ............................................................151
15.1. Deployment and Installation Process Principles..............................................151
15.2. Example of Deploying and Installing an EJB Using an EJB-JAR File ........... 151
15.3. Deploying and Installing a Web Application...................................................153
15.4. Deploying and Installing a J2EE Application.................................................. 153
III. Web Application Programmer’s Guide .................................................................................. 155
16. Developing Web Components......................................................................................... 157
16.1. Introduction to Web Component Development ............................................... 157
16.2. The JSP Pages.................................................................................................. 157
16.3. The Servlets ..................................................................................................... 158
16.4. Accessing an EJB from a Servlet or JSP Page.................................................160
17. Defining the Web Deployment Descriptor......................................................................163
17.1. Principles.......................................................................................................... 163
17.2. Examples of Web Deployment Descriptors..................................................... 164
17.3. Tips...................................................................................................................166
18. WAR Packaging..............................................................................................................167
18.1. Principles.......................................................................................................... 167
Page 5
IV. J2EE Client Application Programmer’s Guide .....................................................................169
19. Launching J2EE Client Applications.............................................................................. 171
19.1. Launching Clients ............................................................................................171
19.2. Configuring the Client Container.....................................................................171
19.3. Examples.......................................................................................................... 172
20. Defining the Client Deployment Descriptor ...................................................................173
20.1. Principles.......................................................................................................... 173
20.2. Examples of Client Deployment Descriptors .................................................. 173
20.3. Tips...................................................................................................................175
21. Client Packaging ............................................................................................................. 177
21.1. Principles.......................................................................................................... 177
V. J2EE Application Assembler’s Guide ...................................................................................... 179
22. Defining the EAR Deployment Descriptor .....................................................................181
22.1. Principles.......................................................................................................... 181
22.2. Simple Example of Application Deployment Descriptor ................................ 181
22.3. Advanced Example .......................................................................................... 182
22.4. Tips...................................................................................................................182
23. EAR Packaging...............................................................................................................183
23.1. Principles.......................................................................................................... 183
VI. Advanced Topics ....................................................................................................................... 185
24. JOnAS Services .............................................................................................................. 187
24.1. Introducing a New Service............................................................................... 187
24.2. Advanced Understanding.................................................................................189
25. JOnAS and the Connector Architecture.......................................................................... 193
25.1. Introducing the Connector Architecture ..........................................................193
25.2. Defining the JOnAS Connector Deployment Descriptor.................................193
26. JMS User’s Guide ...........................................................................................................197
26.1. JMS is Pre-installed and Configured................................................................ 197
26.2. Writing JMS Operations Within an Application Component.......................... 197
26.3. Some Programming Rules and Restrictions When Using JMS within EJB ....201
26.4. JMS Administration......................................................................................... 204
26.5. Running an EJB Performing JMS Operations ................................................. 205
26.6. A JMS EJB Example .......................................................................................207
27. Ant EJB Tasks: Using EJB-JAR ..................................................................................... 211
27.1. ejbjar Parameters.............................................................................................. 211
28. Login Modules in a Java Client ...................................................................................... 215
28.1. Configuring an Environment to Use Login Modules with Java Clients ..........215
28.2. Example of a Client ......................................................................................... 215
29. Web Services with JOnAS.............................................................................................. 217
29.1. Web Services.................................................................................................... 217
29.2. Exposing a J2EE Component as a Web Service .............................................. 219
29.3. The Web Services Client..................................................................................222
29.4. WsGen.............................................................................................................. 224
29.5. Limitations .......................................................................................................225
VII. How-to Documents..................................................................................................................227
30. JOnAS Versions Migration Guide ..................................................................................229
30.1. JOnAS 3.3.x to Red Hat Application Server 1.0 ............................................. 229
31. How to Install a jUDDI Server on JOnAS ...................................................................... 231
31.1. UDDI Server ....................................................................................................231
31.2. What is jUDDI? ............................................................................................... 231
31.3. Where Can I Find the Latest Version? .............................................................231
31.4. Installation Steps ..............................................................................................231
31.5. Links ................................................................................................................234
32. Clustering with JOnAS ...................................................................................................235
Page 6
32.1. Cluster Architecture .........................................................................................235
32.2. Load Balancing at the Web Level with mod_jk............................................... 236
32.3. Session Replication at the Web Level..............................................................239
32.4. Load Balancing at the EJB Level..................................................................... 241
32.5. Preview of a Coming Version .......................................................................... 243
32.6. Used Symbols ..................................................................................................243
32.7. References........................................................................................................244
33. Distributed Message Beans in JOnAS 4.1 ......................................................................245
33.1. Scenario and General Architecture .................................................................. 245
33.2. Common Configuration ................................................................................... 245
33.3. Specific Configuration .....................................................................................246
33.4. The Beans.........................................................................................................247
34. How to use Axis in JOnAS .............................................................................................249
34.1. Unique Axis Webapp ....................................................................................... 249
34.2. Embedded Axis Webapp..................................................................................249
34.3. Axis Tests.........................................................................................................250
34.4. Axis Tools........................................................................................................250
35. Using WebSphere MQ JMS............................................................................................253
35.1. Architectural Rules .......................................................................................... 253
35.2. Setting the JOnAS Environment ......................................................................253
35.3. Configuring WebSphere MQ ........................................................................... 254
35.4. Starting the Application ................................................................................... 256
35.5. Limitations .......................................................................................................256
36. Web Service Interoperability between JOnAS and BEA WebLogic ..............................257
36.1. Libraries ........................................................................................................... 257
36.2. Accessing a JOnAS Web Service from a WebLogic Server’s EJB..................257
36.3. Accessing a WebLogic Web Service from a JOnAS EJB................................ 259
37. RMI-IIOP Interoperability between JOnAS and BEA WebLogic..................................263
37.1. Accessing a JOnAS EJB from a WebLogic Server’s EJB using RMI-IIOP .... 263
37.2. Access a WebLogic Server’s EJB from a JOnAS EJB using RMI-IIOP ......... 263
38. Interoperability between JOnAS and CORBA ............................................................... 265
38.1. Accessing an EJB Deployed on a JOnAS Server by a CORBA Client ........... 265
38.2. Accessing a CORBA Service by an EJB Deployed on JOnAS Server............ 267
39. How to Migrate the New World Cruises Application to JOnAS ....................................269
39.1. JOnAS Configuration.......................................................................................269
39.2. SUN Web Service ............................................................................................ 270
39.3. JOnAS Web Service.........................................................................................272
40. Configuring JDBC Resource Adapters ...........................................................................275
40.1. Configuring Resource Adapters .......................................................................275
40.2. Using CMP2.0/JORM......................................................................................277
40.3. ConnectionManager Configuration..................................................................278
40.4. Tracing SQL Requests through P6Spy ............................................................278
40.5. Migration from dbm Service to the JDBC RA ................................................ 280
41. Configuring Resource Adapters ......................................................................................281
41.1. Principles.......................................................................................................... 281
41.2. Description and Examples ...............................................................................281
Index.................................................................................................................................................283
Page 7
I. Introductory JOnAS Documentation
The chapters in this section contain introductory information for all JOnAS users.
Table of Contents
1. Java Open Application Server (JOnAS): a J2EE Platform ........................................................ 1
2. Getting Started with JOnAS ........................................................................................................ 15
3. JOnAS Configuration ...................................................................................................................21
4. Configuring JDBC DataSources.................................................................................................. 51
5. JOnAS Class Loader Hierarchy ..................................................................................................55
6. JOnAS Command Reference ....................................................................................................... 59
Page 8
Page 9
Chapter 1.
Java Open Application Server (JOnAS): a J2EE
Platform
This chapter provides an overview of Red Hat Application Server and the JOnAS J2EE platform.
1.1. Introduction to Red Hat Application Server
Red Hat Application Server is a middleware platform—it is layered between the operating system and applications. This middleware links systems and resources that are scattered across the network.
Red Hat Application Server comprises a runtime system and associated development libraries for cre­ating and deploying Java-based Web applications with dynamic content (for example, dynamic Web sites, portal servers, and content management systems). These applications might retrieve, display, or update data in database management systems such as PostgreSQL or Oracle, or they might communi­cate with standard application software, such as ERP systems, or with proprietary legacy applications.
Red Hat Application Server is a robust platform for the development and deployment of Web applica­tions written in Java and built with JSP, servlet, and Enterprise JavaBeans (EJB) technologies. It has been built to standard protocols and APIs that have emerged from Java, J2EE, Web Services, SOAP (Single Object Access Protocol), XML (Extensible Markup Language), and CORBA (Common Ob­ject Request Broker Architecture) standards groups. Developers build their applications using these standards, while Red Hat’s middleware infrastructure ensures compatibility with the guidelines set forth by the J2EE specifications.
1.1.1. J2EE
The Sun J2EE specification (http://java.sun.com/j2ee/), together with related specifications such as EJB (http://java.sun.com/products/ejb/) and JMS (http://java.sun.com/products/jms/), define an archi­tecture and interfaces for developing and deploying distributed Internet Java server applications based on a multi-tier architecture. This specification facilitates and standardizes the development, deploy­ment, and assembling of application components that will be deployable on J2EE platforms. These applications are typically web-based, transactional, database-oriented, multi-user, secure, scalable, and portable.
More precisely, the Sun J2EE specification describes two kinds of information:
The first is the runtime environment, called a J2EE server, that provides the execution environment
and the required system services, such as the transaction service, the persistence service, the Java Message Service (JMS), and the security service.
The second is programmer and user information that explains how an application component should
be developed, deployed, and used.
Not only will an application component be independent of the platform and operating system (because it is written in Java), it will also be independent of the J2EE platform.
A typical J2EE application is composed of:
Presentation components, also called web components, that define the application
Web interface. These are servlets (http://java.sun.com/products/servlet/) and JSPs (http://java.sun.com/products/jsp/).
Enterprise components, the Enterprise JavaBeans (EJB), that define the application business logic
and application data.
Page 10
2 Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform
The J2EE server provides containers for hosting web and enterprise components. The container pro­vides the component with life-cycle management and interfaces the components with the services provided by the J2EE server:
The web container handles servlet and JSP components.
The EJB container handles the Enterprise JavaBeans components.
A J2EE server can also provide an environment for deploying Java clients (accessing EJBs); this is
called a client container.
Figure 1-1. J2EE Architecture
1.2. JOnAS Features
JOnAS is a pure Java, open-source, application server that conforms to the J2EE specification. Its high degree of modularity enables it to be used as:
A J2EE server, for deploying and running EAR applications (that is, applications composed of both
web and EJB components)
An EJB container, for deploying and running EJB components (for example, for applications with-
out web interfaces or when using JSP/servlet engines that are not integrated as a JOnAS J2EE container)
A Web container, for deploying and running JSPs and servlets (for example, for applications without
EJB components).
1.2.1. System Requirements
JOnAS is available for JDK 1.4. It has been used on many operating systems (Linux, AIX, Windows, Solaris, HP-UX, etc.) and with different databases (Oracle, PostgreSQL, MySQL, SQL server, Access, DB2, Versant, Informix, Interbase, etc.).
Page 11
Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform 3
1.2.2. Java Standard Conformance
JOnAS is an implementation of J2EE 1.4. It currently conforms to EJB 2.1. Its current integration of Tomcat as a Web container ensures conformity to Servlet 2.4 and JSP 2.0 specifications. The JOnAS server relies on or implements the following Java APIs: JCA 1.5, JDBC 3.0, JTA 1.0.1, JMS 1.1, JMX
1.2, JNDI 1.2.1, JAAS 1.0, JACC 1.0, and JavaMail 1.3.
1.2.3. Key Features
In addition to the implementation of all J2EE-related standards, JOnAS provides the following impor­tant advanced features:
Management: JOnAS server management uses JMX and provides a servlet-based management con-
sole.
Services: JOnAS’s service-based architecture provides for high modularity and configurability of
the server. It allows the developer to apply a component-model approach at the middleware level, and makes the integration of new modules easy (for example, for open source contributors). It also provides a way to start only the services needed by a particular application, thus saving valuable system resources. You can manage JOnAS services through JMX.
Scalability: JOnAS integrates several optimization mechanisms for increasing server scalability.
This includes a pool of stateless session beans, a pool of message-driven beans, a pool of threads, a cache of entity beans, activation/passivation of entity beans, a pool of connections (for JDBC and JMS), and storage access optimizations (shared flag, isModified).
Clustering: JOnAS clustering solutions, both at the WEB and EJB levels, provide load balancing,
high availability, and failover support.
Distribution: JOnAS works with several distributed processing environments, due to the
integration of ObjectWeb’s CAROL (Common Architecture for RMI ObjectWeb Layer) project (http://www.objectweb.org/carol/index.html), which enables simultaneous support of several communication protocols:
CMI (Cluster Method Invocation), the “Cluster aware” distribution protocol of JOnAS
RMI (Java Remote Method Invocation) using the Sun proprietary protocol JRMP (Java Remote
Method Protocol)
RMI on IIOP (Java Remote Method Invocation over Internet Inter-Orb Protocol).
Support of "Web Services": Due to the integration of AXIS, JOnAS allows J2EE components to
access "Web Services" (that is, to be "Web Services" clients), and allows J2EE components to be deployed as "Web Services" endpoints. Standard Web Services clients and endpoints deployment, as specified in J2EE 1.4, is supported.
Support of JDO: By integrating the ObjectWeb implementation of JDO (Java Data Objects)
(http://java.sun.com/products/jdo), SPEEDO (http://speedo.objectweb.org), and its associated J2EE CA Resource Adapter, JOnAS provides the capability of using JDO within J2EE components.
Three critical J2EE aspects were implemented early on in the JOnAS server:
J2EE CA: JOnAS applications can easily access Enterprise Information Systems (EIS). By sup-
porting the Java Connector Architecture, JOnAS allows deployment of any J2EE CA-compliant Resource Adapter (connector), which makes the corresponding EIS available from the J2EE ap­plication components. Moreover, resource adapters will become the standard way to plug JDBC drivers (and JMS implementation, with J2EE 1.4) into J2EE platforms. A JDBC Resource Adapter
Page 12
4 Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform
available with JOnAS provides JDBC PreparedStatement pooling and can be used in place of the JOnAS DBM service. A JORAM JMS Resource adapter is also available.
JMS (Java Messaging Service): JMS implementations can be easily plugged into JOnAS. They run
as a JOnAS service either in the same JVM (Java Virtual Machine) or in a separate JVM, and JOnAS provides administration facilities that hide the JMS proprietary administration APIs. Currently, three JMS implementations can be used: the JORAM open-source JMS implementation from Ob­jectWeb (http://joram.objectweb.org/), SwiftMQ (http://www.swiftmq.com/), and Websphere MQ. J2EE CA Resource Adapters are also available, providing a more standard way to plug JORAM or SwiftMQ into JOnAS.
JTA (Java Transaction API): The JOnAS platform supports distributed transactions that involve
multiple components and transactional resources. The JTA transactions support is provided by a Transaction Monitor that has been developed on an implementation of the CORBA Object Trans­action Service (OTS).
1.3. JOnAS Architecture
JOnAS is designed with services in mind. A service typically provides system resources to containers. Most of the components of the JOnAS application server are pre-defined JOnAS services. However, it is possible and easy for an advanced JOnAS user to define a service and to integrate it into JOnAS. Because J2EE applications do not necessarily need all services, it is possible to define, at JOnAS server configuration time, the set of services that are to be launched at server start.
The JOnAS architecture is illustrated in the following figure, showing WEB and EJB containers rely­ing on JOnAS services (all services are present in this figure). Two thin clients are also shown in this figure, one of which is the JOnAS administration console (called JonasAdmin).
Figure 1-2. J2EE Architecture
Page 13
Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform 5
1.3.1. Communication and Naming Service
The Communication and Naming Service (also called Registry) is used for launching the RMI reg­istry, the CosNaming, and/or the CMI registry, depending on the JOnAS configuration (that is, the CAROL configuration, which specifies which communication protocols are to be used). There are different registry launching modes, such as using the same JVM or not, and launching automatically if not already running. CAROL enables multi-protocol runtime support and deployment, which avoids having to redeploy components when changing the communication protocol.
The Communication and Naming Service provides the JNDI (Java Naming and Directory Interface) API to application components and to other services in order to bind and look up remote objects (for example, EJB Homes) and resource references (JDBC DataSource, Mail, and JMS connection factories, etc.).
1.3.2. EJB Container Service
The EJB Container Service is in charge of loading the EJB components and their containers. EJB containers consist of a set of Java classes that implement the EJB specification and a set of interposi­tion classes that interface the EJB components with the services provided by the JOnAS application server. Interposition classes are specific to each EJB component and are generated by the deployment tool called GenIC.
JOnAS configuration provides a means for specifying that this service be launched during JOnAS initialization.
Enterprise JavaBeans (EJB) are software components that implement the business logic of an appli­cation (while the servlets and JSPs implement the presentation). There are three types of Enterprise JavaBeans:
Session beans are objects associated with only one client; they are short-lived (one method call or a
client session) and represent the current state of the client session. They can be transaction-aware, stateful, or stateless.
Entity beans are objects that represent data in a database. They can be shared by several clients
and are identified by means of a primary key. The EJB container is responsible for managing the persistence of such objects. The persistence management of such an object is entirely transparent to the client that will use it, and may or may not be transparent to the bean provider who develops it. This depends on if it is one of the following:
For an Enterprise Bean with Container-Managed Persistence, the bean provider does not de-
velop any data access code; persistence management is delegated to the container. The mapping between the bean and the persistent storage is provided in the deployment descriptor, in an ap­plication server-specific way.
For an Enterprise Bean with Bean-Managed Persistence, the bean provider writes the database
access operations in the methods of the Enterprise Bean that are specified for data creation, load, store, retrieval, and remove operations.
Message-driven Beans are objects that can be considered as message listeners. They execute
on receipt of a JMS Java Message Service message; they are transaction-aware and stateless. They implement some type of asynchronous EJB method invocation. (Refer to http://java.sun.com/products/jms/.)
JOnAS configuration provides a means for specifying a set of EJB-JAR files to be loaded. EJB-JAR files can also be deployed at server runtime using the JOnAS administration tools.
For implementing Container-Managed Persistence of EJB 2.0 and EJB 2.1 (CMP2), JOnAS relies on the ObjectWeb JORM (Java Object Repository Mapping http://jorm.objectweb.org/) and MEDOR (Middleware Enabling Distributed Object Requests http://medor.objectweb.org/) frameworks. JORM
Page 14
6 Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform
supports complex mappings of EJBs to database tables, as well as several types of persistency support (relational databases, object databases, LDAP repositories, etc.).
JOnAS also implements the Timer Service features as specified in EJB 2.1.
1.3.3. WEB Container Service
The WEB Container Service is in charge of running a servlet/JSP engine in the JVM of the JOnAS server and of loading web applications (WAR files) within this engine. Currently, this service can be configured to use Tomcat (see http://jakarta.apache.org/tomcat/). Servlet/JSP engines are integrated within JOnAS as web containers, that is, containers that provide the web components with access to the system resources (of the application server) and to EJB components, in a J2EE-compliant way.
JOnAS configuration provides a means for specifying that the WEB Container Service be launched during JOnAS initialization. Additionally, JOnAS configuration provides a means for specifying a set of WAR files to be loaded. Such WAR files can also be deployed at server runtime using the JOnAS administration tools. User management for Tomcat and JOnAS has been unified. The class-loading delegation policy (priority to the Webapp classloader or to the parent classloader) can be configured.
Servlet (http://java.sun.com/products/servlet/) and JSP (http://java.sun.com/products/jsp/) are tech­nologies for developing dynamic web pages. The servlet approach allows the development of Java classes (HTTP servlets) that generate HTML pages and that can be invoked through HTTP requests. Typically, servlets access the information system using Java APIs (such as JDBC or the APIs of EJB components) in order to build the content of the HTML page they will generate in response to the HTTP request. The JSP technology is a complement of the servlet technology. A JSP is an HTML page containing Java code within particular XML-like tags; this Java code is in charge of generating the dynamic content of the HTML page.
Servlets and JSPs are considered as J2EE application components, responsible for the application presentation logic. Such application components can access resources provided by the J2EE server (such as JDBC datasources, JMS connection factories, EJBs, mail factories). For EJB components, the actual assignment of these resources is performed at component deployment time and is specified in the deployment descriptor of each component, because the component code uses logical resource names.
1.3.4. EAR Service
The EAR Service is used for deploying complete J2EE applications, that is, applications packaged in EAR files, which themselves contain EJB-JAR files and/or WAR files. This service handles the EAR files and delegates the deployment of the WAR files to the WEB Container service and the EJB-JAR files to the EJB Container service. It handles creating the appropriate class loaders, as defined in the J2EE specification, in order for the J2EE application to execute properly.
For deploying J2EE applications, JOnAS must be configured to launch the EAR service and to specify the set of EAR files to be loaded. EAR files can also be deployed at server runtime using the JOnAS administration tools.
1.3.5. Transaction Service
The Transaction Service encapsulates a Java Transaction Monitor called JOTM, a project from Ob­jectWeb (http://jotm.objectweb.org). It is a mandatory service that handles distributed transactions. It provides transaction management for EJB components as defined in their deployment descriptors. It handles two-phase commit protocol against any number of Resource Managers (XA Resources). For J2EE, a transactional resource can be a JDBC connection, a JMS session, or a J2EE CA Resource Adapter connection. The transactional context is implicitly propagated with the distributed requests. The Transaction Monitor can be distributed across one or more JOnAS servers; thus a transaction
Page 15
Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform 7
may involve several components located on different JOnAS servers. This service implements the JTA 1.0.1 specification, thus allowing transactions from application components or from application clients to be explicitly started and terminated. Starting transactions from application components is allowed only from Web components, session beans, or message-driven beans. Restricting transactions to only these two types of beans is called Bean-managed transaction demarcation.
One of the main advantages of the EJB support for transactions is its declarative aspect, which means that transaction control is no longer hard-coded in the server application, but is configured at deploy­ment time. This is known as container-managed transaction demarcation. With container-managed transaction demarcation, the transactional behavior of an Enterprise Bean is defined at configuration time and is part of the deployment descriptor of the bean. The EJB container is responsible for pro­viding the transaction demarcation for the enterprise beans according to the value of transactional attributes associated with EJB methods. These attributes can be one of the following:
NotSupported: If the method is called within a transaction, this transaction is suspended during
the time of the method execution.
Required: If the method is called within a transaction, the method is executed in the scope of this
transaction; otherwise, a new transaction is started for the execution of the method and committed before the method result is sent to the caller.
RequiresNew: The method is always executed within the scope of a new transaction. The new
transaction is started for the execution of the method and committed before the method result is sent to the caller. If the method is called within a transaction, this transaction is suspended before the new one is started, and resumed when the new transaction has completed.
Mandatory: The method should always be called within the scope of a transaction; otherwise, the
container throws the TransactionRequired exception.
Supports: The method is invoked within the caller transaction scope. If the caller does not have
an associated transaction, the method is invoked without a transaction scope.
Never: With this attribute the client is required to call the method without a transaction context,
otherwise the container throws the java.rmi.RemoteException exception.
The ObjectWeb project JOTM (Java Open Transaction Manager), is actually based on the transaction service of earlier JOnAS versions. It will be enhanced to provide advanced transaction features, such as nested transactions and “Web Services” transactions (an implementation of DBTP is available).
1.3.6. Database Service
This service is responsible for handling Datasource objects. A Datasource is a standard JDBC admin­istrative object for handling connections to a database. The database service creates and loads such datasources on the JOnAS server. DataSources to be created and deployed can be specified at JOnAS configuration time, or they can be created and deployed at server runtime using the JOnAS admin­istration tools. The database service is also responsible for connection pooling; it manages a pool of database connections to be used by the application components, thus avoiding many physical con­nection creations, which are time-consuming operations. The database service can now be replaced by the JDBC Resource Adapter, to be deployed by the J2EE CA resource service, which additionally provides JDBC PreparedStatement pooling.
1.3.7. Security Service
The Security Service implements the authorization mechanisms for accessing J2EE components, as specified in the J2EE specification.
Page 16
8 Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform
EJB security is based on the concept of roles. The methods can be accessed by a given set of roles.
In order to access the methods, you must be in at least one role of this set.
The mapping between roles and methods (permissions) is done in the deployment descriptor using the security-role and method-permission elements. Programmatic security management is also possible using two methods of the EJBContext interface in order to enforce or comple­ment security check in the bean code: getCallerPrincipal() and isCallerInRole (String
roleName). The role names used in the EJB code (in the isCallerInRole method) are, in fact,
references to actual security roles, which makes the EJB code independent of the security configu­ration described in the deployment descriptor. The programmer makes these role references avail­able to the bean deployer or application assembler by way of the security-role-ref elements included in the session or entity elements of the deployment descriptor.
Web security uses the same mechanisms; however, permissions are defined for URL patterns instead
of EJB methods. Therefore, the security configuration is described in the Web deployment descrip­tor. Programmatically, the caller role is accessible within a web component via the isUserInRole
(String roleName) method.
In JOnAS, the mapping between roles and user identification is done in the user identification repos­itory. When using Tomcat for user authentication, this user identification repository can be stored either in files, in a JNDI repository (such as LDAP), or in a relational database. This is achieved through a JOnAS implementation of the Realm for each Web container and through the JAAS (Java Authentication and Authorization Service) login modules for Java clients.
Realms use authentication resources provided by JOnAS, which enable you to rely on files, LDAP, or JDBC. These realms are in charge of propagating the security context to the EJB container dur­ing EJB calls. JAAS login modules are provided for user authentication of Web Container and Java clients. Certificate-based authentication is also available, with the CRLLoginModule login module for certificate revocation.
JOnAS also implements the Java Authorization Contract for Containers (JACC 1.0) specification, allowing you to manage authorizations as Java security permissions and to plug in any security policy provider.
1.3.8. Messaging Service
Asynchronous EJB-method invocation is possible on Message-driven Bean components. A Message-driven Bean is an EJB component that can be considered to be a JMS (Java Message Service) MessageListener; that is, a service that processes JMS messages asynchronously (see http://java.sun.com/products/jms). It is associated with a JMS destination. Its onMessage method is activated on the reception of messages sent by a client application to this destination. It is also possible for any EJB component to use the JMS API within the scope of transactions managed by the application server.
For supporting Message-driven Beans and JMS operations coded within application components, the JOnAS application server relies on a JMS implementation. JOnAS makes use of a third-party JMS im­plementation; currently the JORAM open-source software is integrated and delivered with JOnAS, the SwiftMQ product can also be used, and other JMS provider implementations can easily be integrated (see http://joram.objectweb.org/ and http://www.swiftmq.com/). JORAM provides several noteworthy features, particularly:
Reliability (with a persistent mode)
Distribution (transparently to the JMS client, it can run as several servers, thus allowing load bal-
ancing)
The choice of TCP or SOAP as the communication protocol for messages.
Page 17
Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform 9
The JMS service is in charge of launching (or establishing a connection to) the integrated JMS server, which may or may not run in the same JVM as JOnAS. It also provides connection pooling and thread pooling (for Message-driven Beans). Through this service, JOnAS provides facilities to create JMS­administered objects such as the connection factories and the destinations, either at server-launching time or at runtime using the JOnAS administration tools.
Note that the same function of JMS implementation integration can now be achieved through a Re­source Adapter, to be deployed by the J2EE CA Resource Service. Such a Resource Adapter, J2EE CA 1.5, is provided for JORAM.
1.3.9. J2EE CA Resource Service
The J2EE Connector Architecture (J2EE CA) allows the connection of different Enterprise Informa­tion Systems (EIS) to a J2EE application server. It is based on the Resource Adapter (RA); this is an architecture component—comparable to a software driver—that connects the EIS, the application server, and the enterprise application (J2EE components). The RA is generally provided by an EIS vendor and provides a Java interface (the Common Client Interface or CCI) to the J2EE components for accessing the EIS (this can also be a specific Java interface). The RA also provides standard in­terfaces for plugging into the application server, allowing them to collaborate to keep all system-level mechanisms (transactions, security, and connection management) transparent from the application components.
Figure 1-3. JCA Architecture
The application performs "business logic" operations on the EIS data using the RA client API (CCI), while transactions, connections (including pooling), and security on the EIS are managed by the ap­plication server through the RA (system contract).
The JOnAS Resource service is in charge of deploying J2EE CA-compliant Resource Adapters (con­nectors), packaged as RAR files, on the JOnAS server. RAR files can also be included in EAR files, in which case the connector will be loaded by the application classloader. Once Resource Adapters are deployed, a connection factory instance is available in the JNDI namespace to be looked up by application components.
A J2EE CA 1.0 Resource Adapter for JDBC is available with JOnAS. It can replace the current JOnAS database service for plugging JDBC drivers and managing connection pools. It also provides JDBC
Page 18
10 Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform
PreparedStatement pooling.
A J2EE CA 1.5 Resource Adapter for JMS is available with JOnAS. It can replace the current JOnAS Messaging service for plugging into JORAM.
1.3.10. Management Service
You require the Management service in order to administer a JOnAS server from the JOnAS admin­istration console. Each server running this service is visible from the administration console.
The Management service is based on JMX (Java Management Extension). Standard MBeans defined within the JOnAS application server expose the management methods of the instrumented JOnAS server objects, such as services, containers, and the server itself. These MBeans implement the man­agement model as specified in the J2EE Management Specification. The Management service runs a JMX server (currently the MX4J server, but the Sun RI server is also available). The MBeans of the JOnAS server are registered within this JMX server.
The JOnAS administration console is a Struts-based Web application (servlet/JSP) that accesses the JMX server to present the managed features within the administration console. Thus, through a simple Web browser, it is possible to manage one or several JOnAS application servers. The administration console provides a means for configuring all JOnAS services (and making the configuration persis­tent) and for deploying any type of application (EJB-JAR, WAR, EAR) and any type of resource (DataSources, JMS and Mail connection factories, J2EE CA connectors), all without the need to stop or restart the server. The administration console displays information for monitoring the servers and applications. This information includes used memory, used threads, number of EJB instances, and which component currently uses which resources. When Tomcat is used as Web Container, the Tomcat Management is integrated within the JOnAS console. A Management EJB (MEJB) is also delivered, providing access to the management features, as specified in the J2EE Management Specification.
1.3.11. Mail Service
A J2EE application component can send e-mail messages using JavaMail (see http://java.sun.com/products/javamail/). The Mail service of the JOnAS application server provides the resources necessary for the J2EE application components. The Mail service creates mail factories and registers these resources in the JNDI namespace in the same way that the database service or the JMS service creates Datasources or ConnectionFactories and registers these objects in the JNDI namespace. There are two types of mail factories: javax.mail.Session and
javax.mail.internet.MimePartDataSource.
1.3.12. WebServices Service
This service is implemented on top of AXIS and is used for the deployment of Web Services.
1.4. JOnAS Development and Deployment Environment
The JOnAS development and deployment environment comprises the JOnAS configuration and de­ployment facilities and the JOnAS development environment.
1.4.1. JOnAS Configuration and Deployment Facilities
Once JOnAS has been installed in a directory referenced by the JONAS_ROOT environment variable, it is possible to configure servers and to deploy applications into several execution environments. This is achieved using the JONAS_BASE environment variable. JONAS_ROOT and JONAS_BASE can
Page 19
Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform 11
be compared to the CATALINA_HOME and CATALINA_BASE variables of Tomcat. While JONAS_ROOT is dedicated to JOnAS installation, JONAS_BASE is used to specify a particular JOnAS instance con­figuration. JONAS_BASE designates a directory containing a specific JOnAS configuration, and it iden­tifies subdirectories containing the EJB-JAR, WAR, EAR, and RAR files that can be loaded in this application environment. There is an ANT target in the JOnAS build.xml file for creating a new
JONAS_BASE directory structure. Thus, from one JOnAS installation, it is possible to switch from one
application environment to another by just changing the value of the JONAS_BASE variable.
There are two ways to configure a JOnAS application server and load applications: either by using the administration console or by editing the configuration files. There are also “autoload” directories for each type of application and resource (EJB-JAR, WAR, EAR, RAR) that allow the JOnAS server to automatically load the applications located in these directories when starting.
JOnAS provides several facilities for deployment:
For writing the deployment descriptors, plugins for Integrated Development Environments (IDE)
provide some generation and editing features (Eclipse and JBuilder plugins are available). The NewBean JOnAS built-in tool generates template deployment descriptors. The Xdoclet tool also generates deployment descriptors for JOnAS. The Apollon ObjectWeb project generates Graph­ical User Interfaces for editing any XML file; it has been used to generate a deployment de­scriptor editor GUI (see http://debian-sf.objectweb.org/projects/apollon). A deployment tool de­veloped by the ObjectWeb JOnAS community, earsetup (http://sourceforge.net/projects/earsetup), will also be available for working with the JSR88-compliant (J2EE 1.4) deployment APIs provided by the ObjectWeb Ishmael project (see http://sourceforge.net/projects/earsetup/ and http://debian­sf.objectweb.org/projects/ishmael/ respectively.
Some basic tools for the deployment itself are the JOnAS GenIC command line tool and the cor-
responding ANT EJB-JAR task. The IDE plugins integrate the use of these tools for deployment operations. The main feature of the Ishmael project will be the deployment of applications on the JOnAS platform.
1.4.2. JOnAS Development Environments
There are many plugins and tools that facilitate the development of J2EE applications to be deployed on JOnAS. IDE plugins for JBuilder Kelly (http://forge.objectweb.org/projects/kelly/), JOPE (http://forge.objectweb.org/projects/jope/), and Lomboz (http://lomboz.objectweb.org) provide the means to develop, deploy, and debug J2EE components on JOnAS. The Xdoclet code generation engine (http://xdoclet.sourceforge.net/) can generate EJB interfaces and deployment descriptors (standard and JOnAS specific ones), taking as input the EJB implementation class containing specific JavaDoc tags. The JOnAS NewBean tool generates templates of interfaces, implementation class, and deployment descriptors for any kind of EJB. Many development tools may work with JOnAS; refer to the JOnAS tools page at http://www.objectweb.org/jonas/tools.html for more details.
In addition, JOnAS is delivered with complete J2EE examples, providing a build.xml ANT file with all the necessary targets for compiling, deploying, and installing J2EE applications.
1.5. Clustering and Performance
Clustering for an application server generally makes use of three features: Load Balancing (LB), High Availability (HA), and Failover. Such mechanisms can be provided at the Web-container level by dispatching requests to several Servlet/JSP engine instances, at the EJB-container level by dispatching EJB requests to several EJB container instances, and at the database level by using several databases. A replicated JNDI naming is also necessary.
JOnAS provides Load Balancing, High Availability, and Failover at the WEB container level using the Apache Tomcat mod_jk plugin and an HTTP-in-memory session-replication mechanism based
Page 20
12 Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform
on JGroups. The plugin dispatches HTTP requests from the Apache web server to Tomcat instances running as JOnAS web containers. Server fluctuations are automatically taken into account. This plu­gin supports round-robin and weighted round-robin load-balancing algorithms, with a sticky session option.
Load balancing and HA are provided at the EJB container level in JOnAS. Operations invoked on EJB Home interfaces (EJB creation and retrieval) are dispatched on the nodes of the cluster. The mechanism is based on a clustered-aware replicated JNDI registry using a Clustered remote Method Invocation protocol (CMI). The stubs contain the knowledge of the cluster and implement the load­balancing policy, which may be round-robin and weighted round-robin. In the near future, a load­balancing mechanism based on the nodes load will be available. Failover at the EJB level will be provided by implementing a stateful Session Bean state replication mechanism.
The JOnAS clustering architecture is illustrated in the following figure.
Figure 1-4. Clustered Architecture
Apache is used as the front-end HTTP server; Tomcat is used as the JOnAS web container. The JOnAS servers share the same database. The mod_jk plug-in provides load balancing/high availability at the Servlet/JSP level. Failover is provided through the in-memory, session-replication mechanism. Load balancing/high availability are provided at the EJB level through the CMI protocol associated with the replicated, clustered-aware JNDI registry. Tomcat may or may not run in the same JVM as the EJB container. JOnAS provides some documentation for configuring such an architecture.
The use of the C-JDBC ObjectWeb project offers load balancing and high availability at the database level (see http://www.objectweb.org/c-jdbc/index.html). The use of C-JDBC is transparent to the ap­plication (in our case, to JOnAS), because it is viewed as a standard JDBC driver. However, this “driver” implements the cluster mechanisms (reads are load-balanced and writes are broadcasted). The database is distributed and replicated among several nodes, and C-JDBC load balances the queries between these nodes. An evaluation of C-JDBC using the TPC-W benchmark on a 6-node cluster has shown performance scaling linearly up to six nodes.
Page 21
Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform 13
In addition to clustering solutions, JOnAS provides many intrinsic mechanisms to ensure high scalable and efficiency:
A pool of stateless Session Bean instances
A pool of Entity Bean instances, configurable for each Entity Bean within its deployment descriptor
Activation/passivation of entity beans (passivation can be controlled through the management con-
sole)
Pools of connections, for JDBC, JMS, J2EE CA connectors
A pool of threads for message-driven beans
Session Bean timeout can be specified at deployment
A “shared” flag in the specific deployment descriptor of an Entity Bean that indicates whether the
persistent representation of this Entity Bean is shared by several servers/applications, or whether it is dedicated to the JOnAS server where it is loaded. In the latter case, the optimization performed by JOnAS consists of not reloading the corresponding data between transactions.
The usual EJB 1.1 “isModified” (or “Dirty”) mechanism is available, for avoiding storage of un-
modified data.
Some benchmarks and JOnAS Use cases have already proven that JOnAS is highly scalable. Re­fer to the Rubis http://www.cs.rice.edu/CS/Systems/DynaServer/perf_scalability_ejb.pdf results or the OpenUSS Use case (http://openuss.sourceforge.net/openuss/). Rubis is a benchmark for e-commerce J2EE applications, which now belongs to the ObjectWeb JMOB (Java Middleware Open Benchmark­ing) project (http://www.objectweb.org/jmob/index.html). OpenUSS is an operational university por­tal that has approximately 20,000 users.
1.6. Future Development
As an open source implementation of a J2EE server, JOnAS is constantly evolving to satisfy user requirements and to follow the related standards. These are the current JOnAS plans:
J2EE 1.4 compliance, JOnAS being currently in the process of passing the Sun J2EE Compatibility
Test Suite.
JOnAS administration will be enhanced by completing the concept of management domain, and by
introducing cluster management facilities.
Addressing performance issues by developing workbenches and by producing tuning guides.
Support of “Web Services” and tools for developing those services.
Deployment APIs as specified in JSR88 (J2EE 1.4) will be supported as a result of the Ishmael
project.
Page 22
14 Chapter 1. Java Open Application Server (JOnAS): a J2EE Platform
Page 23
Chapter 2.
Getting Started with JOnAS
This tutorial guides you through running a first example EJB. Guidance is also provided for running a more complex example in which an EJB has access to a database.
You can find additional information about JOnAS configuration in Chapter 3 JOnAS Configuration.
2.1. Running the First EJB Application
2.1.1. JOnAS Examples
There are several examples in the JOnAS distribution under $JONAS_ROOT/examples/src. You should run the example located in the $JONAS_ROOT/examples/src/sb/ directory first.
In this example, a Java client accesses a stateful Session Bean and calls the buy method of the bean several times inside the scope of transactions.
2.1.2. Building the sb Example
The easiest way to compile this example is to go to the sb directory $JONAS_ROOT/examples/src/sb/ and use the compile.sh shell script.
2.1.3. Running the sb Example
This a distributed example in which two processes are involved:
The JOnAS server, in which beans will be loaded
The Java client that creates instances of beans and calls business methods on it.
To run this example:
1. Run the JOnAS server:
service jonas start
The following message is displayed on the standard output:
The JOnAS Server ’jonas’ version-number is ready
2. Make beans available to clients by loading the jar containing the sb example:
jonas admin -a sb.jar
The following message is displayed on the standard output:
message-header: Op available
3. Run the Java client in another terminal command-line window:
jclient sb.ClientOp
4. If the following output displays, the first EJB application with JOnAS has run successfully:
Create a bean Start a first transaction First request on the new bean Second request on the bean Commit the transaction Start a second transaction
Page 24
16 Chapter 2. Getting Started with JOnAS
Rollback the transaction Request outside any transaction ClientOp OK. Exiting.
5. Before ending this session, be sure to stop the JOnAS server:
service jonas stop
These instructions are also located in the README file in the working directory.
2.1.4. Understanding Why This Works
This example demonstrates that the CLASSPATH is correctly set because, when the JOnAS server is
launched, the jonas script calls the JOnAS bootstrap class.
The jclient script is being used to run the client. Note that the bean classes were found in
$JONAS_ROOT/examples/classes. If this had not been the case, it would have been necessary
to call the jclient script with the -cp "$JONAS_ROOT/ejbjars/sb.jar" option.
The client has succeeded in contacting the JOnAS server because the client has a distributed refer-
ence that was previously registered in the naming service. To do this, server and client use JNDI (the Java Naming and Directory Interface). The carol.properties file (which contains the JNDI configuration) is located in the $JONAS_ROOT/conf directory.
This carol.properties has the JNDI properties set to the default values.
With these default values, the registry runs on localhost on the default port (1099 for RMI/JRMP).
By default, the registry is launched in the same JVM as the JOnAS Server.
2.2. More Complex Examples
2.2.1. Other JOnAS Examples
The following examples are located under $JONAS_ROOT/examples/src:
The eb example ($JONAS_ROOT/examples/src/eb/) uses Entity beans. (See Section 2.2.2 An Ex-
ample With Database Access.)
The two beans share the same interface (Account): one uses bean-managed persistence (explicit persistence), the other uses container-managed persistence (implicit persistence).
This is a good example for understanding what must be done, or not done, for persistence, based on the chosen mode of persistence. It provides both a CMP 1.1 and a CMP 2.0 implementation.
The lb example ($JONAS_ROOT/examples/src/lb/) uses Entity beans with local interfaces.
A Session Bean, Manager, locally manages an Entity Bean, Manac, which represents an account.
This is a good example for understanding what must be done for a local client collocated with an Entity Bean providing local interfaces.
The jms directory ($JONAS_ROOT/examples/src/jms/) contains a stateful Session Bean with
methods performing JMS operations and a pure JMS client message receptor.
A complete description of this example is in Section 26.6 A JMS EJB Example.
The mailsb directory ($JONAS_ROOT/examples/src/mailsb/) contains a SessionMailer and
MimePartDSMailer Stateful Session beans with methods providing a way for building and
sending mail.
Page 25
Chapter 2. Getting Started with JOnAS 17
The mdb/samplemdb directory ($JONAS_ROOT/examples/src/mdb/samplemdb/) contains a Mes-
sage Driven Bean that listens to a topic and an MdbClient, which is a pure JMS client, that sends
10 messages on the corresponding topic.
This is a very good example for understanding how to write and use message-driven beans.
The mdb/sampleappli directory ($JONAS_ROOT/examples/src/mdb/sampleappli/) contains the
following:
Two Message-Driven beans, one listening to a topic (StockHandlerBean) the other listening
to a queue (OrderBean)
An Entity Bean with container-managed persistence (StockBean) and a stateless Session Bean
for creating the table used in the database.
SampleAppliClient sends several messages on the topic. Upon receipt of a message, the StockHan- dlerBean updates the database via the StockBean and sends a message to the queue inside a global transaction. All of the EJBs are involved in transactions that may commit or rollback.
Alarm (http://jonas.objectweb.org/current/examples/alarm/) is an application that watches alarm
messages generated asynchronously through JMS. It utilizes the different techniques used in JOnAS:
An Entity Bean for AlarmRecord, persistent in a database
A Session Bean to allow clients to visualize Alarms received
A Message Driven Bean to catch Alarms
JMS to use a topic where Alarms are sent and received
Tomcat (for JSP pages and servlets)
Security.
Earsample (http://jonas.objectweb.org/current/examples/earsample/) contains a complete J2EE ap-
plication. This sample is a simple stateful Session Bean that has synchronization and security.
This bean is accessed from a servlet in which the user is authenticated and JOnAS controls access to the methods of the bean. The servlet performs a variety of lookups (resource-ref, resource-env-ref, env-entry, ejb-ref, and ejb-local-ref) in the java:comp/env environment to illustrate how the uniform naming works in the servlets.
The CMP2 directory (http://jonas.objectweb.org/current/examples/cmp2/) contains an example il-
lustrating most of the concepts of CMP 2.0.
jaasclient (http://jonas.objectweb.org/current/examples/jaasclient/) contains an example of a
JAAS login module that illustrates the different methods for authentication.
There are different callback handlers that demonstrate how to enter identification at a command line prompt, either with a dialog or without a prompt (where the client uses its own login/password).
Each directory contains a README that explains how to build and run each example.
2.2.2. An Example With Database Access
The eb example contains two Entity beans that manage Account objects.
The two beans share the same interface (Account); one with bean-managed persistence (BMP, explicit persistence), the other with container-managed persistence (CMP, implicit persistence). The default CMP implementation is CMP 1.1. A CMP 2.0 implementation is also provided and its use is described in the README.
Before running this example, perform the steps in:
Page 26
18 Chapter 2. Getting Started with JOnAS
Section 2.2.2.1 Configuring Database Access
Section 2.2.2.2 Creating the Table in the Database
Section 2.2.2.3 Configuring the Classpath
2.2.2.1. Configuring Database Access
In order to be able to access your relational database, JOnAS will create and use a DataSource object that must be configured according to the database that will be used.
These DataSource objects are configured via properties files. $JONAS_ROOT/conf contains templates for configuring DataSource objects for databases such as Oracle and PostgreSQL:
$JONAS_BASE/conf/Oracle1.properties
$JONAS_BASE/conf/PostgreSQL1.properties
Depending on your database, you can customize one of these files with values appropriate for your installation. After doing so, you must update the property jonas.service.dbm.datasources in the jonas.properties file.
For example, for the Oracle1.properties file.
jonas.service.dbm.datasources Oracle1
Section 3.5.7 Configuring the Database Service provides more details about DataSource objects and their configuration.
2.2.2.2. Creating the Table in the Database
The $JONAS_ROOT/examples/src/eb directory contains an SQL script for Oracle: Account.sql ($JONAS_ROOT/examples/src/eb/Account.sql). If your Oracle server is running and you are using CMP 1.1, you can create the table used by the example. If you are using CMP 2.0, do not create the table.
2.2.2.2.1. Example: Creating the Table in Oracle
sqlplus user/passwd
SQL
@Account.sql
SQLquit
2.2.2.3. Configuring the Classpath
The JDBC driver classes must be accessible from the classpath. To enable that, update the
config_env file (http://jonas.objectweb.org/current/bin/unix/config_env).
In this file, set one of the following variables: IDB_CLASSES, ORACLE_CLASSES, or POST­GRE_CLASSES with the appropriate value for your database installation.
Page 27
Chapter 2. Getting Started with JOnAS 19
2.2.2.4. Building the eb Example
The simplest way to compile this example is to go to the $JONAS_ROOT/examples/src/eb directory ($JONAS_ROOT/examples/src/eb/) and use the compile.sh shell script ($JONAS_ROOT/examples/src/eb/compile.sh).
If the Ant 1.5 build tool is installed on your machine, you can build the JOnAS examples by using the build.xml files located in the $JONAS_ROOT/examples or $JONAS_ROOT/examples/src directories. To do this, use the build.sh shell script.
2.2.2.5. Running the eb Example
Here, again, two processes are involved:
The JOnAS server in which beans will be loaded
The Java client that creates instances of beans and calls business methods on it.
To run this example:
1. Run the JOnAS server to make beans available to clients:
service jonas start
jonas admin -a eb.jar
The following messages are displayed on the standard output:
The JOnAS Server ’jonas’ version-number is ready and running on rmi
message-header : AccountExpl available
message-header : AccountImpl available
2. Run the Java clients in another terminal emulator window:
jclient eb.ClientAccount AccountImplHome
jclient eb.ClientAccount AccountExplHome
The example eb has run successfully if the following output displays:
Getting a UserTransaction object from JNDI
Connecting to the AccountHome
Getting the list of existing accounts in database
101 Antoine de St Exupery 200.0 102 alexandre dumas fils 400.0 103 conan doyle 500.0 104 alfred de musset 100.0 105 phileas lebegue 350.0 106 alphonse de lamartine 650.0
Creating a new Account in database
Finding an Account by its number in database
Starting a first transaction, that will be committed
Starting a second transaction, that will be rolled back
Getting the new list of accounts in database
Page 28
20 Chapter 2. Getting Started with JOnAS
101 Antoine de St Exupery 200.0 102 alexandre dumas fils 300.0 103 conan doyle 500.0 104 alfred de musset 100.0 105 phileas lebegue 350.0 106 alphonse de lamartine 650.0 109 John Smith 100.0
Removing Account previously created in database
ClientAccount terminated
3. Before ending this session, be sure to stop the JOnAS server:
service jonas stop
Page 29
Chapter 3.
JOnAS Configuration
This chapter describes how to configure JOnAS.
3.1. JOnAS Configuration Rules
As described in Chapter 2 Getting Started with JOnAS, JOnAS is pre-configured and ready to use directly with RMI/JRMP for remote access, if visibility to classes other than those contained in the JOnAS distribution in $JONAS_ROOT/lib is not required.
To use RMI/IIOP for remote access or to work with additional Java classes (for example, JDBC driver classes), you must perform additional configuration tasks, such as setting a specific port number for the registry.
The JOnAS distribution contains a number of configuration files in $JONAS_ROOT/conf directory. These files can be edited to change the default configuration. However, it is recommended that the configuration files needed by a specific application running on JOnAS be placed in a separate location. This is done by using an additional environment variable called JONAS_BASE.
3.1.1. JONAS_BASE Environment Variable
Warning
JOnAS configuration files are read from the $JONAS_BASE/conf directory. If JONAS_BASE is not de­fined, it is automatically initialized to $JONAS_ROOT.
There are two ways to use the JONAS_BASE environment variable:
1. Perform the following actions:
a. Create a new directory and initialize JONAS_BASE with the path to this directory.
b. Create the following sub-directories in $JONAS_BASE:
conf
ejbjars
apps
webapps
rars
logs
c. Copy the configuration files located in $JONAS_ROOT/conf into $JONAS_BASE/conf.
Then, modify the configuration files according to the requirements of your application, as explained in the following sections.
2. Perform the following actions:
Initialize $JONAS_BASE with a path.
Change to the $JONAS_ROOT directory and enter:
ant create_jonasbase
Page 30
22 Chapter 3. JOnAS Configuration
This copies all the required files and creates all the directories.
Note
The build.xml files provided with the JOnAS examples support JONAS_BASE. If this environment variable is defined prior to building and installing the examples, the generated archives are installed under the appropriate sub-directory of $JONAS_BASE. For example, the EJB-JAR files corresponding to the sample examples of $JONAS_ROOT/examples/s rc/ are installed in $JONAS_BASE/ejbjars.
3.2. Configuring the JOnAS Environment
3.2.1. The JOnAS Configuration File
The JOnAS server is configured via a configuration file named jonas.properties. It contains a list of key/value pairs presented in the Java properties file format.
The default configuration is provided in $JONAS_ROOT/conf/jonas.properties (refer to
$JONAS_BASE/conf/jonas.properties). This file, which holds all possible properties with
their default values, is mandatory. The JOnAS server looks for this file at start time in the
$JONAS_BASE/conf directory ($JONAS_ROOT/conf if $JONAS_BASE is not defined).
Most of the properties are related to the JOnAS services that can be launched in the JOnAS server. These properties are described in detail in Section 3.5 Configuring JOnAS Services.
The property jonas.orb.port is not related to any service. It identifies the port number on which the remote objects receive calls. Its default value is 0, which means that an anonymous port is chosen. When the JOnAS server is behind a firewall, this property can be set to a specific port number.
When several JOnAS servers must run simultaneously, it is beneficial to set a different name for each JOnAS server in order to administer these servers.
Also note that it is possible to define configuration properties on the command line:
java -Dproperty=value
Use the jonas check command to review the JOnAS configuration state. (Refer to Section 6.1 jonas.)
3.2.2. Configuration Scripts
The JOnAS distribution contains the $JONAS_ROOT/bin/unix/setenv and
$JONAS_ROOT/bin/unix/config_env configuration scripts.
These configuration scripts set useful environment variables for JAVA setup ($JAVA and $JAVAC). They add $JONAS_BASE/conf to the $CLASSPATH if $JONAS_BASE is set, otherwise they add
$JONAS_ROOT/conf. These scripts are called by almost all other scripts (jclient, jonas, newbean, registry, GenIC).
Therefore, when requiring the visibility of specific .jar files, the best practice is to update the
config_env file. For example, to see some of the JDBC driver classes, one or more of the variables IDB_CLASSES, ORACLE_CLASSES, and POSTGRE_CLASSES must be updated.
Another way to place an additional .jar in the classpath of your JOnAS server is to insert it at the end of the config_env file:
Page 31
Chapter 3. JOnAS Configuration 23
CLASSPATH=The_Path_To_Your_Jar$SPS$CLASSPATH
Note that an additional environment variable called XTRA_CLASSPATH can be defined to load specific classes at JOnAS server start-up. Refer to Chapter 5 JOnAS Class Loader Hierarchy.
3.3. Configuring the Communication Protocol and JNDI
3.3.1. Choosing the Protocol
Typically, access to JNDI (the Java Naming and Directory Interface) is bound to a jndi.properties file that must be accessible from the classpath. This is somewhat different within JOnAS. Starting with JOnAS 3.1.2, multi-protocol support is provided through the integration of the CAROL component (refer to http://www.objectweb.org/carol). This currently provides support for RMI/JRMP, RMI/IIOP, and CMI (clustered protocol) by changing the configuration. Other protocols may be supported in the future. This configuration is now provided within the carol.properties file (that includes what was provided in the jndi.properties file). This file is supplied with the JOnAS distribution in the
$JONAS_ROOT/conf directory (refer to $JONAS_BASE/conf/carol.properties).
The following communication protocols are supported:
RMI/JRMP is the JRE implementation of RMI on the JRMP protocol. This is the default commu-
nication protocol.
RMI/IIOP is the JRE implementation of RMI over the IIOP protocol.
CMI (Cluster Method Invocation) is the JOnAS communication protocol used for clustered config-
urations. Note that this protocol is based on JRMP.
The carol.properties file contains:
# jonas rmi activation (jrmp, iiop, or cmi) carol.protocols=jrmp #carol.protocols=cmi #carol.protocols=iiop #carol.protocols=jeremie # RMI JRMP URL carol.jrmp.url=rmi://localhost:1099
# RMI IIOP URL carol.iiop.url=iiop://localhost:2000
# CMI URL carol.cmi.url=cmi://localhost:2001
# general rules for jndi carol.jndi.java.naming.factory.url.pkgs=org.objectweb.jonas.naming
CAROL can be customized by editing the $JONAS_BASE/conf/carol.properties file to:
Choose the protocol through the carol.protocols property.
Change localhost to the hostname where registry will be run.
Change the standard port number.
If the standard port number is changed, registry must be run with this port number as the argument,
registryYour_Portnumber
, when the registry is not launched inside the JOnAS server.
Page 32
24 Chapter 3. JOnAS Configuration
You can configure JOnAS to use several protocols simultaneously. To do this, just specify a comma­separated list of protocols in the carol.protocols property of the carol.properties file. For example:
# jonas rmi activation (choose from jrmp, iiop, and cmi) carol.protocols=jrmp,iiop
3.3.2. Security and Transaction Context Propagation
JOnAS implements EJB security and transactions by using the communication layer to propagate the security and transaction contexts across method calls. By default, the communication proto­col is configured for context propagation. However, this configuration can be changed by disabling the context propagation for security and/or transaction; this is done primarily to increase perfor­mance. The context propagation can be configured in the jonas.properties file by setting the
jonas.security.propagation and jonas.transaction.propagation properties to true or false:
# Enable the Security context propagation jonas.security.propagation true
# Enable the Transaction context propagation jonas.transaction.propagation true
3.3.3. Multi-protocol Deployment (GenIC)
The JOnAS deployment tool (GenIC) must be told which protocol stubs (for remote invocation) are to be generated. Choosing several protocols will eliminate the need to redeploy the EJBs when switching from one protocol to another. The default is that GenIC generates stubs for rmi/jrmp. To change this configuration, call GenIC as described in Section 6.5 GenIC. Use the -protocols option to specify a comma-separated list of protocols (chosen from jrmp, iiop, and cmi). For example:
GenIC -protocols jrmp,iiop
This list of protocols can also be specified for Ant EJB tasks (refer to Chapter 27 Ant EJB Tasks: Using EJB-JAR):
jonas destdir="${dist.ejbjars.dir}"
jonasroot="${jonas.root}" protocols="jrmp,iiop" keepgenerated="true" verbose="${verbose}" mappernames="${mapper.names}" additionalargs="${genicargs}"
/jonas
3.4. Configuring Logging System (monolog)
The logging system is based on Monolog, the standard API for ObjectWeb projects (refer to http://www.objectweb.org/monolog/doc/index.html). Configuring trace messages inside Jonas can be done in two ways:
Page 33
Chapter 3. JOnAS Configuration 25
Changing the trace.properties file to configure the traces statically, before the JOnAS Server
is run (refer to $JONAS_BASE/conf/trace.properties).
Using the jonas admin command (refer to Section 6.1 jonas) to configure the traces dynamically
while the JOnAS Server is running.
Note
The SQL requests sent to a database can be easily traced using the JOnAS Logging system and the integrated P6Spy tool. The configuration steps are described in Chapter 4 Configuring JDBC DataSources.
3.4.1. trace.properties Syntax
A standard file is provided in $JONAS_ROOT/conf/trace.properties (refer to
$JONAS_BASE/conf/trace.properties). Use the CLASSPATH to retrieve this file.
The monolog documentation described in http://www.objectweb.org/monolog/doc/index.html pro­vides more details about how to configure logging. Monolog is built over astandard log API (currently,
log4j). Loggers can be defined, each one being backed on a handler.
A handler represents an output, is identified by its name, has a type, and has some additional properties. Two handlers have been defined in the trace.properties file (refer to
$JONAS_BASE/conf/trace.properties):
tty is basic, standard output on a console, with no headers.
logf is a handler for printing messages on a file.
Each handler can define the header it will use, the type of logging (console, file, rolling file), and the file name.
Note that if the tag automatic is specified as the output filename, JOnAS will replace this tag with a file pointing to $JONAS_BASE/logs/
The logf handler, which is bundled with JOnAS, uses this automatic tag.
Loggers are identified by names that are structured as a tree. The root of the tree is named root.
Each logger is a topical logger (that is, it is associated with a topic). Topic names are usually based on the package name. Each logger can define the handler it will use and the trace level among the following four values:
jonas_name_server-timestamp.log.
ERROR errors. Should always be printed.
WARN warning. Should be printed.
INFO informative messages, not typically used in Jonas (for example, test results).
DEBUG debug messages. Should be printed only for debugging.
If nothing has been defined for a logger, it will use the properties defined for its parent.
JOnAS code is written using the monolog API and can use the tty handler.
Page 34
26 Chapter 3. JOnAS Configuration
3.4.1.1. Example: Setting the DEBUG Level
To set the DEBUG level for the logger used in the jonas_ejb module:
logger.org.objectweb.jonas_ejb.level DEBUG
3.4.1.2. Example: Setting the Output Traces to the Console and a File
To set the output of JOnAS traces to both the console and a file named /tmp/jonas/log:
handler.logf.output /tmp/jonas.log logger.org.objectweb.jonas.handler.0 tty logger.org.objectweb.jonas.handler.1 logf
3.4.1.3. Example: Setting the Output Trace to a File
To set the output of JOnAS traces to a file in the $JONAS_BASE/logs/ directory:
handler.logf.output automatic logger.org.objectweb.jonas.handler.0 logf
3.5. Configuring JOnAS Services
JOnAS may be viewed as a number of manageable built-in services started at server launching time. JOnAS is also able to launch external services, which can be defined as explained in Chapter 24 JOnAS Services.
The following is a list of the JOnAS built-in services:
registry
The registry binds remote objects and resources that will later be accessed via JNDI. It is automatically launched before all the other services when starting JOnAS.
jmx
The jmx service enables you to administer the JOnAS servers and the JOnAS services via a JMX-based administration console. jmx launches automatically.
JOnAS uses MX4J (refer to http://mx4j.sourceforge.net/).
jtm
The Transaction Manager service is used for the support of distributed transactions. This is the only mandatory service for JOnAS.
dbm
The database service is required by application components that need to access relational databases.
resource
The resource service is needed for access to Resource Adapters conformant to the J2EE Con­nector Architecture Specification.
Page 35
Chapter 3. JOnAS Configuration 27
jms
As of the 4.1 release, a JMS provider can be integrated through the deployment of a resource adapter.
security
The security service enforces security at runtime.
ear
The EAR service provides support for J2EE applications.
mail
The Mail service is required by e-mail applications.
ejb
The EJB Container service provides support for EJB application components.
web
The WEB Container service provides support for web components (as servlets and JSP). At this time JOnAS provides an implementation of this service for Tomcat.
ws
The WebServices service provides support for WebServices (WSDL publication).
The services available in a JOnAS server are those specified in the JOnAS configuration file. The
jonas.services property in the jonas.properties file must contain a list of the required service
names. Currently, these services are started in the order in which they appear in the list. Therefore, the following constraints should be considered:
jmx must precede all other services in the list (except registry) in order to allow the management
of these services.
jtm must precede the dbm, resource, and jms services.
security must be after dbm, as it uses datasources.
The services used by the application components must be listed before the container service used to
deploy these components. For example, if the application contains EJBs that need database access,
dbm must precede ejb in the list of required services.
Example:
jonas.services registry,jmx,jtm,dbm,security,resource,jms,mail,ejb,ws,web,ear
The registry can be omitted from the list because this service is automatically launched if it is not already activated by another previously started server. This is also true for jmx, since, beginning with JOnAS 3.1, this service is automatically launched after the registry.
The dbm, resource, and jms services are listed after the jtm.
The application components deployed on this server can use Java Messaging and Java Mail because
jms and mail are listed before ejb.
Configuration parameters for services are located in the jonas.properties file. They must follow the strict naming convention that a service XX will be configured via a set of properties:
jonas.service.XX.foo something jonas.service.XX.bar else
Page 36
28 Chapter 3. JOnAS Configuration
3.5.1. Configuring the Registry Service
The registry service is used for accessing the RMI registry, CMI registry, or CosNaming (iiop), depending on the configuration of communication protocols specified in carol.properties. (refer to Section 3.3 Configuring the Communication Protocol and JNDI.)
There are several Registry-launching modes based on the value of the JOnAS property
jonas.service.registry.mode. The possible values of this property are:
automatic
The Registry is launched in the same JVM as JOnAS Server, if not already started. This is the default value.
collocated
The Registry is launched in the same JVM as the JOnAS Server.
remote
The Registry must be launched before the JOnAS Server in a separate JVM. (Refer to Section
6.4 registry.)
The port number on which the Registry is launched is defined in the carol.properties file.
3.5.2. Configuring the EJB Container Service
The EJB Container service is the primary JOnAS service. It provides EJB containers for EJB compo­nents.
You can create an EJB container from an EJB-JAR file in the following ways:
The corresponding EJB-JAR file name is listed in the jonas.service.ejb.descriptors prop-
erty in the jonas.properties file. If the file name does not contain an absolute path, it should be located in the $JONAS_BASE/ejbjars/ directory. The container is created when the JOnAS server starts.
Example:
jonas.service.ejb.descriptors Bank.jar
In this example the Container service creates a container from the EJB-JAR file named Bank.jar. JOnAS will search for this file in the $JONAS_BASE/ejbjars/ directory.
To automatically create an EJB container at server start-up time, place the EJB-JAR
files in an autoload directory. The name of this directory is specified using the
jonas.service.ejb.autoloaddir property in the jonas.properties file.
JOnAS also allows for loading unpacked EJB components. The name of the xml file containing the EJB’s deployment descriptor must be listed in the jonas.service.ejb.descriptors property. Note that the JOnAS server must have access to the component’s classes, which may be achieved using the XTRA_CLASSPATH environment variable (refer to Chapter 5 JOnAS Class Loader Hierarchy).
3.5.3. Configuring the WEB Container Service
The WEB Container service provides WEB containers for the WEB components used in the J2EE applications. JOnAS provides an implementation of the WEB Container service for Tomcat 5.0.x.
A WEB container is created from a WAR file. If the file name does not contain an absolute path name, it must be located in the $JONAS_BASE/webapps/ directory.
Page 37
Chapter 3. JOnAS Configuration 29
JOnAS can create WEB containers when the JOnAS server starts by providing the corresponding file names via the jonas.service.web.descriptors property in the jonas.properties file.
Example:
jonas.service.web.descriptors Bank.war
In this example the WEB Container service creates a container from the WAR file named Bank.war. It searches for this file in the $JONAS_BASE/webapps/ directory.
By using webapp directories instead of packaging a new WAR file each time, you can improve the development process. You can replace the classes with the new compiled classes, reload the servlets in your browser, and immediately see the changes. This is also true for the JSPs. Note that these reload features can be disabled in the configuration of the Tomcat web container at production time.
Example of using the jonasAdmin/ webapp directory instead of jonasAdmin.war.
1. In the JONAS_BASE/webapps/autoload directory, create a directory (for example,
jonasAdmin): JONAS_BASE/webapps/autoload/jonasAdmin
2. Move the jonasAdmin.war file to this directory.
3. Unpack the WAR file to the current directory, then remove the WAR file.
4. At the next JOnAS startup, the webapp directory is used instead of the WAR file. Change the JSP and see the changes at the same time.
3.5.4. Configuring the WebServices Service
3.5.4.1. A. Choose a Web Service Engine
At this time, only one implementation for WebServices is available: the Axis implementation. But in the future, a Glue implementation can be made easily.
In jonas.properties:
#... # the fully qualifier name of the service class jonas.service.ws.class org.objectweb.jonas.ws.AxisWSServiceImpl #...
3.5.4.2. B. Choose One or More WSDL Handler(s)
WSDL Handlers are used to locate and publish all your WSDL documents. You can use several WSDL Handlers as long as you define them in the jonas.properties file.
Example:
If you want to publish a WSDL into the local file system, use the FileWSDLHandler
In jonas.properties:
#... # a list of comma separated WSDL Handlers
jonas.service.ws.wsdlhandlers file1
# Configuration of the file WSDL Handler
jonas.service.ws.file1.type file
# Make sure users who run JOnAS have read/write access in this directory
jonas.service.ws.file1.location /path/to/directory/where/store/wsdls
#...
Page 38
30 Chapter 3. JOnAS Configuration
3.5.5. Configuring the EAR Service
The EAR service allows deployment of complete J2EE applications (including both EJB-JAR and WAR files packed in an EAR file). This service is based on the WEB container service and the
EJB container service. The WEB container service is used to deploy the WARs included
in the J2EE application; the EJB container service is used to deploy the EJB containers for the EJB­JARs included in the J2EE application.
This service may be configured by setting the jonas.service.ear.descriptors property in
jonas.properties file. This property provides a list of ears that must be deployed when JOnAS
is launched.
When using relative paths for EAR file names, the files should be located in the $JONAS_BASE/apps/ directory.
Example:
jonas.service.ear.descriptors Bank.ear
In this example the EAR service will deploy the EAR file named Bank.ear. It will search for this file in the $JONAS_BASE/apps/ directory.
3.5.6. Configuring the Transaction Service
The Transaction service is used by the Container service in order to provide transaction management for EJB components as defined in the deployment descriptor. This is a mandatory service.
The Transaction service uses a Transaction manager that may be local or may be launched in another JVM (a remote Transaction manager). Typically, when there are several JOnAS servers working to­gether, one Transaction service must be considered as the master and the others as slaves. The slaves must be configured as if they were working with a remote Transaction manager.
The following is an example of the configuration for two servers: one named TM in which a standalone Transaction service will be run, one named EJB that will be used to deploy an EJB container:
jonas.name TM jonas.services jtm jonas.service.jtm.remote false
and
jonas.name EJB jonas.services jmx,security,jtm,dbm,ejb jonas.service.jtm.remote true jonas.service.ejb.descriptors foo.jar
Another possible configuration option is the value of the transaction time-out, in seconds, via the
jonas.service.jtm.timeout property.
The following is the default configuration:
jonas.service.jtm.timeout 60
Page 39
Chapter 3. JOnAS Configuration 31
3.5.7. Configuring the Database Service
Note
The description of the new JDBC Resource Adapters as a replacement for the database service is located in Chapter 40 Configuring JDBC Resource Adapters.
To allow access to one or more relational databases (for example, Oracle, PostgreSQL, and so on), JOnAS will create and use DataSource objects. Such a DataSource object must be configured accord­ing to the database that will be used for the persistence of a bean. More details about DataSource objects and their configuration are provided in Chapter 4 Configuring JDBC DataSources.
The following subsections briefly explain how to configure a DataSource object for your database in order to be able to run the Entity Bean example.
Note that the SQL requests sent to the database can be easily traced using the JOnAS Logging system and the integrated P6Spy tool. The configuration steps are described in Section 4.4 Tracing SQL Requests Through P6Spy.
3.5.7.1. Configuring Oracle for the Supplied Example
You can find a template Oracle1.properties file in the installation directory (refer to
$JONAS_BASE/conf/Oracle1.properties). This file is used to define a DataSource object
that is named Oracle1. This template must be updated with values appropriate to your installation. The fields are the following:
datasource.name JNDI name of the DataSource: The name used in the example is jdbc_1.
datasource.url The JDBC database URL: for the Oracle JDBC "Thin" driver it is
datasource.classname Name of the class implementing the Oracle JDBC driver:
datasource.mapper Adapter (JORM), mandatory for CMP2.0 only (more details in Section 4.2
datasource.username Database user name
datasource.password Database user password
jdbc:oracle:thin:@hostname:sql*net_port_number:ORACLE_SID If using an Oracle OCI JDBC driver, the URL is jdbc:oracle:oci7: or
jdbc:oracle:oci8:
oracle.jdbc.driver.OracleDriver
CMP2.0/JORM): rdb.oracle8 for Oracle 8 and prior versions
For the EJB platform to create the corresponding DataSource object, the Oracle1 name must be in the jonas.properties file on the jonas.service.dbm.datasources line:
jonas.service.dbm.datasources Oracle1
There may be several DataSource objects defined for an EJB server, in which case there will be several dataSourceName.properties files and a list of the DataSource names on the
jonas.service.dbm.datasources line of the jonas.properties file:
jonas.service.dbm.datasources Oracle1, Oracle2
To create the table used in the example with the SQL script that is provided in the
examples/src/eb/Account.sql file, the Oracle server must be running with a JDBC
Page 40
32 Chapter 3. JOnAS Configuration
driver installed. (Oracle JDBC drivers can be downloaded from Oracle’s web site: http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html)
For example:
sqlplus user/passwd
@Account.sql
SQL
SQLquit
The JDBC driver classes must be accessible from the classpath. To do this, update the config_env file $JONAS_ROOT/bin/unix/config_env.
3.5.7.2. Configuring Other Databases
The same type of process can be used for other databases. A template of datasource for PostgreSQL and for InterBase is supplied with JOnAS. Although many other databases are currently used by the JOnAS users (for example, Informix, Sybase, SQL Server), not all JDBC drivers have been tested against JOnAS.
3.5.8. Configuring the Security Service
The Security service is used by the Container service to provide security for EJB components. The
Container service provides security in two forms: declarative security and programmatic secu-
rity. The Security service uses security roles and method permissions located in the EJB deployment descriptor.
Note that:
JOnAS relies on Tomcat (http://jakarta.apache.org/tomcat) for the identification of the web clients.
The Java clients use the JAAS login modules for the identification. JOnAS performs the user au­thentication.
In the $JONAS_ROOT/conf/jonas-realm.xml file you can define three types of Realm for JOnAS:
Memory realm: users, groups, and roles are written in the file in the section
jonas-memoryrealm
Datasource realm: users, groups, and roles information is stored in a database; the configura-
tion for accessing a specific datasource is described in the section
$JONAS_ROOT/conf/jonas-realm.xml file.
The configuration requires the name of the datasource, the tables used, and the names of the columns.
LDAP realm: users, groups, and roles information is stored in an LDAP directory. This is de-
scribed in the section file.
There are some optional parameters. If they are not specified, some of the parameters are set to a default value. That is, if the providerUrl element is not set, the default value is
ldap://localhost:389.
Edit the jonas-realm_1_0.dtd DTD file to see the default values.
For Tomcat, use the realm: org.objectweb.jonas.security.realm.web.catalina50.JACC
These realms require as an argument the name of the resource to be used for the authentication. This is the name that is in the jonas-realm.xml file.
of the $JONAS_ROOT/conf/jonas-realm.xml file.
jonas-ldaprealm
of the $JONAS_ROOT/conf/jonas-realm.xml
jonas-dsrealm
of the
Page 41
Chapter 3. JOnAS Configuration 33
There is no mapping for the security between JOnAS and the target operational environment. More
specifically, the roles defined for JOnAS cannot be mapped to roles of the target operational envi­ronment (for example, groups).
There is one property in the jonas.properties file for configuring the security service: the
jonas.security.propagation property should be set to true (which is the default value) to
allow the security context to propagate across method calls. Refer to Section 3.3.2 Security and Transaction Context Propagation.
3.5.8.1. Using Web Container Tomcat 5.0.x Interceptors for Authentication
With Tomcat 5.0.x, go to the $JONAS_ROOT/conf/server.xml file, the
$JONAS_BASE/conf/server.xml file, the $CATALINA_HOME/conf/server.xml file, or the $CATALINA_BASE/conf/server.xml file and replace the following line:
Realm className="org.objectweb.jonas.security.realm.web.catalina50.JACC"
debug="99" resourceName="memrlm_1"/
with this line:
Realm className="org.objectweb.jonas.security.realm.JRealmCatalina41" \
debug="0" resourceName="memrlm_1" /
A memory, Datasource, or LDAP resource can be used for the authentication, with the correct name of the specified resource as resourceName that is: memrlm_1, memrlm_2, dsrlm_1, ldaprlm_1, etc.
3.5.8.2. Configuring Mapping Principal/Roles
JOnAS relies on the jonas-realm.xml file for access control to the methods of EJB components (refer to $JONAS_BASE/conf/jonas-realm.xml).
Example of a secured bean with the role jonas:
assembly-descriptor
security-role
role-namejonas/role-name
/security-role
method-permission
role-namejonas/role-name
method
ejb-nameBean/ejb-name
method-name*/method-name
/method
/method-permission ... ...
/assembly-descriptor
The following subsections describe how to configure the different resources for performing authen­tication if it is necessary to add a user that has the specified role (jonas) and is authorized to call methods, etc.
Page 42
34 Chapter 3. JOnAS Configuration
3.5.8.2.1. Configuring a Memory Resource in the jonas-realm.xml File
To add the role ’jonas’, place this example role in the
roles
role name="jonas" description="Role used in
the sample security howto" /
/roles
Then, add a user with the specified role. Add a user with the ’jonas’ role in the
users
user name="jonas_user" password="jonas_password" roles="jonas" /
/users
The
groups
section permits grouping roles. Add the memory resource in the jonas-realm.xml
roles
section:
users
section:
file:
jonas-memoryrealm
[...]
memoryrealm name="howto_memory_1"
roles
role name="jonas" description="Role used in
the sample security howto" /
/memoryrealm
[...]
/jonas-memoryrealm
/roles
users
user name="jonas_user" password="jonas_password" roles="jonas" /
/users
3.5.8.2.2. Configuring a Datasource Resource in the jonas-realm.xml File
First, build the tables in which the users and roles will be stored.
Example of tables :
realm_users: Add a user jonas_user with the password jonas_password
... ...
jonas_user jonas_password
... ...
Note that the table can contain more than two columns.
realm_roles: Add the role jonas to the user jonas_user
... ...
jonas_user jonas
... ...
Now, declare the resource in the jonas-realm.xml file.
The dsName element describes the JNDI name of the datasource to use. Thus, a Datasource configu­ration with the right JNDI name for the dbm service must be set in the jonas.properties file.
The datasource resource to add in the jonas-realm.xml file is:
jonas-dsrealm
[...]
Page 43
Chapter 3. JOnAS Configuration 35
dsrealm name="howto_datasource_realm1"
dsName="jdbc_1" userTable="realm_users" userTableUsernameCol="user_name"
userTablePasswordCol="user_pass"
roleTable="realm_roles" roleTableUsernameCol="user_name"
roleTableRolenameCol="role_name"
/
[...]
/jonas-dsrealm
3.5.8.2.3. Configuring an LDAP Resource in the jonas-realm.xml File
The user is added in the LDAP server. In this case, all the users are on the
ou=people,dc=jonas,dc=objectweb,dc=org DN.
For example, for the user jonas_user the unique name will be: DN
uid=jonas_user,ou=people,dc=jonas,dc=objectweb,dc=org
The role jonas will be added on the ou=groups,dc=jonas,dc=objectweb,dc=org DN. In this case: DN cn=jaas,ou=groups,dc=jonas,dc=objectweb,dc=org
The user is added to the role by adding a field uniquemember to the role: uniquemember =
uid=jonas,ou=people,dc=jonas,dc=objectweb,dc=org
LDIF format for the user:
# jonas_user, people, jonas, objectweb, org dn: uid=jonas_user,ou=people,dc=jonas,dc=objectweb,dc=org objectClass: inetOrgPerson uid: jonas_user sn: jonas_user cn: JOnAS user userPassword:: jonas_password
LDIF format for the role:
# jonas, groups, jonas, objectweb, org dn: cn=jonas,ou=groups,dc=jonas,dc=objectweb,dc=org objectClass: groupOfUniqueNames uniqueMember: uid=jonas_user,ou=people,dc=jonas,dc=objectweb,dc=org cn: jonas
Now the jonas-realm.xml file can be customized by adding a LDAP resource.
There are two authentication methods:
The bind method (default): In order to check the access rights, the resource attempts to login to the
LDAP server with the given username and password.
The compare method: The resource retrieves the password of the user from the LDAP server and
compares this password to the password given by the user.
Note
The compare method requires the admin roles in the configuration in order to read the user pass­words.
Page 44
36 Chapter 3. JOnAS Configuration
All the elements of the configuration for the LDAP resource can be found in the
jonas-realm_1_0.dtd DTD file (refer to http://jonas.objectweb.org/current/xml/jonas-
realm_1_0.dtd).
For this sample, it is assumed that the LDAP server is on the same computer and is on the default port (389). It takes all the default values of the DTD.
The datasource resource to add in the jonas-realm.xml file is:
jonas-ldaprealm
[...]
ldaprealm name="howto_ldap_realm1"
[...]
/jonas-ldaprealm
baseDN="dc=jonas,dc=objectweb,dc=org" /
3.5.8.3. Configuring Client Authentication Based on the Client Certificate in the Web Container
3.5.8.3.1. Introduction
In order to set up the client authentication based on client certificate in a Web container, do the fol­lowing:
1. Configure the Realm the Web container will have to use.
2. Configure an SSL listener on the Web container.
3. Configure the Web application to make it ask a client certificate.
4. Configure the JAAS LoginModules.
5. Populate the Realm access list.
It is mandatory to possess a X.509 certificate for your Web container on each external interface (IP address) that accepts secure connections. This one can be digitally signed by a Certification Authority or can be autosigned.
3.5.8.3.2. Step 1: Configure the Realm the Web Container Uses
With Tomcat 5.0.x, in the $JONAS_ROOT/conf/server.xml file, the
$JONAS_BASE/conf/server.xml file, the $CATALINA_HOME/conf/server.xml file, or the $CATALINA_BASE/conf/server.xml file, replace the current Realm by the following:
Realm
className="org.objectweb.jonas.security.realm.web.catalina50.JAAS" /
The class specified uses the JAAS model to authenticate the users. Thus, to choose the resource in which to look for authentication data, configure JAAS.
3.5.8.3.3. Step 2: Configure an SSL Listener on the Web Container
Uncomment the following section in the server.xml file:
Connector className="org.apache.catalina.connector.http.HttpConnector"
port="9043" minProcessors="5" maxProcessors="75" enableLookups="true"
Page 45
Chapter 3. JOnAS Configuration 37
acceptCount="10" debug="0" scheme="https" secure="true"
Factory className="org.apache.catalina.net.SSLServerSocketFactory"
clientAuth="false" protocol="TLS"/
/Connector
Important
Set the clientAuth parameter to false, otherwise all Web applications will request a client certificate if they need SSL. The client authentication will be configured later in the web.xml file in the specific WAR files.
For more information, refer to http://jakarta.apache.org/tomcat/tomcat-5.0-doc/ssl-howto.html.
3.5.8.3.4. Step 3: Configure your Web Application to Request a Client Certificate
Add the following lines to the web.xml file of the WAR file of the Web application:
login-config
auth-methodCLIENT-CERT/auth-method
realm-nameExample Authentication Area/realm-name
/login-config
Important
Ensure that the restricted Web application area is configured in the web.xml file in the WAR file
with a security-constraint declaration.
Ensure that the Web application is always accessed with SSL, unless the Web container will not
get a certificate and will not be able to authenticate the user.
When authentication is enabled on client certificate, the user’s Web browser receives the list of the
Certification Authorities trusted by your Web application. A connection will be established with the client only if it has a certificate issued by a trusted Certification Authority, otherwise its cer tificate will be rejected.
The cer tificates of all the trusted Certification Authorities must be imported in the
$JAVA_HOME/jre/lib/security/cac erts keystore file (customize the SSL listener to modify this
location).
3.5.8.3.5. Step 4: Configure the JAAS LoginModules
This authentication process is built on the JAAS technology. This means that authentication is per­formed in a pluggable way and the desired authentication technology is specified at runtime. There­fore, you must choose the LoginModules to use in your Web container to authenticate the users.
3.5.8.3.5.1. Choose the LoginModules
org.objectweb.jonas.security.auth.spi.JResourceLoginModule is the main
LoginModule. It is highly recommended that this be used in every authentication, as it verifies the user authentication information in the specified resource.
Page 46
38 Chapter 3. JOnAS Configuration
org.objectweb.jonas.security.auth.spi.JResourceLoginModule accepts the following
parameters:
resourceName: the name of the entry in the jonas-realm.xml file being used; this entry repre-
sents how and where the authentication information is stored. This is the only required parameter.
certCallback: Specify this optional parameter if you want this login module to ask for a cer-
tificate callback. By default it is set to false. When using JAAS realms with certificates, set it to
true.
org.objectweb.jonas.security.auth.spi.CRLLoginModule is the LoginModule that con-
tains authentication based on certificates. However, when enabled, it will also permit non-certificate based accesses. It verifies that the certificate presented by the user has not been revoked by the Certi­fication Authority that signed it. To use it, the directory in which to store the revocation lists (CRLs) files or a LDAP repository must exist.
org.objectweb.jonas.security.auth.spi.CRLLoginModule can take the following param-
eters:
CRLsResourceName: this parameter specifies how the CRLs are stored:
Directory: if the CRL files are stored in a directory on the machine, you must specify another
parameter pointing to that directory:
CRLsDirectoryName: the directory containing the CRL files (the extension for these files
must be .crl).
LDAP: This functionality is experimental if your CRL files are stored in a LDAP repository, two
additional parameters must be specified:
address: the address of the server that hosts the LDAP repository
port: the port used by the LDAP repository; CRLs are retrieved from an LDAP directory
using the LDAP schema defined in RFC 2587 (refer to http://www.ietf.org/rfc/rfc2587.txt).
3.5.8.3.5.2. Specify the Configuration Parameters
The JAAS configuration sits on a file in which the login module to use for authentication is described. This file is located in $JONAS_BASE/conf and named jaas.config. To change its location and name, edit the $JOANS_BASE/bin/jonas.sh script and modify the following line:
-Djava.security.auth.login.config=$JONAS_BASE/conf/jaas.config
The contents of the JAAS configuration file follow this structure:
Application_1 {
LoginModuleClassA Flag Options; LoginModuleClassB Flag Options;
LoginModuleClassC Flag Options; }; Application_2 {
LoginModuleClassB Flag Options;
LoginModuleClassC Flag Options; }; Other {
LoginModuleClassC Flag Options;
Page 47
Chapter 3. JOnAS Configuration 39
LoginModuleClassA Flag Options; };
Sample of a configuration file with a CRL directory:
tomcat {
org.objectweb.jonas.security.auth.spi.CRLLoginModule required
CRLsResourceName="Directory"
CRLsDirectoryName="path_to/CRLs";
org.objectweb.jonas.security.auth.spi.JResourceLoginModule
required
resourceName="memrlm_1"; };
There can be multiple entries in this file, specifying different configurations that JOnAS can use. The entry dedicated to Tomcat must be named tomcat. Note that everything in this file is case-sensitive.
There is a flag associated with all the LoginModules to configure their behavior in case of success or failure:
required: The LoginModule is required to succeed. If it succeeds or fails, authentication still
proceeds through the LoginModule list.
requisite: The LoginModule is required to succeed. If it succeeds, authentication continues
through the LoginModule list. If it fails, control immediately returns to the application (authen­tication does not proceed through the LoginModule list).
sufficient: The LoginModule is not required to succeed. If it does succeed, control immediately
returns to the application (authentication does not proceed through the LoginModule list). If it fails, authentication continues through the LoginModule list.
optimal: The LoginModule is not required to succeed. If it succeeds or fails, authentication still
proceeds through the LoginModule list.
3.5.8.3.6. Step 5: Populate the Realm Access List
Now, users will not have to enter a login/password. They will just present their certificates and au­thentication is performed transparently by the browser (after the user has imported the certificate into it). Therefore, the identity presented to the server is not a login, but a Distinguished Name: that is the name identifying the person to whom the certificate belongs.
This name has the following structure:
CN=Someone Unknown, OU=ObjectWeb, O=JOnAS, C=ORG
E : Email Address CN : Common Name OU : Organizational Unit O : Organization L : Locality ST : State or Province Name C : Country Name
The Subject in a certificate contains the main attributes and may include additional ones, such as Title, Street Address, Postal Code, Phone Number.
Previously in the jonas-realm.xml file a memory realm might contain:
user name="jps_admin" password="admin" roles="administrator"/
Page 48
40 Chapter 3. JOnAS Configuration
To enter a certificate-based user access, you must now enter the user’s DN preceded by the String:
##DN##, as shown in the following example:
user name="##DN##CN=whale, OU=ObjectWeb, O=JOnAS, L=JOnAS, ST=JOnAS,
C=ORG" password="" roles="jadmin" /
3.5.9. Configuring the JMS Service
Until JOnAS release 4.1, the only way to provide the JMS facilities was by setting a JMS service when configuring JOnAS. The JMS service is a default setting in the jonas.properties config file; however, this JMS service will not allow you to deploy 2.1 MDBs (Message Driven Beans), and will eventually become deprecated in later JOnAS versions.
The new way to integrate a JMS platform is by deploying a J2EE 1.4 compliant resource adapter. How you do this is described in Section 3.7 Configuring JMS Resource Adapters.
JOnAS integrates a third-party JMS implementation, JORAM (http://www.objectweb.org/joram/), which is the default JMS service. Other JMS providers, such as SwiftMQ (http://www.swiftmq.com/ and WebSphere MQ (http://www-3.ibm.com/software/integration/mqfamily/), can easily be integrated as JMS services.
The JMS service is used to contact (or launch) the corresponding MOM (Message Oriented Mid- dleware) or JMS server. You should create the JMS-administered objects used by the EJB com- ponents, such as the connection factories and the destinations, prior to the EJB execution, using the proprietary JMS implementation administration facilities. JOnAS provides “wrappers” on such JMS administration APIs, which enable the EJB server itself to perform simple administration operations automatically.
The JMS service is an optional service that must be started before the EJB container service.
The following are the properties that can be set in jonas.properties file for the JMS service:
jonas.service.jms.collocated for setting the JMS server launching mode. If set to true,
it is launched in the same JVM as the JOnAS Server (this is the default value). If set to false, it is launched in a separate JVM, in which case the jonas.service.jms.url must be set with the connection URL to the JMS server.
jonas.service.ejb.mdbthreadpoolsize is used for setting the default thread pool used for
Message Driven Beans (10 is the default value).
jonas.service.jms.queues and jonas.service.jms.topics are used for setting lists of
administered objects queues or topics at launching time.
jonas.service.jms.mom is used to indicate which class must be used to perform
administrative operations. This class is the wrapper to the actual JMS provider implementation. The default class is org.objectweb.jonas_jms.JmsAdminForJoram, which is required for JORAM (refer to http://joram.objectweb.org//). For the SwiftMQ product, obtain a
com.swiftmq.appserver.jonas.JmsAdminForSwiftMQ class from the SwiftMQ site
(http://www.swiftmq.com/).
Some additional information about JMS configuration (in particular, several JORAM advanced con­figuration aspects) is provided in Section 26.4 JMS Administration and Section 26.5 Running an EJB Performing JMS Operations.
Page 49
Chapter 3. JOnAS Configuration 41
3.5.10. Configuring the Resource Service
The Resource service is an optional service that must be started as soon as EJB components require access to an external Enterprise Information Systems. The standard way to do this is to use a third-party software component called a Resource Adapter.
The role of the Resource service is to deploy the Resource Adapters in the JOnAS server, (that is, configure it in the operational environment and, in JNDI name space, register a connection factory instance that can be looked up by the EJB components).
The Resource service can be configured in one of the following ways:
The corresponding RAR file name is listed in the jonas.service.resource.resources prop-
erty in jonas.properties file. If the file name does not contain an absolute path name, then it should be located in the $JONAS_BASE/rars/ directory.
Example:
jonas.service.resource.resources MyEIS
This file will be searched for in the $JONAS_BASE/rars/ directory. This property is a comma­separated list of resource adapter file names (the .rar suffix is optional).
Another way to automatically deploy resource adapter files at the server start-up is to
place the RAR files in an autoload directory. The name of this directory is specified using the jonas.service.resource.autoloaddir property in jonas.properties file. This directory is relative to the $JONAS_BASE/rars/ directory.
A jonas-specific, resource-adapter configuration xml file must be included in each resource adapter. This file replicates the values of all configuration properties declared in the deployment descriptor for the resource adapter. Refer to Section 25.2 Defining the JOnAS Connector Deployment Descriptor for additional information.
3.5.11. Configuring the JMX (Java Management Extension) Service
The JMX service is mandatory and will be started even if it is not present in the list of services. It is configured by choosing one of the two supported JMX implementations, SUN RI or MX4J. The choice is made based on the value of the jonas.service.jmx.class property in the JOnAS configuration file. The two possible values are:
org.objectweb.jonas.jmx.sunri.JmxServiceImpl, for SUN RI
org.objectweb.jonas.jmx.mx4j.Mx4jJmxServiceImpl, for MX4J
3.5.12. Configuring the Mail Service
The Mail service is an optional service that can be used to send email. It is based on JavaMail and on the JavaBeans Activation Framework (JAF) API (refer to http://java.sun.com/products/javamail/ and http://java.sun.com/products/beans/glasgow/jaf.html respectively).
A mail factory is required in order to send or receive mail. JOnAS provides two types of mail factories:
javax.mail.Session and javax.mail.internet.MimePartDataSource.
MimePartDataSource factories allow mail to be sent with a subject and the recipients already set.
Mail factory objects must be configured accordingly to their type. The subsections that follow briefly describe how to configure Session and MimePartDataSource mail factory objects, in order to run the SessionMailer SessionBean and the MimePartDSMailer SessionBean delivered with the platform.
Page 50
42 Chapter 3. JOnAS Configuration
3.5.12.1. Configuring a Session Mail Factory
The template MailSession1.properties file supplied in the installation directory defines a mail factory of type Session. The JNDI name of the mail factory object is mailSession_1. This template must be updated with values appropriate to your installation.
Refer to $JONAS_BASE/conf/MailSession1.properties for a sample of the file and Section
3.5.12.4 Configuring a Mail Factory for the list of available properties.
3.5.12.2. Configuring MimePartDataSource Mail Factory
The template MailMimePartDS1.properties file supplied in the installation directory defines a mail factory of MimePartDSMailer type. The JNDI name of the mail factory object is
mailMimePartDS_1. This template must be updated with values appropriate to your installation.
Refer to $JONAS_BASE/conf/MailMimePartDS1.propertiesfor a sample of the file and Section
3.5.12.4 Configuring a Mail Factory for a list of the available properties.
3.5.12.3. Configuring JOnAS for a Mail Factory
Mail factory objects created by JOnAS must be given a name. In the mailsb example, two factories called MailSession1 and MailMimePartDS1 are defined.
Each factory must have a configuration file whose name is the name of the factory with the
.properties extension (MailSession1.properties for the MailSession1 factory).
Additionally, the jonas.properties file must define the jonas.service.mail.factories property. For this example, it is:
jonas.service.mail.factories MailSession1,MailMimePartDS1
3.5.12.4. Configuring a Mail Factory
A mail factory has the following required properties:
mail.factory.name JNDI name of the mail factory
mail.factory.type The type of the factory. This property can be
javax.mail.Session or javax.mail.internet.MimePartDataSource.
Table 3-1. Required properties
A mail factory has the following optional authentication properties:
mail.authentication.username Set the username for the authentication.
mail.authentication.password Set the password for the authentication.
Table 3-2. Optional Authentication properties
The javax.mail.Session.properties file has the properties:
Page 51
Chapter 3. JOnAS Configuration 43
mail.authentication.username Set the username for the authentication.
mail.authentication.password Set the password for the authentication.
mail.debug The initial debug mode. Default is false.
mail.from The return email address of the current user, used by the
InternetAddress method getLocalAddress.
mail.mime.address.strict The MimeMessage class uses the InternetAddress method
parseHeader to parse headers in messages. This property
controls the strict flag passed to the parseHeader method. The default is true.
mail.host The default host name of the mail server for both Stores and
Transports. Used if the mail.protocol.host property is not set.
mail.store.protocol Specifies the default message access protocol. The Session
method getStore() returns a Store object that implements this protocol. By default the first Store provider in the configuration files is returned.
mail.transport.protocol Specifies the default message access protocol. The Session
method getTransport() returns a Transport object that implements this protocol. By default, the first Transport provider in the configuration files is returned.
mail.user The default user name to use when connecting to the mail server.
Used if the mail.protocol.user property is not set.
mail.protocol.class Specifies the fully- qualified class name of the provider for the
specified protocol. Used in cases where more than one provider for a given protocol exists; this property can be used to specify which provider to use by default. The provider must still be listed in a configuration file.
mail.protocol.host The host name of the mail server for the specified protocol.
Overrides the mail.host property.
mail.protocol.port The port number of the mail server for the specified protocol. If it
is not specified, the protocol’s default port number is used.
mail.protocol.user The user name to use when connecting to mail servers using the
specified protocol. Overrides the mail.user property.
Table 3-3. javax.mail.Session.properties
(Refer to JavaMail documentation at http://java.sun.com/products/javamail/1.3/docs/javadocs/overview­summary.html for more information.)
mail.to Set the list of primary recipients (“to”) of the message.
mail.cc Set the list of Carbon Copy recipients (“cc”) of the message.
mail.bcc Set the list of Blind Carbon Copy recipients (“bcc”) of the message.
mail.subject Set the subject of the message.
Table 3-4. MimePartDataSource properties (used only if mail.factory.type is javax.mail.internet.MimePartDataSource)
Page 52
44 Chapter 3. JOnAS Configuration
3.6. Configuring the DB Service (hsql)
The DB service is an optional service that can be used to start a Java database server in the same JVM as JOnAS.
The listening port and the database name can be set as follows:
jonas.service.db.port 9001 jonas.service.db.dbname db_jonas
You can use the $JONAS_ROOT/conf/HSQL1.properties file with these default values.
The users are declared as follows:
jonas.service.db.user<1..n> login:password
For example, to give access to this database to the user jonas with the password jonas, use:
jonas.service.db.user1 jonas:jonas
This login and this password (jonas/jonas) are used in the HSQL1.properties file.
3.7. Configuring JMS Resource Adapters
Instead of using the JOnAS "JMS Service" for configuring a JMS platform, it is possible to use the JOnAS "Resource Service" and JMS adapters that are compliant with the J2EE Connector Architec­ture specification. The provided functionalities are the same, with the extra benefit of allowing the deployment of 2.1 MDBs.
JMS connections are obtained from a JMS Resource Adapter (RA), which is configured to identify a JMS server and access it. Multiple JMS RAs can be deployed, either via the jonas.properties file, or via the JonasAdmin tool, or included in the autoload directory of the resource service. For complete information about RAs in JOnAS, refer to Chapter 25 JOnAS and the Connector Architec- ture.
3.7.1. JORAM Resource Adapter
This section describes how JMS Resource Adapters should be configured to provide messaging func­tionalities to JOnAS components and applications.
The JORAM resource adapter archive (joram_for_jonas_ra.rar) is provided with the JOnAS distribution. It can be found in the $JONAS_ROOT/rars directory. To deploy it, you can declare the archive file in the jonas.properties file as follows:
jonas.service.resource.resources joram_for_jonas_ra
jms must be removed from the list of services:
jonas.services registry,jmx,jtm,dbm,security,resource,ejb,web,ear
The archive can also be deployed by putting it in the JOnAS rars/autoload directory.
The JORAM RA may be seen as the central authority to go through for connecting and using a JORAM platform. The RA is provided with a default deployment configuration that:
Starts a collocated JORAM server in non-persistent mode, with id 0 and name s0, on host
localhost and using port 16010; for doing so it relies on an a3servers.xml file located in the $JONAS_ROOT/conf directory.
Page 53
Chapter 3. JOnAS Configuration 45
Creates managed JMS ConnectionFactory instances and binds them with the names CF, QCF,
and TCF.
Creates administered objects for this server (JMS destinations and non-managed factories) as de-
scribed by the joram-admin.cfg file, located in the $JONAS_ROOT/conf directory; those objects are bound with the names sampleQueue, sampleTopic, JCF, JQCF, and JTCF
This default behavior is strictly equivalent to the default JMS service’s behavior.
Of course, you can modify the default configuration.
3.7.1.1. Configuring the JORAM Adapter
jonas-ra.xml is the JOnAS specific deployment descriptor that configures the JORAM adapter.
Changing the configuration of the RA requires you to extract the deployment descriptor, edit it, and update the archive file. The RAConfig utility is provided for doing this (refer to Section 6.7 RAConfig for a complete description). To extract the jonas-ra.xml file, use:
RAConfig joram_for_jonas_ra.rar
Then, to update the archive, use:
RAConfig -u jonas-ra.xml joram_for_jonas_ra.rar
The jonas-ra.xml file sets the central configuration of the adapter, defines and sets managed con­nection factories for outbound communication, and defines a listener for inbound communication.
The following properties are related to the central configuration of the adapter:
Property Name Description Possible Values
CollocatedServer Running mode of the
JORAM server to which the adapter gives access.
True: when deploying, the adapter starts a collocated JORAM server. False: when deploying, the adapter con­nects to a remote JORAM server.
PlatformConfigDir Directory where the
a3servers.xml and joram-admin.cfg files
are located.
PersistentPlatform Persistence mode of the
collocated JORAM server (not taken into account if the JORAM server is set as non collocated).
Nothing (default True value is then set).
Any String describing an absolute path (for example: /myHome/myJonasRoot/conf). Empty String, files will be searched in
$JONAS_ROOT/conf.
Nothing (default empty string is then set).
True: starts a persistent JORAM server. False: starts a non-persistent JORAM server.
Nothing (default False value is then set).
Page 54
46 Chapter 3. JOnAS Configuration
Property Name Description Possible Values
ServerId Identifier of the JORAM
server to start (not taken into account if the JORAM server is set as
Identifier corresponding to the server to start described in the a3servers.xml file (ex: 1). Nothing (default 0 value is then set).
non collocated).
ServerName Name of the JORAM
server to start (not taken into account if the JORAM server is set as
Name corresponding to the server to start described in the a3servers.xml file (ex: s1). Nothing (default s0 name is then set).
non collocated).
AdminFile Name of the file
describing the administration tasks to
Name of the file (ex: myAdminFile.cfg). Nothing (default joram-admin.cfg name is
then set). perform; if the file does not exist, or is not found, no administration task is performed.
HostName Name of the host where
the JORAM server runs, used for accessing a
Any host name (ex: myHost).
Nothing (default localhost name is then
set). remote JORAM server (non collocated mode), and for building appropriate connection factories.
ServerPort Port the JORAM server is
listening on, used for
Any port value (ex: 16030).
Nothing (default 16010 value is then set). accessing a remote JORAM server (non collocated mode), and for building appropriate connection factories.
Table 3-5. Adapter Configuration Properties
The jonas-connection-definition tags wrap properties related to the managed connection fac­tories:
Property Name Description Possible Values
jndi-name Name used for binding the
constructed connection factory.
UserName Default user name that will be
used for opening JMS connections.
Any name (such as myQueueConnectionFactory).
Any name (such as myName). Nothing (default anonymous name will be set).
Page 55
Chapter 3. JOnAS Configuration 47
Property Name Description Possible Values
UserPassword Default user password that will
be used for opening JMS connections.
Any name (such as myPass). Nothing (default anonymous password will be set).
Collocated Specifies if the connections that
will be created from the factory should be TCP or local-optimized connections
True (for building local-optimized connections). False (for building TCP con-
nections). (the collocated mode can only be set if the JORAM server is collocated; such factories will
Nothing (default TCP mode
will be set). only be usable from within JOnAS).
Table 3-6. jonas-connection-definition Tags
The jonas-activationspec tag wraps a property related to inbound messaging:
Property Name Description Possible Values
jndi-name Binding name of a JORAM
object to be used by 2.1 MDBs.
Any name (such as joramActivationSpec).
Table 3-7. jonas-activationspec Tag
3.7.1.2. Configuring a Collocated JORAM Server
The a3servers.xml file describes a JORAM platform configuration and is used by a starting JO­RAM server (thus, it is never used if JORAM is in non-collocated mode).
The default file provided with JOnAS is the following:
?xml version="1.0"?
config
server id="0" name="S0" hostname="localhost"
service class="org.objectweb.joram.mom.proxies.ConnectionManager"
service class="org.objectweb.joram.mom.proxies.tcp.TcpProxyService"
/server
/config
args="root root"/
args="16010"/
The above configuration describes a JORAM platform made of one unique JORAM server (id 0, name s0), running on localhost, listening on port 16010. Those values are taken into account by the JORAM server when starting. However they should match the values set in the deployment descriptor of the RA, otherwise the adapter either will not connect to the JORAM server, or will build improper connection factories.
3.7.1.3. Specifying Administration Tasks
The joram-admin.cfg file describes administered objects to be (optionally) created when deploying the adapter.
Page 56
48 Chapter 3. JOnAS Configuration
The default file provided with JOnAS creates a queue bound with the name sampleQueue, creates a topic bound with the name sampleTopic, sets the anonymous user, and creates and binds non­managed connection factories named JCF, JQCF, and JTCF. It also defines a host name and server port, which have the same meanings as the parameters set in the jonas-ra.xml file. Their goal is to make it easy to change the host and port values without having to edit the deployment descriptor.
To request the creation of a queue with the name "myQueueName", add the line:
Queue myQueueName
To request the creation of a topic with the name "myTopicName", add the line:
Topic myTopicName
To request the creation of the user "myName" - "myPass", add the line:
User myName myPass
To request the creation of a non-managed ConnectionFactory to be bound with the name "myCF", add the line:
CF myCF
To request the creation of a non-managed QueueConnectionFactory to be bound with the name "myQCF", add the line:
QCF myQCF
To request the creation of a non-managed TopicConnectionFactory, to be bound with the name "myTCF", add the line:
TCF myTCF
Note:
All administration tasks are performed locally (that is, on the JORAM server to which the adapter
is connected).
If a queue, a topic, or a user already exists on the JORAM server (for example because the server
is in persistent mode and has re-started after a crash, or because the adapter has been deployed, undeployed, and is re-deployed giving access to a remote JORAM ser ver), it will be retrieved instead of being re-created.
3.7.1.4. Undeploying and Redeploying a JORAM Adapter
Undeploying a JORAM adapter either stops the collocated JORAM server, or disconnects from a remote JORAM server. It is then possible to deploy the same adapter again:
If set for running a collocated server, it will re-start it.
If the running mode is persistent, then server will be retrieved in its pre-undeployed state (with the
existing destinations, users, and possibly messages).
If set for connecting to a remote server, the adapter will reconnect and access the destinations it
previously created.
Page 57
Chapter 3. JOnAS Configuration 49
In the collocated persistent case, if you want to start a new JORAM server, remove its persistence directory. This directory is located in JOnAS’ running directory, and has the same name as the JORAM server (for example s0/ for server "s0").
Page 58
50 Chapter 3. JOnAS Configuration
Page 59
Chapter 4.
Configuring JDBC DataSources
This chapter shows the bean or application deployer how to configure the DataSources to connect the application to databases.
4.1. Configuring DataSources
For both container-managed and bean-managed persistence, JOnAS makes use of relational storage systems through the JDBC interface. JDBC connections are obtained from an object, the
DataSource, provided at the application server level. The DataSource interface is defined in
the JDBC 2.0 standard extensions (see http://java.sun.com/products/jdbc/). A DataSource object identifies a database and a means to access it via a JDBC driver. An application server may request access to several databases and thus provide the corresponding DataSource objects. Available DataSource objects can be added on the platform; they must be defined in the jonas.properties file. This section explains how DataSource objects can be defined and configured in the JOnAS server.
To support distributed transactions, JOnAS requires the use of a JDBC2-XA-compliant driver. Such drivers that implement the XADataSource interface are not always available for all relational databases. JOnAS provides a generic driver-wrapper that emulates the XADataSource interface on a regular JDBC driver.
Important
It is important to note that this driver-wrapper does not ensure a real two-phase commit for distributed database transactions.
JOnAS’s generic driver-wrapper provides an implementation of the DataSource interface that al­lows DataSource objects to be defined using a JDBC1-compliant driver for some relational databases, such as Oracle and PostgreSQL.
Neither the EJB specification nor the J2EE specification describe how to define DataSource objects so that they are available to a J2EE platform. Therefore, this document, which describes how to define and configure DataSource objects, is specific to JOnAS. However, the way to use these DataSource objects in the Application Component methods is standard; that is, by using the resource manager con­nection factory references (refer to the example in Section 8.6 Writing Database Access Operations (Bean-Managed Persistence)).
A DataSource object should be defined in a file called DataSourcename.properties (for example,
Oracle1.properties for an Oracle DataSource), as delivered with the platform.
In the jonas.properties file, to define a DataSource “Oracle1”, add the name Oracle1 (the same name as in the properties file) to the line jonas.service.dbm.datasources, as follows:
jonas.service.dbm.datasources Oracle1,PostgreSQL
The property file defining a DataSource should contain the following information:
datasource.name JNDI name of the DataSource
Page 60
52 Chapter 4. Configuring JDBC DataSources
datasource.url The JDBC database URL:
jdbc:database_vendor_subprotocol:...
datasource.classname Name of the class implementing the JDBC driver
datasource.username Database user name
datasource.password Database user password
A DataSource object for Oracle (for example, Oracle1), named jdbc_1 in JNDI, and using the Oracle thin JDBC driver, would be described in a file called Oracle1.properties, as in the following example:
datasource.name jdbc_1 datasource.url jdbc:oracle:thin:@malte:1521:ORA1 datasource.classname oracle.jdbc.driver.OracleDriver datasource.username scott datasource.password tiger
In this example, malte is the hostname of the server running the Oracle DBMS, 1521 is the SQL*Net V2 port number on this server, and ORA1 is the ORACLE_SID.
This example makes use of the Oracle "Thin" JDBC driver. If your application server is running on the same host as the Oracle DBMS, you can use the Oracle OCI JDBC driver; depending on the Oracle re­lease. The URLto use for this would be jdbc:oracle:oci7, or jdbc:oracle:oci8. Oracle JDBC drivers can be downloaded at the Oracle web site: http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html
To create a PostgreSQL DataSource object named jdbc_3 in JNDI, describe it as follows (in a file
PostGreSQL.properties):
datasource.name jdbc_3 datasource.url jdbc:postgresql://your_host/your_db datasource.classname org.postgresql.Driver datasource.username useless datasource.password useless
Properties having the useless value are not used for this type of persistence storage.
If the database user and password are placed in the DataSource description (the
DataSource-name.properties file), then Application Components should use the getConnection() method. If the database user and password are omitted from the DataSource
description file, then Application Components should use the getConnection(String
username, String password) method. The resource reference of the associated datasource in
the standard deployment descriptor, the
Container if the user and password are given in the DataSource description, Application if the
res-authelement, should have the corresponding value:
user and password are provided by the Application.
4.2. CMP2.0/JORM
To implement EJB 2.0 persistence (CMP2.0), JOnAS relies on the JORM framework (see http://jorm.objectweb.org/index.html). JORM must adapt its object-relational mapping to the underlying database and makes use of adapters called "mappers" for this purpose. Thus, for each type of database (and more precisely for each JDBC driver), the corresponding mapper must be specified in the DataSource properties file. This is the purpose of the datasource.mapper property.
The JORM database mapper named datasource.mapper has the following possible values:
rdb: generic mapper (JDBC standard driver ...)
Page 61
Chapter 4. Configuring JDBC DataSources 53
rdb.postgres: mapper for PostgreSQL
rdb.oracle8: mapper for Oracle 8 and lesser versions
rdb.oracle: mapper for Oracle 9
rdb.mysql: mapper for MySQL
4.3. ConnectionManager Configuration
Each Datasource is implemented as a connection manager that can be configured via some additional properties described in the following table. Refer to the Oracle1.propertiesfile to see an example of settings. All these settings have default values and are not required.
Property Name Description Default Value
jdbc.connchecklevel JDBC connection checking
level: 0 (no check), 1 (check connection), higher (call the test statement)
jdbc.connmaxage maximum age for jdbc
connections
jdbc.connteststmt test statement select 1
jdbc.minconpool Minimum number of
connections in the pool
jdbc.maxconpool Maximum number of
connections in the pool
1
30 minutes
0
-1 (no max boundary)
jdbc.connteststmt is not used when jdbc.connchecklevel is equal to 0 or 1.
jdbc.minconpool is used at DataSource creation time. Modifying this property during runtime has
no effect on already-created DataSources.
jdbc.maxconpool can be dynamically increased or decreased.
4.4. Tracing SQL Requests Through P6Spy
The P6Spy tool is integrated within JOnAS to provide a means for easily tracing the SQL requests that are sent to the database (see http://www.p6spy.com/).
To enable this tracing feature, perform the following configuration steps:
1. Set the datasource.classname property of your DataSource properties file to
com.p6spy.engine.spy.P6SpyDriver
2. Set the realdriver property in the spy.properties file (located within
$JONAS_BASE/conf) to the JDBC driver of your actual database
3. Verify that logger.org.objectweb.jonas.jdbc.sql.level is set to DEBUG in the
$JONAS_BASE/conf/trace.properties file.
Example:
DataSource properties file contents:
datasource.name jdbc_3 datasource.url jdbc:postgresql://your_host:port/your_db
Page 62
54 Chapter 4. Configuring JDBC DataSources
datasource.classname com.p6spy.engine.spy.P6SpyDriver datasource.username jonas datasource.password jonas datasource.mapper rdb.postgres
Within the $JONAS_BASE/conf/spy.properties file:
realdriver=org.postgresql.Driver
Within the $JONAS_BASE/conf/trace.properties file:
logger.org.objectweb.jonas.jdbc.sql.level DEBUG
Page 63
Chapter 5.
JOnAS Class Loader Hierarchy
This chapter is for the EAR application provider; that is, the person in charge of developing the J2EE application components on the server side. It describes a new and important key feature of the J2EE integration: the class loader hierarchy in JOnAS.
5.1. Understanding the Class Loader Hierarchy
An application is deployed by its own class loader. This means, for example, that if a WAR and an EJB JAR are deployed separately, the classes contained in the two archives are loaded with two separate classloaders with no hierarchy between them. Thus, the EJBs from within the JAR will not be visible to the Web components in the WAR.
This is not acceptable in cases where the Web components of an application need to reference and use some of the EJBs.
For this reason, prior to EAR files, when a Web application had to be deployed using EJBs, the EJB JAR had to be located in the WEB-INF/lib directory of the Web application.
Currently, with the J2EE integration and the use of the EAR packaging, class visibility problems no longer exist and the EJB JAR is no longer required to be in the WEB-INF/lib directory.
The following sections describe the JOnAS class loader hierarchy and explain the mechanism used to locate the referenced classes.
5.2. Commons Class Loader
The JOnAS-specific commons class loader will load all classes and libraries required to start the JOnAS server (that is, libraries for mail, Tomcat, etc.). This class loader has the system class loader as parent class loader. The commons class loader adds all the common libraries required to start the JOnAS server (J2EE applications, commons logging, ObjectWeb components, etc.); it also loads the classes located in XTRA_CLASSPATH.
To have a library available for each component running inside JOnAS, add the required JAR files in the
JONAS_ROOT/lib/ext directory or in JONAS_BASE/lib/ext. The jars in JONAS_BASE/lib/ext
are loaded first, followed by the jars in JONAS_ROOT/lib/ext. All jars in subordinate directories will also be loaded.
If a specific JAR is needed only for a web application (that is, you need to use a version of a JAR file that is different than a version loaded by JOnAS), change the compliance of the web application classloader to the Java 2 delegation model. See Section 5.6.3 WEB Class Loader.
5.3. Application Class Loader
The application class loader is a JOnAS-specific class loader that loads all application classes required by the user applications. This implies that this loader will load all single RAR files, so all applications have the visibility of the resource adapter’s classes. This class loader has the commons class loader as its parent class loader.
Page 64
56 Chapter 5. JOnAS Class Loader Hierarchy
5.4. Tools Class Loader
The tools class loader is a JOnAS-specific class loader that loads all classes for which applications do not require visibility (that is, user applications will not be able to load the classes packaged in the tools class loader). For example, it includes the jakarta velocity and digester components. This class loader has the commons class loader as its parent class loader.
5.5. Tomcat Class Loader
The Tomcat class loader loads all classes of the Tomcat server (the CATALINA_HOME/server/lib directory). The classes of the common directory of Tomcat (CATALINA_HOME/common/lib direc­tory) are loaded by the application class loader and not by this Tomcat class loader. Applications have the visibility of the common classes and not the server classes. To have the visibility of the server class, the context must have the privileged attribute set to true. This class loader has the application class loader as its parent class loader.
5.6. JOnAS Class Loaders
The JOnAS class loader hierarchy that allows the deployment of EAR applications without placing the EJB JAR in the WEB-INF/lib directory consists of the following:
5.6.1. EAR Class Loader
The EAR class loader is responsible for loading the EAR application. There is only one EAR class loader per EAR application. This class loader is the child of the application class loader, thus making it visible to the JOnAS classes.
5.6.2. EJB Class Loader
The EJB class loader is responsible for loading all the EJB JARs of the EAR application, thus all the EJBs of the same EAR application are loaded with the same EJB classloader. This class loader is the child of the EAR class loader.
5.6.3. WEB Class Loader
The WEB class loader is responsible for loading the Web components. There is one WEB class loader per WAR file, and this class loader is the child of the EJB class loader. Using this class loader hierarchy (the EJB class loader is the parent of the WEB class loader) eliminates the problem of visibility between classes when a WEB component tries to reference EJBs; the classes loaded with the WEB class loader are definitely visible to the classes loaded by its parent class loader (EJB class loader).
The compliance of the class loader of the web application to the Java 2 delegation model can be changed by using the jonas-web.xml file. This is described in Chapter 17 Defining the Web Deploy- ment Descriptor.
If the java2-delegation-model element is set to false, the class loader of the web application looks for the class in its own repository before asking its parent class loader.
Page 65
Chapter 5. JOnAS Class Loader Hierarchy 57
5.7. JOnAS Class Loader Hierarchy
The resulting JOnAS class loader hierarchy is as follows:
Figure 5-1. JOnAS Class Loader Hierarchy
Page 66
58 Chapter 5. JOnAS Class Loader Hierarchy
Page 67
JOnAS Command Reference
Commands provided with JOnAS are described in this chapter.
Section 6.1 jonas: JOnAS manager
Section 6.2 jclient: Starting a JOnAS client
Section 6.3 newbean: Bean generator
Section 6.4 registry: Java Remote Object Registry
Section 6.5 GenIC: Container classes generator
Section 6.6 JmsServer
Section 6.7 RAConfig: Resource Adapter configuration tool
6.1. jonas
6.1.1. Synopsis
jonas start [-fg | -bg | -win] [-n name]
start a JOnAS server
jonas stop [-n name]
Stop a JOnAS server.
jonas admin [-n name] [admin_options]
Administer a JOnAS server.
jonas check
Check the environment before running a JOnAS server.
jonas version
Print the current version of JOnAS.
Chapter 6.
6.1.2. Description
This command provides the capability to start, stop, or administer JOnAS servers.
The outcome of this program may depend on the directory from which the command is run (that is depending on the existence of a jonas.properties file in the current directory). It is possible to set system properties to the program by using the JAVA_OPTS environment variable, if required. Note that setting system properties with a -D option will always take precedence over the properties described in the other jonas.properties files.
The jonas script /usr/share/jonas/bin/unix/jonas can be reviewed and possibly modified for assistance with problems or for obtaining additional information.
There are five different sub-commands that depend on the first mandatory argument:
Page 68
60 Chapter 6. JOnAS Command Reference
jonas start
Start a new JOnAS server. The process can be run in the foreground, in the background, or in a new window. If the background option is chosen (default option), control is given back to the caller only when the server is ready. The default name is jonas. A different name can be given with the -n option.
jonas stop
Stop a running JOnAS server. Use the -n option if the server was given a name other than the default name.
jonas admin
Administer a JOnAS server. Use the -n option if the server was given a name other than the default name. Used without any other option, this command will prompt the user for an admin­istrative command (interactive mode). Each administrative command exists in a non-interactive mode, for use in applications such as shell scripts, for example. Refer to the option list for a description of each.
jonas check
Check the environment settings before running a JOnAS server. (This is a very basic trou­bleshooting test.)
jonas version
Print the current version of JOnAS.
6.1.3. Options
Each option may be pertinent only for a subset of the five different sub-commands. For example,
jonas check and jonas version do not accept any options.
-n name
Give a name to the JOnAS server. The default is jonas. Used for start, stop, or admin.
-fg
Used for start only. The server is launched in the foreground: control is given back to the user only when the JOnAS server is stopped.
-bg
Used for start only. The server is launched in the background. Control is given back to the user only when the JOnAS server is ready. This is the default mode.
-win
Used for start only. The server is launched in a new window.
-?
Used for admin only. Prints a help with all possible options.
-a filename
Used for admin only. Deploys a new application described by filename inside the JOnAS Server. The application can be one of the following:
Page 69
Chapter 6. JOnAS Command Reference 61
A standard EJB-JAR file. This leads to the creation of a new EJB Container in the JOnAS
Server. If the file name has a relative path, this path is relative to where the EJB server has been launched or relative to the $JONAS_ROOT/ejbjars directory for an EJB-JAR file.
A standard WAR file containing a WEB Component. If the file name has a relative
path, this path is relative to where the EJB server has been launched or relative to the
$JONAS_ROOT/webapps directory for a WAR file.
A standard EAR file containing a complete J2EE application. If the file name has a rela-
tive path, this path is relative to where the EJB server has been launched or relative to the
$JONAS_ROOT/apps directory for an EAR file.
-r filename
Used for admin only. Dynamically removes a previous -a filename command.
-gc
Used for admin only. Runs the garbage collector in the specified JOnAS server.
-passivate
Used for admin only. Passivates all Entity Bean instances. This affects only instances outside transaction.
-e
Used for admin only. Lists the properties of the specified JOnAS server.
-j
Used for admin only. Lists the registered JNDI names, as seen by the specified JOnAS server.
-l
Used for admin only. Lists the beans currently loaded by the specified JOnAS server.
-sync
Used for admin only. Synchronizes the Entity Bean instances on the current JOnAS server. Note that this affects only the instances that are not involved in a transaction.
-debug topic
Used for admin only. Sets the topic level to DEBUG.
-tt timeout
Used for admin only. Changes the default timeout for transactions. timeout is in seconds.
Each jonas admin option has its equivalent in the interactive mode. To enter interactive mode and access the following list of subcommands, type jonas admin [-n name] without any other argu­ment. To exit from interactive mode, use the quit command.
Interactive Command Online Matching Command
addbeans -a fileName
env -e
gc -gc
help -?
Page 70
62 Chapter 6. JOnAS Command Reference
Interactive Command Online Matching Command
jndinames -j
listbeans -l
removebeans -r fileName
sync -sync
trace -debug topic
ttimeout -tt timeout
quit exit interactive mode
6.1.4. Examples
jonas check
jonas start -n jonas1
jonas admin -n jonas1 -a bean1.jar
jonas stop -n jonas1
6.2. jclient
6.2.1. Synopsis
jclient [options] java-class [args]
Start a Java client.
6.2.2. Description
The jclient command allows the user to easily start a "heavy" java client that will be able to reach beans in remote JOnAS servers and start distributed transactions.
6.2.3. Options
-cp classpath
Add an additional classpath before running the Java program.
6.2.4. Example
jclient package.javaclassname args
Page 71
Chapter 6. JOnAS Command Reference 63
6.3. newbean
6.3.1. Synopsis
newbean
Generates skeletons for all the necessary files for making a bean.
6.3.2. Description
The newbean tool helps the bean writer start developing a bean by generating skeletons for all the nec­essary files for making a bean. Note that this tool creates only templates of the files. These templates must then be customized and the business logic written. However, the files should be compilable.
To create these templates, type newbean and enter a set of parameters in interactive mode.
newbean generates a build.xml file.
The Bean Name must start with a capital letter. Avoid the reserved names: Home, EJB, Session, Entity. This name will be used as a prefix for all filenames relative to the bean.
The Bean Type must be one of the following:
S Session Bean
E Entity Bean
MD Message-Driven Bean
The Session Type must be one of the following:
L Stateless Session Bean
F Stateful Session Bean
The Persistence manager must be one of the following:
B Bean-Managed Persistence (BMP)
C Container-Managed Persistence (CMP 1.x)
C2 Container-Managed Persistence (CMP 2.x)
The Bean Location must be one of the following:
R Remote Interfaces
L Local Interfaces
The Package name is a dot-separated string representing the package to which the bean belongs. Usually this is the same as the current directory.
The Jar name argument is the name that will be used to build the .jar file. Do not provide the .jar extension with this argument. Typically, the last part of the package name is used.
The Primary Key class is the class that represents the primary key. It is required only for Entity Beans. Its possible values are:
S java.lang.String
I java.lang.Integer
O Object (Will be chosen later)
Page 72
64 Chapter 6. JOnAS Command Reference
6.3.3. Example
newbean Bean Name
MyFirstBean
Bean type
S Session bean E Entity bean MD Message-Driven bean
E
Persistance manager
B Bean C Container (CMP 1.x) C2 Container (CMP 2.x)
C
Bean location
R Remote L Local
R
Package name
truc.machin
Jar name
machin
Primary Key class
S String I Integer O Object
S
Creating bean MyFirstBean (type ECR) in package truc.machin Your bean files have been created. You can now customize them.
6.3.4. Example 2
-bash-2.05b$ /usr/share/jonas/bin/unix/newbean Bean Name > MySecondBean
Bean type
S Session bean E Entity bean MD Message-Driven bean
> S
Session type
L Staless F Stateful
> F
Bean location
Page 73
Chapter 6. JOnAS Command Reference 65
R Remote L Local
> L
Package name > com.redhat.rhdb.cc.jonas
Jar name > rhaps-cc-jonas
Creating bean MySecondBean (type SFL) in package com.redhat.rhdb.cc.jonas Your bean files have been created. You can now customize them.
6.4. registry
6.4.1. Synopsis
registry [ port ]
Creates and starts a remote object registry.
6.4.2. Description
The registry tool creates and starts a remote object RMI registry on the specified port of the current host. If the port is omitted, the registry is started on port 1099.
Note that, by default, the registry is collocated in the same JVM as the JOnAS Server. In this case, it is not necessary to use this tool; the registry is automatically launched.
6.4.3. Options
port
Port number.
6.4.4. Example
The registry command can normally be run in the background:
registry &
6.5. GenIC
6.5.1. Synopsis
GenIC [ Options ] InputFilename
Starts the GenIC utility.
Page 74
66 Chapter 6. JOnAS Command Reference
6.5.2. Description
The GenIC utility generates the container classes for JOnAS from the given Enterprise Java Beans.
The InputFileName is either the file name of an EJB-JAR file or the file name of an XML deploy­ment descriptor of beans.
The GenIC utility does the following in the order listed:
1. Generates the sources of the container classes for all the beans defined in the deployment de­scriptor.
2. Compiles these classes via the Java compiler.
3. Generates stubs and skeletons for those remote objects via the RMI compiler.
4. If the InputFile is an EJB-JAR file, adds the generated classes in this EJB-JAR file.
6.5.3. Options
-d directory
Specifies the root directory of the class hierarchy.
This option can be used to specify a destination directory for the generated files.
If the -d option is not used, the package hierarchy of the target class is ignored and the generated files are placed in the current directory.
If the InputFile is an EJB-JAR file, the generated classes are added to the EJB-JAR file, unless the -noaddinjar option is set.
-invokecmd
Invoke, directly in some cases, the method of the Java class corresponding to the command.
-javac options
Specifies the java compiler name to use (javac by default).
-javacopts options
Specifies the options to pass to the java compiler.
-keepgenerated
Do not immediately delete generated files.
-noaddinjar
If the InputFile is an EJB-JAR file, do not add the generated classes to the EJB-JAR file.
-nocompil
Do not compile the generated source files via the Java and RMI compilers.
-novalidation
Remove xml validation during parsing.
-protocols
Comma-separated list of protocols (chosen from jrmp, iiop, cmi) for which stubs should be gen­erated. Default is jrmp.
Page 75
Chapter 6. JOnAS Command Reference 67
-rmiopts options
Specifies the options to pass to the rmi compiler.
-verbose
Displays additional information about command execution.
-mappernames
Comma-separated list of mapper names for which the container classes will be generated. Used for the JORM-based implementation of CMP 2.0. A mapper is used by JORM for accessing a given database. This list of mappers corresponds to the list of potential databases upon which the Entity Beans can be deployed.
6.5.4. Example
GenIC -d ../../classes sb.xml
Generates container classes of all the Enterprise JavaBeans defined in the sb.xml file. Classes are generated in the ../../classes directory adhering to the classes hierarchy.
GenIC sb.jar
Generates container classes for all the Enterprise JavaBeans defined in the sb.jar file and adds the generated classes to this EJB-JAR file.
6.5.5. Environment
If InputFile is an XML deployment descriptor, the classpath must include the paths of the directo­ries in which the Enterprise Bean’s classes can be found, as well as the path of the directory specified by the -d option.
If InputFile is an EJB-JAR file, the classpath must include the path of the directory specified by the
-d option.
6.6. JmsServer
6.6.1. Synopsis
JmsServer
Launches the JORAM Server.
6.6.2. Description
Launches the JORAM Server (that is, the MOM) with its default options.
Page 76
68 Chapter 6. JOnAS Command Reference
6.6.3. Options
None.
6.6.4. Example
The JmsServer command is typically run in the background:
JmsServer &
6.7. RAConfig
6.7.1. Synopsis
RAConfig [ Options ] InputFilename [OutputFilename]
Generates a JOnAS-specific resource-adapter configuration file.
6.7.2. Description
The RAConfig utility generates a JOnAS-specific resource-adapter configuration file
(jonas-ra.xml) from an ra.xml file (Resource adapter deployment descriptor).
The InputFileName is the file name of a resource adapter.
The OutputFileName is the file name of an output resource adapter used with the -p (required) or
-u (optional).
6.7.3. Options
-? or -help options
Gives a summary of the options.
-dm,-ds,-pc,-xa DriverManager, DataSource, PooledConnection, XAConnection
Specifies the rarlink value to configure; used with the -p option.
-j jndiname
It is a mandatory option. It specifies the JNDI name of the connection factory. This name cor­responds to the name of the JOnAS-specific deployment descriptor. This name is used by the resource service for registering in JNDI the connection factory corresponding to this resource adapter.
-p database_properties_file
Specifies the name of the database.properties file to process. The result of this processing will be a jonas-ra.xml file that will update the /META-INF/jonas-ra.xml file in the output RAR.
jndi-nameelement of thejonas-resourceelement in the
Page 77
Chapter 6. JOnAS Command Reference 69
-r rarlink
Specifies the JNDI name of the RAR file with which to link. This option can be used when this RAR file will inherit all attributes associated with the specified JNDI name. If this option is specified in the jonas-ra.xml file, it is the only file needed in the RAR, and the ra.xml file will be processed from the rarlink file.
-u inputname
Specifies the name of the XML file to process. This file will update the
/META-INF/jonas-ra.xml file in the RAR. If this argument is used, it is the only argument
executed.
-verbose
Verbose mode. Displays the deployment descriptor of the resource adapter on standard
System.out.
6.7.4. Example
RAConfig -j adapt_1 MyRA.rar
Generates the jonas-ra.xml file from the ra.xml file.
After jonas-ra.xml has been configured for the MyRA.rar file,
RAConfig -u jonas-ra.xml MyRA.rar
Updates/inserts the jonas-ra.xml file into the RAR file.
RAConfig -dm -p MySQL1 $JONAS_ROOT/rars/autoload/JOnAS_jdbcDM MySQL_dm
Generates the jonas-ra.xml file from the ra.xml file of the JOnAS_jdbcDM.rar and inserts the corresponding values from the MySQL1.properties file. The jonas-ra.xml file is then added/updated to the MySQL_dm.rar file. This RAR file can then be deployed and will replace the configured MySQL1 datasource.
Page 78
70 Chapter 6. JOnAS Command Reference
Page 79
II. Enterprise Beans Programmer’s Guide
This part contains information for the Enterprise Beans programmer; that is, the person in charge of developing the software components on the server side and, more specifically, the Session Beans.
The individual in charge of developing Enterprise Beans should consult chapters in this part for in­structions on how to perform the following tasks:
Write the source code for the beans.
Specify the deployment descriptor.
Bundle the compiled classes and the deployment descriptor into an EJB JAR file.
For information on developing the three types of enterprise beans, refer to:
Chapter 7 Developing Session Beans
Chapter 8 Developing Entity Beans
Chapter 9 Developing Message-Driven Beans.
The deployment descriptor specification is presented in Chapter 10 Defining the Deployment Descrip­tor.
More specific issues related to transaction behavior, the Enterprise Bean environment, and security service are presented in the corresponding chapters: Chapter 11 Transactional Behavior of EJB Ap- plications, Chapter 12 Enterprise Bean Environment, and Chapter 13 Security Management.
Principles and tools for providing EJB JAR files are presented in Chapter 14 EJB Packaging and Chapter 15 Application Deployment and Installation Guide.
Table of Contents
7. Developing Session Beans............................................................................................................. 73
8. Developing Entity Beans...............................................................................................................79
9. Developing Message-Driven Beans............................................................................................ 119
10. Defining the Deployment Descriptor ....................................................................................... 129
11. Transactional Behavior of EJB Applications ......................................................................... 135
12. Enterprise Bean Environment ................................................................................................. 141
13. Security Management ............................................................................................................... 145
14. EJB Packaging .......................................................................................................................... 149
15. Application Deployment and Installation Guide ...................................................................151
Page 80
Page 81
Chapter 7.
Developing Session Beans
This chapter is for the Enterprise Bean provider; that is, the person in charge of developing the soft­ware components on the server side and, more specifically, the Session Beans.
Note
In this documentation, the term "Bean" always means "Enterprise Bean."
7.1. Introduction to Session Beans
A Session Bean is composed of the following parts, which are developed by the Enterprise Bean provider:
The Component Interface is the client view of the bean. It contains all the “business methods” of
the bean.
The Home Interface contains all the methods for the bean life cycle (creation, suppression) used by
the client application.
The bean implementation class implements the business methods and all the methods (described in
the EJB specification), allowing the bean to be managed in the container.
The deployment descriptor contains the bean properties that can be edited at assembly or deploy-
ment time.
Note that, according to the EJB 2.0 specification, the couple “Component Interface and Home Inter­face” may be either local or remote. Local Interfaces (Home and Component) are to be used by a client running in the same JVM as the EJB component. Create and finder methods of a local or remote home interface return local or remote component interfaces respectively. An EJB component can have both remote and local interfaces, even if typically only one type of interface is provided.
The description of these elements is provided in the sections that follow.
A Session Bean object is a short-lived object that executes on behalf of a single client. There are stateless and stateful Session Beans. Stateless Beans do not maintain state across method calls. Any instance of stateless beans can be used by any client at any time. Stateful Session Beans maintain state within and between transactions. Each stateful session bean object is associated with a specific client. A stateful Session Bean with container-managed transaction demarcation can optionally implement the SessionSynchronization interface. In this case, the bean objects will be informed of transaction boundaries. A rollback could result in a Session Bean object’s state being inconsistent; in this case, implementing the SessionSynchronization interface may enable the bean object to update its state according to the transaction completion status.
7.2. The Home Interface
A Session Bean’s home interface defines one or more create(...) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean’s remote interface type.
The home interface of a stateless Session Bean must have one create method that takes no argu­ments.
Page 82
74 Chapter 7. Developing Session Beans
All the exceptions defined in the throws clause of an ejbCreate method must be defined in the
throws clause of the matching create method of the home interface.
A remote home interface extends the javax.ejb.EJBHome interface, while a local home interface extends the javax.ejb.EJBLocalHome interface.
7.2.1. Session Bean Example:
The following examples use a Session Bean named Op.
public interface OpHome extends EJBHome {
Op create(String user) throws CreateException, RemoteException;
}
A local home interface could be defined as follows (LocalOp being the local component interface of the bean):
public interface LocalOpHome extends EJBLocalHome {
LocalOp create(String user) throws CreateException;
}
7.3. The Component Interface
The Component Interface is the client’s view of an instance of the Session Bean. This interface contains the business methods of the Enterprise Bean. If it is remote, the interface must extend the javax.ejb.EJBObject interface; if it is local, the interface must extend the
javax.ejb.EJBLocalObject interface. The methods defined in a remote component interface
must follow the rules for Java RMI (this means that their arguments and return value must be valid types for Java RMI, and their throws clause must include the java.rmi.RemoteException). For each method defined in the component interface, there must be a matching method in the enterprise Bean’s class (same name, same arguments number and types, same return type, and same exception list, except for RemoteException).
7.3.1. Example:
public interface Op extends EJBObject {
public void buy (int Shares) throws RemoteException; public int read () throws RemoteException;
}
The same type of component interface could be defined as a local interface (even if it is not considered good design to define the same interface as both local and remote):
public interface LocalOp extends EJBLocalObject {
public void buy (int Shares); public int read ();
}
Page 83
Chapter 7. Developing Session Beans 75
7.4. The Enterprise Bean Class
This class implements the Bean’s business methods of the component interface and the methods of the
SessionBean interface, which are those dedicated to the EJBenvironment. The class must be defined
as public and may not be abstract. The Session Bean interface methods that the EJB provider must develop are the following:
public void setSessionContext(SessionContext ic);
This method is used by the container to pass a reference to the SessionContext to the bean instance. The container invokes this method on an instance after the instance has been created. Generally, this method stores this reference in an instance variable.
public void ejbRemove();
This method is invoked by the container when the instance is in the process of being removed by the container. Since most session Beans do not have any resource state to clean up, the implementation of this method is typically left empty.
public void ejbPassivate();
This method is invoked by the container when it wants to passivate the instance. After this method completes, the instance must be in a state that allows the container to use the Java Serialization protocol to externalize and store the instance’s state.
public void ejbActivate();
This method is invoked by the container when the instance has just been reactivated. The instance should acquire any resource that it has released earlier in the ejbPassivate() method.
A stateful session Bean with container-managed transaction demarcation can optionally implement the javax.ejb.SessionSynchronization interface. This interface can provide the Bean with transaction-synchronization notifications. The Session Synchronization interface methods that the EJB provider must develop are the following:
public void afterBegin();
This method notifies a session Bean instance that a new transaction has started. At this point the instance is already in the transaction and can do any work it requires within the scope of the trans­action.
public void afterCompletion(boolean committed);
This method notifies a session Bean instance that a transaction commit protocol has completed and tells the instance whether the transaction has been committed or rolled back.
public void beforeCompletion();
This method notifies a session Bean instance that a transaction is about to be committed.
7.4.1. Enterprise Bean Class Example:
package sb;
import java.rmi.RemoteException; import javax.ejb.EJBException; import javax.ejb.EJBObject; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import javax.ejb.SessionSynchronization; import javax.naming.InitialContext; import javax.naming.NamingException;
Page 84
76 Chapter 7. Developing Session Beans
// This is an example of Session Bean, stateful, and synchronized.
public class OpBean implements SessionBean, SessionSynchronization {
protected int total = 0; // actual state of the bean protected int newtotal = 0; // value inside Tx, not yet committed. protected String clientUser = null; protected SessionContext sessionContext = null;
public void ejbCreate(String user) {
total = 0; newtotal = total; clientUser = user;
}
public void ejbActivate() {
// Nothing to do for this simple example
}
public void ejbPassivate() {
// Nothing to do for this simple example
}
public void ejbRemove() {
// Nothing to do for this simple example
}
public void setSessionContext(SessionContext sessionContext) {
this.sessionContext = sessionContext;
}
public void afterBegin() {
newtotal = total;
}
public void beforeCompletion() {
// We can access the bean environment everywhere in the bean, // for example here! try {
InitialContext ictx = new InitialContext(); String value = (String) ictx.lookup("java:comp/env/prop1"); // value should be the one defined in ejb-jar.xml
} catch (NamingException e) {
throw new EJBException(e);
}
}
public void afterCompletion(boolean committed) {
if (committed) {
total = newtotal;
} else {
newtotal = total;
}
}
public void buy(int s) {
newtotal = newtotal + s; return;
}
public int read() {
Page 85
Chapter 7. Developing Session Beans 77
return newtotal;
}
}
7.5. Tuning the Stateless-Session Bean Pool
JOnAS handles a pool for each stateless Session Bean. The pool can be configured in the JOnAS­specific deployment descriptor with the following tags:
min-pool-size
This optional integer value represents the minimum instances that will be created in the pool when the bean is loaded. This will improve bean instance creation time, at least for the first beans. The default value is 0.
max-cache-size
This optional integer value represents the maximum of instances in memory. This value keeps JOnAS scalable.
The policy is that, at bean creation time, an instance is taken from the pool of free instances. If the pool is empty, a new instance is always created. When the instance must be released (at the end of a business method), it is pushed into the pool, except if the current number of instances created exceeds the max-cache-size, in which case this instance is dropped. The default value is no limit.
jonas-ejb-jar
jonas-session
ejb-name!SessSLR /ejb-name jndi-name!EJB/SessHome /jndi-name max-cache-size!20 /max-cache-size min-pool-size!10 /min-pool-size
/jonas-session
/jonas-ejb-jar
!
!
!
!
!
!
Example 7-1. Stateless-Session Bean Pool Example
!
!
Page 86
78 Chapter 7. Developing Session Beans
Page 87
Chapter 8.
Developing Entity Beans
This chapter is for is the Enterprise Bean provider; that is, the person in charge of developing the software components on the server side, and more specifically the Entity Beans.
Note
In this documentation, the term "Bean" always means "Enterprise Bean."
8.1. Introduction to Entity Beans
An Entity Bean is comprised of the following elements, which are developed by the Enterprise Bean Provider:
The Component Interface is the client view of the bean. It contains all the “business methods” of
the bean.
The Home Interface contains all the methods for the bean life cycle (creation, suppression) and for
instance retrieval (finding one or several bean objects) used by the client application. It can also contain methods called “home methods,” supplied by the bean provider, for business logic that is not specific to a bean instance.
The Primary Key class (for Entity Beans only) contains a subset of the bean’s fields that identi-
fies a particular instance of an Entity Bean. This class is optional since the bean programmer can alternatively choose a standard class (for example, java.lang.String)
The bean implementation class implements the business methods and all the methods (described in
the EJB specification) allowing the bean to be managed in the container.
The deployment descriptor, containing the bean properties that can be edited at assembly or de-
ployment time.
Note
According to the EJB 2.0 specification, the “Component Interface and Home Interface” can be either local or remote. Local Interfaces (Home and Component) are to be used by a client running in the same JVM as the EJB component. Create and finder methods of a local (or remote) home interface return local (or remote) component interfaces. An EJB component may have both remote and local interfaces, even if normally only one type of interface is provided. If an Entity Bean is the target of a container-managed relationship (refer to EJB 2.0 persistence), then it must have local interfaces.
These elements are described in the following sections.
An Entity Bean represents persistent data. It is an object view of an entity stored in a relational database. The persistence of an Entity Bean can be handled in two ways:
Container-Managed Persistence: the persistence is implicitly managed by the container; no code
for data access is supplied by the bean provider. The bean’s state will be stored in a relational database according to a mapping description delivered within the deployment descriptor (CMP 1.1) or according to an implicit mapping (CMP 2.0).
Page 88
80 Chapter 8. Developing Entity Beans
Bean-Managed Persistence: the bean provider writes the database access operations (JDBC code)
in the methods of the enterprise bean that are specified for data creation, load, store, retrieval, and remove operations (ejbCreate, ejbLoad, ejbStore, ejbFind..., ejbRemove).
Currently, the platform handles persistence in relational storage systems through the JDBC interface. For both container-managed and bean-managed persistence, JDBC connections are obtained from an object provided at the EJB server level, the DataSource. The DataSource interface is defined in the JDBC 2.0 standard extensions (see http://java.sun.com/products/jdbc/). A DataSource object identifies a database and a means to access it via JDBC (a JDBC driver). An EJB server may propose access to several databases and thus provides the corresponding DataSource objects. DataSources are described in more detail in Chapter 4 Configuring JDBC DataSources.
8.2. The Home Interface
In addition to “home business methods,” the Home interface is used by any client application to cre­ate, remove, and retrieve instances of the Entity Bean. The bean provider needs to provide only the desired interface; the container will automatically provide the implementation. If it is remote, the in­terface must extend the javax.ejb.EJBHome interface; if it is local, the interface must extend the
javax.ejb.EJBLocalHome interface. The methods of a remote home interface must follow the rules
for Java RMI. The signatures of the create and find... methods should match the signatures of the
ejbCreate and ejbFind... methods that will be provided later in the Enterprise Bean implementa-
tion class (the same number and types of arguments, but different return types).
8.2.1. create Methods
The return type is the Enterprise Bean’s component interface.
The exceptions defined in the throws clause must include the exceptions defined for the
ejbCreate and ejbPostCreate methods, and must include javax.ejb.CreateException and
java.rmi.RemoteException (the latter is only for a remote interface).
8.2.2. remove Methods
The interfaces for these methods must not be defined—they are inherited from EJBHome or
EJBLocalHome.
The method is void remove, taking as an argument the primary key object or the handle (for a
remote interface).
The exceptions defined in the throws clause should be javax.ejb.RemoveException and
java.rmi.RemoteException for a remote interface.
The exceptions defined in the throws clause should be javax.ejb.RemoveException and
java.ejb.EJBException for a local interface.
8.2.3. finder Methods
Finder methods are used to search for an EJB object or a collection of EJB objects. The arguments of the method are used by the Entity Bean implementation to locate the requested entity objects. For bean-managed persistence, the bean provider is responsible for developing the corresponding ejbFinder methods in the bean implementation. For container-managed persistence, the bean provider does not write these methods; they are generated at deployment time by the platform tools; the de­scription of the method is provided in the deployment descriptor, as defined in Section 8.7 Configuring
Page 89
Chapter 8. Developing Entity Beans 81
Database Access for Container-Managed Persistence. In the Home interface, the finder methods must adhere to the following rules:
They must be named find
The return type must be the Enterprise Bean’s component interface, or a collection thereof.
The exceptions defined in the throws clause must include the exceptions defined for
method
"
(for example, findLargeAccounts).
#
the matching ejbFind method, and must include javax.ejb.FinderException and
java.rmi.RemoteException (the latter, only for a remote interface).
At least one of these methods is mandatory: findByPrimaryKey, which takes as argument a primary key value and returns the corresponding EJB object.
8.2.4. home Methods
Home methods are methods that the bean provider supplies for business logic that is not specific to an Entity Bean instance.
The throws clause of every home method on the remote home interface includes the
java.rmi.RemoteException.
Home methods implementation is provided by the bean developer in the bean implementation class
as public static methods named ejbHome
"
METHOD_NAME#(...), where"METHOD_NAME
#
is the
name of the method in the home interface.
8.2.5. Home Interface Example
The Account Bean example, provided with the platform examples, is used to illustrate these concepts. The state of an Entity Bean instance is stored in a relational database, where the following table should exist, if CMP 1.1 is used:
create table ACCOUNT (ACCNO integer primary key,
CUSTOMER varchar(30), BALANCE number(15,4));
public interface AccountHome extends EJBHome {
public Account create(int accno, String customer, double balance)
throws RemoteException, CreateException;
public Account findByPrimaryKey(Integer pk)
throws RemoteException, FinderException;
public Account findByNumber(int accno)
throws RemoteException, FinderException;
public Enumeration findLargeAccounts(double val)
throws RemoteException, FinderException;
}
Page 90
82 Chapter 8. Developing Entity Beans
8.3. The Component Interface
8.3.1. Business Methods
The Component Interface is the client’s view of an instance of the Entity Bean. It is what is returned to the client by the Home interface after creating or finding an Entity Bean instance. This interface contains the business methods of the Enterprise Bean. The interface must extend the
javax.ejb.EJBObject interface if it is remote, or the javax.ejb.EJBLocalObject if it is
local. The methods of a remote component interface must follow the rules for Java RMI. For each method defined in this component interface, there must be a matching method of the bean implementation class (same arguments number and types, same return type, same exceptions except for RemoteException).
8.3.1.1. Component Interface Example
public interface Account extends EJBObject {
public double getBalance() throws RemoteException; public void setBalance(double d) throws RemoteException; public String getCustomer() throws RemoteException; public void setCustomer(String c) throws RemoteException; public int getNumber() throws RemoteException;
}
8.4. The Primary Key Class
The Primary Key class is necessary for entity beans only. It encapsulates the fields representing the primary key of an Entity Bean in a single object. If the primary key in the database table is composed of a single column with a basic data type, the simplest way to define the primary key in the bean is to use a standard Java class (for example, java.lang.Integer or java.lang.String). This must have the same type as a field in the bean class. It is not possible to define it as a primitive field (for example, int, float or boolean). Then, it is only necessary to specify the type of the primary key in the deployment descriptor:
$
prim-key-class%java.lang.Integer$/prim-key-class
And, for container-managed persistence, the field which represents the primary key:
$
primkey-field%accno$/primkey-field
%
The alternative way is to define its own Primary Key class, described as follows:
The class must be serializable and must provide suitable implementation of the hashcode() and
equals(Object) methods.
For container-managed persistence, the following rules apply:
%
The fields of the primary key class must be declared as public.
The primary key class must have a public default constructor.
The names of the fields in the primary key class must be a subset of the names of the container-
managed fields of the Enterprise Bean.
Page 91
Chapter 8. Developing Entity Beans 83
8.4.1. Primary Key Class Example
public class AccountBeanPK implements java.io.Serializable {
public int accno; public AccountBeanPK(int accno) { this.accno = accno; } public AccountBeanPK() { }
public int hashcode() { return accno; } public boolean equals(Object other) {
...
}
}
8.4.1.1. Special Case: Automatic Generation of Primary Keys Field
There are two ways to manage automatic primary keys with JOnAS. The first method is closer to the EJB specification (that is, an automatic PK is a hidden field, the type of which is not even known by the application). In the second method, the idea is to declare a typical PK CMP field of the type
java.lang.Integer as automatic. These two cases are described below.
8.4.1.1.1. Method 1: Standard Automatic Primary Keys (from JOnAS 4.0.0)
In this case, an automatic PK is a hidden field, the type of which is not known by the application. All that is necessary is to stipulate in the standard deployment descriptor that this EJB has an auto­matic PK; you do this by specifying java.lang.Object as primkey-class. The primary key will be completely hidden from the application (no CMP field, no getter/setter method). This is valid for both CMP 2.x and CMP1 entity beans. The container will create an internal CMP field and generate its value when the Entity Bean is created.
8.4.1.1.1.1. Method 1 Example:
Standard deployment descriptor:
&
entity
'
...
&
ejb-name'AddressEJB&/ejb-name
&
local-home'com.titan.address.AddressHomeLocal&/local-home
&
local'com.titan.address.AddressLocal&/local
&
ejb-class'com.titan.address.AddressBean&/ejb-class
&
persistence-type'Container&/persistence-type
&
prim-key-class'java.lang.Object&/prim-key-class
&
reentrant'False&/reentrant
&
cmp-version'2.x&/cmp-version
&
abstract-schema-name'Cmp2_Address&/abstract-schema-name
&
cmp-field
&
cmp-field
&
cmp-field
&
cmp-field
&
'
field-name'street&/field-name
&
field-name'city&/field-name
'
&
field-name'state&/field-name
'
&
field-name'zip&/field-name
'
Address Bean Class extract:
// Primary key is not explicitly initialized during ejbCreate method // No cmp field corresponds to the primary key public Integer ejbCreateAddress(String street, String city,
String state, String zip ) throws javax.ejb.CreateException { setStreet(street); setCity(city); setState(state); setZip(zip);
'
'
'
'
'
'
'
&
'
'
&
'
/cmp-field
&
/cmp-field
&
/cmp-field
/cmp-field
'
'
'
'
'
'
'
Page 92
84 Chapter 8. Developing Entity Beans
return null;
}
If nothing else is specified and the JOnAS default CMP 2 database mapping is used, the JOnAS container generates a database column with the name JPK_ to handle this PK. However, it is possible to specify in the JOnAS-specific Deployment Descriptor the name of the column that will be used to store the PK value in the table. You can do this as follows using the specific
)
element (this technique is necessary for CMP2 legacy and for CMP1):
name
automatic-pk-field-
(
JOnAS-specific deployment descriptor:
*
jonas-ejb-jar xmlns="http://www.objectweb.org/jonas/ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.objectweb.org/jonas/ns http://www.objectweb.org/jonas/ns/jonas-ejb-jar_4_0.xsd"
*
jonas-entity
*
ejb-name+AddressEJB*/ejb-name
*
jdbc-mapping
*
*
*
/jdbc-mapping
*
/jonas-entity
+
jndi-name+jdbc_1*/jndi-name automatic-pk-field-name+FieldPkAuto*/automatic-pk-field-name
+
+
+
+
+
+
+
8.4.1.1.2. Method 2: CMP Field as Automatic Primary Key (from JOnAS 3.3.x)
The idea here is to declare a typical PK CMP field of type java.lang.Integer as automatic. By doing this, the field will no longer appear in create methods and its value will be automatically generated by the container at the EJB instance-creation time. However, it is still a cmp field, with getter/setter methods, and is accessible from the application.
8.4.1.1.2.1. Method 2 Example:
In the standard deployment descriptor, there is a typical primary key definition:
*
entity
+
...
*
prim-key-class+java.lang.Integer*/prim-key-class
*
cmp-field
*
primkey-field+id*/primkey-field
*
+
field-name+id*/field-name
*
+
+
/cmp-field
+
+
In the JOnAS-specific deployment descriptor, specify that this PK is automatic:
*
jonas-entity
...
*
jdbc-mapping
*
automatic-pk+true*/automatic-pk
+
+
+
Page 93
Chapter 8. Developing Entity Beans 85
8.5. The Enterprise Bean Class
The EJB implementation class implements the bean’s business methods of the component interface and the methods dedicated to the EJB environment, the interface of which is explicitly defined in the EJB specification. The class must implement the javax.ejb.EntityBean interface, must be defined as public, cannot be abstract for CMP 1.1, and must be abstract for CMP 2.0 (in this case, the abstract methods are the get and set accessor methods of the bean’s cmp and cmr fields). Following is a list of the EJB-environment dedicated methods that the EJB provider must develop.
The first set of methods are those corresponding to the create and find methods of the Home interface:
public PrimaryKeyClass ejbCreate(...);
This method is invoked by the container when a client invokes the corresponding create operation on the enterprise Bean’s home interface. The method should initialize instance’s variables from the input arguments. The returned object should be the primary key of the created instance. For bean-managed persistence, the bean provider should develop here the JDBC code to create the corresponding data in the database. For container-managed persistence, the container will perform the database insert after the ejbCreate method completes and the return value should be null.
public void ejbPostCreate(...);
There is a matching ejbPostCreate method (same input parameters) for each ejbCreate method. The container invokes this method after the execution of the matching ejbCreate(...) method. During the ejbPostCreate method, the object identity is available.
,
public
managed persistence only
PrimaryKeyClass or Collection
The container invokes this method on a bean instance that is not associated with any particular object identity (some kind of class method ...) when the client invokes the corresponding method on the Home interface. The implementation uses the arguments to locate the requested object(s) in the database and returns a primary key (or a collection thereof). Currently, collections will be represented as java.util.Enumeration objects or java.util.Collection. The mandatory
FindByPrimaryKey method takes as argument a primary key type value and returns a primary
key object (it verifies that the corresponding entity exists in the database). For container-managed persistence, the bean provider does not have to write these finder methods; they are generated
at deployment time by the EJB platform tools. The information needed by the EJB platform for automatically generating these finder methods should be provided by the bean programmer. The EJB 1.1 specification does not specify the format of this finder method description; for JOnAS, the CMP 1.1 finder methods description should be provided in the JOnAS-specific deployment descriptor of the Entity Bean (as an SQL query). Refer to Section 8.7 Configuring Database Access for Container-Managed Persistence. The EJB 2.0 specification defines a standard way to describe these finder methods, that is, in the standard deployment descriptor, as an EJB-QL query. Also refer to Section 8.7 Configuring Database Access for Container-Managed Persistence. Then, the methods of the javax.ejb.EntityBean interface must be implemented:
public void setEntityContext(EntityContext ic);
Used by the container to pass a reference to the EntityContext to the bean instance. The container invokes this method on an instance after the instance has been created. Generally, this method is used to store this reference in an instance variable.
public void unSetEntityContext();
Unset the associated entity context. The container calls this method before removing the instance. This is the last method the container invokes on the instance.
public void ejbActivate();
The container invokes this method when the instance is taken out of the pool of available in­stances to become associated with a specific EJB object. This method transitions the instance to the ready state.
-
ejbFind.method
/
(...); // for bean
Page 94
86 Chapter 8. Developing Entity Beans
public void ejbPassivate();
The container invokes this method on an instance before the instance becomes dissociated with a specific EJB object. After this method completes, the container will place the instance into the pool of available instances.
public void ejbRemove();
This method is invoked by the container when a client invokes a remove operation on the Enter­prise Bean. For entity beans with bean-managed persistence, this method should contain the JDBC code to remove the corresponding data in the database. For container-managed
persistence, this method is called before the container removes the entity representation in
the database.
public void ejbLoad();
The container invokes this method to instruct the instance to synchronize its state by loading it from the underlying database. For bean-managed persistence, the EJB provider should code at this location the JDBC statements for reading the data in the database. For
container-managed persistence, loading the data from the database will be done
automatically by the container just before ejbLoad is called, and the ejbLoad method should only contain some “after loading calculation statements.”
public void ejbStore();
The container invokes this method to instruct the instance to synchronize its state by storing it to the underlying database. For bean-managed persistence, the EJB provider should code at this location the JDBC statements for writing the data in the database. For entity beans with container-managed persistence, this method should only contain some “pre-store statements,” since the container will extract the container-managed fields and write them to the database just after the ejbStore method call.
8.5.1. Enterprise Bean Class Example
The following examples are for container-managed persistence with EJB 1.1 and EJB 2.0. For bean­managed persistence, refer to the examples delivered with your specific platform.
8.5.1.1. CMP 1.1
package eb;
import java.rmi.RemoteException; import javax.ejb.EntityBean; import javax.ejb.EntityContext; import javax.ejb.ObjectNotFoundException; import javax.ejb.RemoveException; import javax.ejb.EJBException;
public class AccountImplBean implements EntityBean {
// Keep the reference on the EntityContext protected EntityContext entityContext;
// Object state public Integer accno; public String customer; public double balance;
public Integer ejbCreate(int val_accno, String val_customer,
double val_balance) {
Page 95
Chapter 8. Developing Entity Beans 87
// Init object state accno = new Integer(val_accno); customer = val_customer; balance = val_balance; return null;
}
public void ejbPostCreate(int val_accno, String val_customer,
double val_balance) { // Nothing to be done for this simple example.
}
public void ejbActivate() {
// Nothing to be done for this simple example.
}
public void ejbLoad() {
// Nothing to be done for this simple example, // in implicit persistence.
}
public void ejbPassivate() {
// Nothing to be done for this simple example.
}
public void ejbRemove() {
// Nothing to be done for this simple example, // in implicit persistence.
}
public void ejbStore() {
// Nothing to be done for this simple example, // in implicit persistence.
}
public void setEntityContext(EntityContext ctx) {
// Keep the entity context in object entityContext = ctx;
}
public void unsetEntityContext() {
entityContext = null;
}
public double getBalance() {
return balance;
}
public void setBalance(double d) {
balance = balance + d;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String c) {
customer = c;
}
public int getNumber() {
Page 96
88 Chapter 8. Developing Entity Beans
return accno.intValue();
}
}
8.5.1.2. CMP 2.0
import java.rmi.RemoteException; import javax.ejb.EntityBean; import javax.ejb.EntityContext; import javax.ejb.ObjectNotFoundException; import javax.ejb.RemoveException; import javax.ejb.CreateException; import javax.ejb.EJBException;
public abstract class AccountImpl2Bean implements EntityBean {
// Keep the reference on the EntityContext protected EntityContext entityContext;
/*==== Abstract set and get accessors for cmp fields ====*/
public abstract String getCustomer(); public abstract void setCustomer(String customer);
public abstract double getBalance(); public abstract void setBalance(double balance);
public abstract int getAccno(); public abstract void setAccno(int accno);
/*================= ejbCreate methods ===================*/
public Integer ejbCreate(int val_accno,
String val_customer, double val_balance) throws CreateException {
// Init object state setAccno(val_accno); setCustomer(val_customer); setBalance(val_balance); return null;
}
public void ejbPostCreate(int val_accno, String val_customer,
double val_balance) { // Nothing to be done for this simple example.
}
/*========= javax.ejb.EntityBean implementation =========*/
public void ejbActivate() {
// Nothing to be done for this simple example.
}
public void ejbLoad() {
// Nothing to be done for this simple example, // in implicit persistence.
Page 97
Chapter 8. Developing Entity Beans 89
}
public void ejbPassivate() {
// Nothing to be done for this simple example.
}
public void ejbRemove() throws RemoveException {
// Nothing to be done for this simple example, // in implicit persistence.
}
public void ejbStore() {
// Nothing to be done for this simple example, // in implicit persistence.
}
public void setEntityContext(EntityContext ctx) {
// Keep the entity context in object entityContext = ctx;
}
public void unsetEntityContext() {
entityContext = null;
}
/**
* Business method to get the Account number
*/
public int getNumber() {
return getAccno();
}
}
8.6. Writing Database Access Operations (Bean-Managed Persistence)
For bean-managed persistence, data access operations are developed by the bean provider using the JDBC interface. However, getting database connections must be obtained through the
javax.sql.DataSource interface on a datasource object provided by the EJB platform. This
is mandatory since the EJB platform is responsible for managing the connection pool and for transaction management. Thus, to get a JDBC connection, in each method performing database operations, the bean provider must:
Call the getConnection(...) method of the DataSource object to obtain a connection to perform
the JDBC operations in the current transactional context (if there are JDBC operations)
Call the close() method on this connection after the database access operations so that the con-
nection can be returned to the connection pool (and be dissociated from the potential current trans­action).
A method that performs database access must always contain the getConnection and close statements, as follows:
public void doSomethingInDB (...) {
conn = dataSource.getConnection(); ... // Database access operations
Page 98
90 Chapter 8. Developing Entity Beans
conn.close();
}
A DataSource object associates a JDBC driver with a database (as an ODBC datasource). It is created and registered in JNDI by the EJB server at launch time (refer also to Chapter 4 Configuring JDBC DataSources).
A DataSource object is a resource manager connection factory for java.sql.Connection objects, which implements connections to a database management system. The Enterprise Bean code refers to resource factories using logical names called Resource manager connection factory references. The resource manager connection factory references are special entries in the Enterprise Bean envi­ronment. The bean provider must use resource manager connection factory references to obtain the datasource object as follow:
Declare the resource reference in the standard deployment descriptor using a resource-ref ele-
ment.
Look up the datasource in the Enterprise Bean environment using the JNDI interface (refer to
Chapter 12 Enterprise Bean Environment).
The deployer binds the resource manager connection factory references to the actual resource factories that are configured in the server. This binding is done in the JOnAS-specific deployment descriptor using the jonas-resource element.
8.6.1. Database Access Operation Example
The declaration of the resource reference in the standard deployment descriptor looks like the follow­ing:
0
resource-ref
0
res-ref-name1jdbc/AccountExplDs0/res-ref-name
0
res-type1javax.sql.DataSource0/res-type
0
res-auth1Container0/res-auth
0
/resource-ref
The2res-auth3element indicates which of the two resource manager authentication approaches is used:
1
1
1
1
1
Container: the deployer sets up the sign-on information.
Bean: the bean programmer should use the getConnection method with user and password param-
eters.
The JOnAS-specific deployment descriptor must map the environment JNDI name of the resource to
2
the actual JNDI name of the resource object managed by the EJB server. This is done in the resource
0
0
element.
3
jonas-entity
0
ejb-name1AccountExpl0/ejb-name
0
jndi-name1AccountExplHome0/jndi-name
0
jonas-resource
0
res-ref-name1jdbc/AccountExplDs0/res-ref-name
0
jndi-name1jdbc_10/jndi-name
0
/jonas-resource
/jonas-entity
1
1
1
1
1
1
1
1
jonas-
The ejbStore method of the same Account example with bean-managed persistence is shown in the following example. It performs JDBC operations to update the database record representing the state of the Entity Bean instance. The JDBC connection is obtained from the datasource associated with the
Page 99
Chapter 8. Developing Entity Beans 91
bean. This datasource has been instantiated by the EJB server and is available for the bean through its resource reference name, which is defined in the standard deployment descriptor.
In the bean, a reference to a datasource object of the EJB server is initialized:
it = new InitialContext();
ds = (DataSource)it.lookup("java:comp/env/jdbc/AccountExplDs");
Then, this datasource object is used in the implementation of the methods performing JDBC opera­tions, such as ejbStore, as illustrated in the following:
public void ejbStore
Connection conn = null; PreparedStatement stmt = null; try { // get a connection
conn = ds.getConnection(); // store Object state in DB stmt = conn.prepareStatement("update account
set customer=?,balance=? where accno=?"); stmt.setString(1, customer); stmt.setDouble(2, balance); Integer pk = (Integer)entityContext.getPrimaryKey(); stmt.setInt(3, pk.accno); stmt.executeUpdate();
} catch (SQLException e) {
throw new javax.ejb.EJBException("Failed to store bean
to database", e);
} finally {
try {
if (stmt != null) stmt.close(); // close statement if (conn != null) conn.close(); // release connection
} catch (Exception ignore) {}
}
}
Note that the close statement instruction may be important if the server is intensively accessed by many clients performing Entity Bean access. If the statement is not closed in the finally block, since stmt is in the scope of the method, it will be deleted at the end of the method (and the close will be implicitly done). However, it may be some time before the Java garbage collector deletes the statement object. Therefore, if the number of clients performing Entity Bean access is important, the DBMS may raise a “too many opened cursors” exception (a JDBC statement corresponds to a DBMS cursor). Since connection pooling is performed by the platform, closing the connection will not result in a physical connection close, therefore opened cursors will not be closed. Thus, it is preferable to explicitly close the statement in the method.
It is a good programming practice to put the JDBC connection and JDBC statement close operations in a finally block of the try statement.
8.7. Configuring Database Access for Container-Managed Persistence
The standard way to indicate to an EJB platform that an Entity Bean has container-managed persis­tence is to fill the tainer," and to fill the managed fields (the fields that the container will have in charge to make persistent). The CMP version (1.x or 2.x) should also bespecified in the descriptor, this is represented by the following lines:
persistence-type5container4/persistence-type
4
4
persistence-type
4
cmp-field
5
tag of the deployment descriptor with the value "con-
5
tag of the deployment descriptor with the list of container-
6
cmp-version7tag. In the textual format of the deployment
5
Page 100
92 Chapter 8. Developing Entity Beans
8
cmp-version91.x8/cmp-version
8
cmp-field
8
field-name9fieldOne8/field-name
8
/cmp-field
8
cmp-field
8
field-name9fieldTwo8/field-name
8
/cmp-field
9
9
9
9
9
9
9
With container-managed persistence the programmer need not develop the code for access­ing the data in the relational database; this code is included in the container itself (generated by the platform tools). However, for the EJB platform to know how to access the database and which data to read and write in the database, two types of information must be provided with the bean:
First, the container must know which database to access and how to access it. To do this, the only
required information is the name of the DataSource that will be used to get the JDBC connection. For container-managed persistence, only one DataSource per bean should be used.
Then, it is necessary to know the mapping of the bean fields to the underlying database (which table,
which column). For CMP 1.1 or CMP 2.0, this mapping is specified by the deployer in the JOnAS­specific deployment descriptor. Note that for CMP 2.0, this mapping may be entirely generated by JOnAS.
The EJB specification does not specify how this information should be provided to the EJB platform by the bean deployer. Therefore, what is described in the remainder of this section is specific to JOnAS.
For CMP 1.1, the bean deployer is responsible for defining the mapping of the bean fields to the database table columns. The name of the DataSource can be set at deployment time, since it depends on the EJB platform configuration. This database configuration information is defined in the JOnAS­specific deployment descriptor via the jdbc-mapping element. The following example defines the mapping for a CMP 1.1 Entity Bean:
8
jdbc-mapping
8
jndi-name9jdbc_18/jndi-name
8
jdbc-table-name9accountsample8/jdbc-table-name
8
cmp-field-jdbc-mapping
8
field-name9mAccno8/field-name
8
jdbc-field-name9accno8/jdbc-field-name
8
/cmp-field-jdbc-mapping
8
cmp-field-jdbc-mapping
8
field-name9mCustomer8/field-name
8
jdbc-field-name9customer8/jdbc-field-name
8
/cmp-field-jdbc-mapping
8
cmp-field-jdbc-mapping
8
field-name9mBalance8/field-name
8
jdbc-field-name9balance8/jdbc-field-name
8
/cmp-field-jdbc-mapping
8
/jdbc-mapping
9
9
9
9
9
9
9
9
9
9
9
9
9
9
9
9
jdbc_1 is the JNDI name of the DataSource object identifying the database. accountsample is the
name of the table used to store the bean instances in the database. mAccno, mCustomer, and
mBalance are the names of the container-managed fields of the bean to be stored in the accno, customer, and balance columns of the accountsample table. This example applies to container-managed persistence. For bean-managed persistence, the database mapping
does not exist.
For a CMP 2.0 Entity Bean, only the jndi-name element of the jdbc-mapping is mandatory, since the mapping may be generated automatically:
8
jdbc-mapping
8
jndi-name9jdbc_18/jndi-name
9
9
Loading...