background image

160

Chapter 16. Developing Web Components

16.4. Accessing an EJB from a Servlet or JSP Page

Starting with JOnAS 2.6 with its

web

container service, it is possible to access an enterprise Java bean

and its environment in a J2EE-compliant way.
The following sections describe:

1. How to access the Remote Home interface of a bean.
2. How to access the Local Home interface of a bean.
3. How to access the environment of a bean.
4. How to start transactions in servlets.

Note

All the following code examples are taken from the The EarSample example provided in the JOnAS

distribution.

16.4.1. Accessing the Remote Home Interface of a Bean:

In this example the servlet gets the Remote Home interface

OpHome

registered in JNDI using an EJB

reference, then creates a new instance of the Session Bean:

import javax.naming.Context;
import javax.naming.InitialContext;

//remote interface
import org.objectweb.earsample.beans.secusb.Op;
import org.objectweb.earsample.beans.secusb.OpHome;

Context initialContext = null;
try {

initialContext = new InitialContext();

} catch (Exception e) {

out.print("

¤

li

¥

Cannot get initial context for JNDI: ");

out.println(e + "

¤

/li

¥

");

return;

}

// Connecting to OpHome through JNDI

OpHome opHome = null;
try {

opHome = (OpHome)
PortableRemoteObject.narrow(initialContext.lookup \

("java:comp/env/ejb/Op"), OpHome.class);

} catch (Exception e) {

out.println("

¤

li

¥

Cannot lookup java:comp/env/ejb/Op: "

+ e + "

¤

/li

¥

");

return;

}
// OpBean creation
Op op = null;
try {

op = opHome.create("User1");

} catch (Exception e) {

out.println("

¤

li

¥

Cannot create OpBean: " + e + "

¤

/li

¥

");

return;

}

Summary of Contents for Application Server

Page 1: ...Red Hat Application Server JOnAS User Guide ...

Page 2: ... registered trademark and the Red Hat Shadow Man logo RPM and the RPM 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 CeleronTM are registered trademarks of Intel Corporation EJBTM J2EETM JCATM JCEETM JDBCTM JDOTM JMSTM RMITM and SunTM and Sun ...

Page 3: ...s 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 jona...

Page 4: ...ons 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...

Page 5: ...r 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 2...

Page 6: ...57 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 Access...

Page 7: ... 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: ... 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 specific...

Page 10: ...pen 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...

Page 11: ...th 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...

Page 12: ...ted 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 applica...

Page 13: ... 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 ...

Page 14: ... 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 EJB...

Page 15: ... 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 sc...

Page 16: ...tion 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 CRL...

Page 17: ...e 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 transpa...

Page 18: ... 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 acc...

Page 19: ...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 JOnA...

Page 20: ...ed 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...

Page 21: ...g 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 in...

Page 22: ...14 Chapter 1 Java Open Application Server JOnAS a J2EE Platform ...

Page 23: ...ctory 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 standa...

Page 24: ...fault 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 p...

Page 25: ...P 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 resour...

Page 26: ...bm 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...

Page 27: ...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...

Page 28: ... 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: ...ation 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_BA...

Page 30: ...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 orde...

Page 31: ...OT 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 ...

Page 32: ...tion 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 Gen...

Page 33: ...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 r...

Page 34: ...es 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 enable...

Page 35: ...ist 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 ...

Page 36: ...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...

Page 37: ...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 th...

Page 38: ...ng 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...

Page 39: ...s 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 jdbc oracle thin hostname sql net_port_number ORACLE_SID If using an Oracle OCI JDBC driver the URL is jdbc oracle oci7 or...

Page 40: ...he 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 of the JONAS_ROOT conf jonas realm xml file Datasource realm users groups and roles information...

Page 41: ...m 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...

Page 42: ... security howto roles users user name jonas_user password jonas_password roles jonas users memoryrealm jonas memoryrealm 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 conta...

Page 43: ... 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 groupOfUniqu...

Page 44: ...cation 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 To...

Page 45: ... 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 certificate will ...

Page 46: ...RLs 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...

Page 47: ...le 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 ...

Page 48: ...on 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 se...

Page 49: ...uration 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...

Page 50: ... 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 jon...

Page 51: ...er 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 ...

Page 52: ...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 messagin...

Page 53: ...te 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 Run...

Page 54: ...g Nothing default joram admin cfg name is then set HostName Name of the host where the JORAM server runs used for accessing a remote JORAM server non collocated mode and for building appropriate connection factories Any host name ex myHost Nothing default localhost name is then set ServerPort Port the JORAM server is listening on used for accessing a remote JORAM server non collocated mode and for...

Page 55: ...onas 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 Connect...

Page 56: ...ry 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 persiste...

Page 57: ...9 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: ...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...

Page 60: ...ies 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 ...

Page 61: ...ections in the pool 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 ...

Page 62: ...ne 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: ...sed 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 logg...

Page 64: ...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 lo...

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: ...r jonas version Print the current version of JOnAS 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 e...

Page 68: ...tion 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 ser...

Page 69: ...llector 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 serv...

Page 70: ...1 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 progr...

Page 71: ...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 ...

Page 72: ...ion 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...

Page 73: ... 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 T...

Page 74: ... 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 th...

Page 75: ...se 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 whi...

Page 76: ...he 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 jndi name element of the jonas resource element i...

Page 77: ...rgument 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 rar...

Page 78: ...70 Chapter 6 JOnAS Command Reference ...

Page 79: ...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 Manageme...

Page 80: ......

Page 81: ...rfaces 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 ca...

Page 82: ...e 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 incl...

Page 83: ... 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 tr...

Page 84: ...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 va...

Page 85: ...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 ...

Page 86: ...78 Chapter 7 Developing Session Beans ...

Page 87: ...ness 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 cl...

Page 88: ...ignatures 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 d...

Page 89: ...use 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 use...

Page 90: ...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 mus...

Page 91: ...ect 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 addres...

Page 92: ...entity ejb name AddressEJB ejb name jdbc mapping jndi name jdbc_1 jndi name automatic pk field name FieldPkAuto automatic pk field name jdbc mapping jonas entity 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...

Page 93: ... 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 corres...

Page 94: ...oad 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 persisten...

Page 95: ...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...

Page 96: ...ublic 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_balanc...

Page 97: ...ng 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 DataSour...

Page 98: ...S 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 ref1 0 res ref name1 jdbc AccountExplDs 0 res ref name1 0 res type1 javax sql DataSource 0 res type1 0 res auth1 Container 0 res auth1 0 resource ref1 The 2 res auth3 element in...

Page 99: ...t 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 corres...

Page 100: ...n 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 ...

Page 101: ...clause that will be used in the generated finder method implementation to query the relational table storing the bean entities Note that the table column names should be used not the bean field names Example finder method jdbc mapping jonas method method name findLargeAccounts method name jonas method jdbc where clause where balance jdbc where clause finder method jdbc mapping The previous finder ...

Page 102: ...specific information Mapping CMP2 0 Entity Beans to the database is described in detail Note that the database mapping can be created entirely by JOnAS in which case the JOnAS specific deployment descriptor for an Entity Bean should contain only the datasource and the element indicating how the database should be initialized 8 9 Standard CMP2 0 Aspects This section briefly describes the new featur...

Page 103: ...efault cmp version value if not specified is 2 x Note that for CMP 2 0 the information defining the behavior of the implementation of a find method method is located in the standard deployment descriptor as an EJB QL query this is not JOnAS specific information For CMP 1 1 this information is located in the JOnAS specific deployment descriptor as an SQL WHERE clause specified in a B finder method ...

Page 104: ...ent on this map per It is possible to deploy generate container code a bean for several mappers in order to change the database that is the DataSource file without redeploying the bean These mappers should be specified as the mappernames argument of the GenIC command or as the mappernames attribute of the JOnAS ANT EJB JAR task The value is a comma separated list of mapper names for which the cont...

Page 105: ... Entity Bean is stored use the jndi name element of the jdbc mapping This is the JNDI name of the DataSource representing the database storing the Entity Bean F jdbc mappingG F jndi nameG jdbc_1 F jndi nameG F jdbc mappingG For a CMP 2 0 Entity Bean the JOnAS specific deployment descriptor contains an additional element cleanup to be specified before the jdbc mapping element The cleanup element ca...

Page 106: ...nameI idA H field nameI H cmp fieldI H cmp fieldI H field nameI f H field nameI H cmp fieldI H entityI 8 11 2 2 Database Mapping t_A c_idA c_f 8 11 2 3 JOnAS Deployment Descriptor H jonas entityI H ejb nameI A H ejb nameI H jdbc mappingI H jndi nameI jdbc_1 H jndi nameI H jdbc table nameI t_A H jdbc table nameI H cmp field jdbc mappingI H field nameI idA H field nameI H jdbc field nameI c_idA H jd...

Page 107: ... 1 1 Standard Deployment Descriptor J entityK J ejb nameK A J ejb nameK J cmp fieldK J field nameK idA J field nameK J cmp fieldK J primkey fieldK idA J primkey fieldK J entityK J entityK J ejb nameK B J ejb nameK J cmp fieldK J field nameK idB J field nameK J cmp fieldK J primkey fieldK idB J primkey fieldK J entityK J relationshipsK J ejb relationK J ejb relation nameK a b J ejb relation nameK J...

Page 108: ...owns the CMR field 8 11 3 1 3 JOnAS Deployment Descriptor L jonas entityM L ejb nameM A L ejb nameM L jdbc mappingM L jndi nameM jdbc_1 L jndi nameM L jdbc table nameM t_A jdbc table nameM L cmp field jdbc mappingM L field nameM idA L field nameM L jdbc field nameM c_idA L jdbc field nameM L cmp field jdbc mappingM L jdbc mappingM L jonas entityM L jonas entityM L ejb nameM B L ejb nameM L jdbc ma...

Page 109: ...ptional Default value is the abstract schema name of the destination bean suffixed by _ and by its primary key field B_idb in the example Table 8 2 1 1 unidirectional relationships Default values 8 11 3 2 1 1 bidirectional relationships In contrast to 1 1 unidirectional relationships there is a CMR field in both of the beans thus making two types of mapping possible 8 11 3 2 1 Standard Deployment ...

Page 110: ... hold a foreign key Case 1 t_A c_idA cfk_idB t_B c_idB Case 2 t_A c_idA t_B c_idB cfk_idA 8 11 3 2 3 JOnAS Deployment Descriptor Case 1 P jonas ejb relationQ P ejb relation nameQ a b P ejb relation nameQ P jonas ejb relationship roleQ P ejb relationship role nameQ a2b P ejb relationship role nameQ P foreign key jdbc mappingQ P foreign key jdbc nameQ cfk_idb P foreign key jdbc nameQ P foreign key j...

Page 111: ...ues are similar to those of the 1 1 unidirectional relationship 8 11 3 3 1 N unidirectional relationships 8 11 3 3 1 Standard Deployment Descriptor R relationshipsS R ejb relationS R ejb relation nameS a b R ejb relation nameS R ejb relationship roleS R A S B S R ejb relationship role nameS a2b R ejb relationship role nameS R multiplicityS One R multiplicityS R relationship role sourceS R ejb name...

Page 112: ...oreign key jdbc nameU cfk_ida T foreign key jdbc nameU T foreign key jdbc mappingU T jonas ejb relationship roleU T jonas ejb relationU jonas ejb relation Optional foreign key jdbc name Optional Default value is the abstract schema name of the destination bean of the one side of the relationship that is the source bean of the relationship role with multiplicity one suffixed by _ and by its primary...

Page 113: ...nameW B V ejb nameW V relationship role sourceW V cmr fieldW V cmr field nameW a V cmr field nameW V cmr fieldW V ejb relationship roleW V ejb relationW V relationshipsW 8 11 3 4 2 Database Mapping t_A c_idA t_B c_idB cfk_idA In this case the foreign key must be in the table of the bean that is on the many side of the re lationship that is in the table of the source bean of the relationship role w...

Page 114: ...the relationship role with multiplicity many 8 11 3 5 1 Standard Deployment Descriptor X relationshipsY X ejb relationY X ejb relation nameY a b X ejb relation nameY X ejb relationship roleY X A Y B Y X ejb relationship role nameY a2b X ejb relationship role nameY X multiplicityY Many X multiplicityY X relationship role sourceY X ejb nameY A X ejb nameY X relationship role sourceY X cmr fieldY X c...

Page 115: ...ion Optional foreign key jdbc name Optional Default value is the abstract schema name of the destination bean of the one side of the relationship that is the source bean of the relationship role with multiplicity one suffixed by _ and by its primary key field B_idb in the example Table 8 5 N 1 unidirectional relationships Default values 8 11 3 6 N M Unidirectional Relationships 8 11 3 6 1 Standard...

Page 116: ...ign keys of each Entity Bean table 8 11 3 6 3 JOnAS Deployment Descriptor jonas ejb relation ejb relation name a b ejb relation name jdbc table name tJoin_AB jdbc table name jonas ejb relationship role ejb relationship role name a2b ejb relationship role name foreign key jdbc mapping foreign key jdbc name cfk_idb foreign key jdbc name foreign key jdbc mapping jonas ejb relationship role jonas ejb ...

Page 117: ...ment Descriptor relationships_ ejb relation_ ejb relation name_ a b ejb relation name_ ejb relationship role_ A _ B _ ejb relationship role name_ a2b ejb relationship role name_ multiplicity_ Many multiplicity_ relationship role source_ ejb name_ A ejb name_ relationship role source_ cmr field_ cmr field name_ b cmr field name_ cmr field type_ java util Collection cmr field type_ cmr field_ ejb re...

Page 118: ...tionship role namea a2b ejb relationship role namea foreign key jdbc mappinga foreign key jdbc namea cfk_idb foreign key jdbc namea foreign key jdbc mappinga jonas ejb relationship rolea jonas ejb relationship rolea ejb relationship role namea b2a ejb relationship role namea foreign key jdbc mappinga foreign key jdbc namea cfk_ida foreign key jdbc namea foreign key jdbc mappinga jonas ejb relation...

Page 119: ...reason not all types of relationship are illustrated below 8 11 4 1 1 1 Bidirectional Relationships 8 11 4 1 1 Standard Deployment Descriptor b entityc b ejb namec A b ejb namec b prim key classc p PkA b prim key classc b cmp fieldc b field namec id1A b field namec b cmp fieldc b cmp fieldc b field namec id2A b field namec b cmp fieldc b entityc b entityc b ejb namec B b ejb namec b prim key class...

Page 120: ...namee d multiplicitye One d multiplicitye d relationship role sourcee d ejb namee B d ejb namee d relationship role sourcee d cmr fielde d cmr field namee a d cmr field namee d cmr fielde d ejb relationship rolee d ejb relatione d relationshipse 8 11 4 1 2 Database Mapping Two mappings are possible one or another of the tables may hold the foreign key Case 1 t_A c_id1A c_id2A cfk_id1B cfk_id2B t_B...

Page 121: ...ionship role nameg b2a f ejb relationship role nameg f foreign key jdbc mappingg f foreign key jdbc nameg cfk_id1a f foreign key jdbc nameg f key jdbc nameg c_id1a f key jdbc nameg f foreign key jdbc mappingg f foreign key jdbc mappingg f foreign key jdbc nameg cfk_id2a f foreign key jdbc nameg f key jdbc nameg c_id2a f key jdbc nameg f foreign key jdbc mappingg f jonas ejb relationship roleg f jo...

Page 122: ...iplicityi Many h multiplicityi h relationship role sourcei h ejb namei A h ejb namei h relationship role sourcei h cmr fieldi h cmr field namei b h cmr field namei h cmr field typei java util Collection h cmr field typei h cmr fieldi h ejb relationship rolei h ejb relationship rolei h B i A i h ejb relationship role namei b2a h ejb relationship role namei h multiplicityi Many h multiplicityi h rel...

Page 123: ...hip rolek j ejb relationship role namek b2a j ejb relationship role namek j foreign key jdbc mappingk j foreign key jdbc namek cfk_id1a j foreign key jdbc namek j key jdbc namek c_id1a j key jdbc namek j foreign key jdbc mappingk j foreign key jdbc mappingk j foreign key jdbc namek cfk_id2a j foreign key jdbc namek j key jdbc namek c_id2a j key jdbc namek j foreign key jdbc mappingk j jonas ejb re...

Page 124: ...policy you can choose the transaction isolation in your database This may be interesting for applications that heavily use transactional read only operations or when the shared flag is needed It does not work with all databases and is expensive in terms of memory Note If you deploy CMP1 beans you should use the default policy only container serialized unless your beans are read only In this latter...

Page 125: ...lement of the JOnAS specific deployment descriptor This method is responsible for determining if the state of the bean has been changed By doing this the container determines if it must store data in the database or not Note This is not required with CMP2 entity beans because the container does this automatically 8 12 6 1 Example The bean implementation manages a boolean isDirty and implements a m...

Page 126: ...erver at a minimum when the server is stopped When a transaction is started on this instance After a configurable timeout If the bean is always accessed with no transaction it may be prudent to periodically store the bean state on disk This passivation timeout can be configured in the JOnAS specific deployment descriptor with a non mandatory tag n passivation timeouto p jonas entityq p ejb nameq I...

Page 127: ...s moment refer to Section 9 5 Transactional Aspects for more details The onMessage method can call other methods on the MDB itself or on other beans and can involve other resources by accessing databases or by sending messages Such resources are accessed the same way as for other beans entity or session that is through resource references declared in the deployment descriptor The JOnAS container m...

Page 128: ...JMS message selector this is a JMS concept which allows the filtering of the messages sent to the destination A message driven destination which contains the destination type Queue or Topic and the sub scription durability in the case of Topic The following example illustrates such a deployment descriptor r enterprise beanss r message drivens r descriptions Describe here the message driven bean Md...

Page 129: ...o the MDB through a destination object obtained via JNDI as follows Queue q context lookup sampleTopic If the client sending messages to the MDB is an EJB component itself it is preferable that it use a resource environment reference to obtain the destination object The use of resource environment references is described in Section 26 2 Writing JMS Operations Within an Application Component 9 3 Ad...

Page 130: ...tances can execute concurrently on behalf of the same MDB The default size of the pool of thread is 10 and it may be customized via the jonas property jonas service ejb mdbthreadpoolsize which is specified in the jonas properties file as in the following example jonas service ejb mdbthreadpoolsize 50 9 4 Running a Message Driven Bean To deploy and run a Message Driven Bean perform the following st...

Page 131: ...onfiguration for the MOM such as changing the default host which is local host or the default connection port number which is 16010 requires defining the additional jonas service jms url configuration property as presented in the following case 3 Launching the MOM on another host This requires defining the jonas service jms url configuration property When using JO RAM its value should be the JORAM...

Page 132: ...t of the started transaction then enlist the resource manager associated with the arriving message and all the resource managers ac cessed by the onMessage method If the onMessage method invokes other Enterprise Beans the container passes the transaction context with the invocation Therefore the transaction started at the onMessage method execution may involve several operations such as accessing ...

Page 133: ...ge Driven Bean lis tening on the OrdersQueue Queue On receipt of a Text message on this queue it writes the corre sponding String as a new line in a file Order txt The example also includes a CMP Entity Bean JONAS_ROOT examples src mdb sampleappli Stock that handles a stock table A Stock item is composed of a Stockid String which is the primary key and a Quantity int The method decreaseQuantity in...

Page 134: ...n JNDI if it does not already exist 1 Run the JOnAS Server service jonas start 2 Deploy the sampleappli container jonas admin a sampleappli jar 3 Run the EJB client jclient sampleappli SampleAppliClient 4 Stop the server service jonas stop 9 7 Tuning the Message Driven Bean Pool A pool is handled by JOnAS for each Message Driven Bean The pool can be configured in the JOnAS specific deployment desc...

Page 135: ...Message Driven Bean Pool Example v jonas ejb jarw v jonas message drivenw v ejb namew Mdb v ejb namew v jndi namew mdbTopic v jndi namew v max cache sizew 20 v max cache sizew v min pool sizew 10 v min pool sizew v jonas message drivenw v jonas ejb jarw ...

Page 136: ...128 Chapter 9 Developing Message Driven Beans ...

Page 137: ...xml jonas ejb jar_X_Y xsd The file name of the JOnAS specific XML deployment descriptor must be the file name of the standard XML deployment descriptor prefixed by jonas The parser gets the specified schema via the classpath schemas are packaged in the JONAS_ROOT lib common ow_jonas jar file The standard deployment descriptor should include the following structural information for each En terprise...

Page 138: ...transaction typey x env entryy x env entry namey name1 x env entry namey x env entry typey java lang String x env entry typey x env entry valuey value1 x env entry valuey x env entryy x ejb refy x ejb ref namey ejb ses1 x ejb ref namey x ejb ref typey session x ejb ref typey x homey tests SS1Home x homey x remotey tests SS1 x remotey x ejb refy x resource refy x res ref namey jdbc mydb x res ref n...

Page 139: ...lns 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 z jonas session z ejb name ExampleOne z ejb name z jndi name ExampleOneHome z jndi name z jonas ejb ref z ejb ref name ejb ses1 z ejb ref name z jndi name SS1Home_one z jndi name z jonas ejb ref z jonas resour...

Page 140: ...ue env entry entity enterprise beans assembly descriptor container transaction method ejb name ExampleTwo ejb name method name method name method trans attribute Supports trans attribute container transaction assembly descriptor ejb jar xml version 1 0 encoding ISO 8859 1 jonas ejb jar xmlns http www objectweb org jonas ns xmlns xsi http www w3 org 2001 XMLSchema instance xsi schemaLocation http w...

Page 141: ...jonas method jdbc where clause where dbf1 jdbc where clause finder method jdbc mapping jdbc mapping jonas entity jonas ejb jar 10 4 Tips Although some characters such as are legal it is good practice to replace them with XML entity references The following is a list of the predefined entity references for XML lt less than gt greater than amp ampersand apos apostrophe quot quotation mark ...

Page 142: ...134 Chapter 10 Defining the Deployment Descriptor ...

Page 143: ...ew transaction is started for the execution of the method and committed before the method result is sent to the caller RequiresNew The method will always be 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 suspend...

Page 144: ... container transaction container transaction method ejb name AccountImpl ejb name method name getBalance method name method trans attribute Required trans attribute container transaction container transaction method ejb name AccountImpl ejb name method name setBalance method name method trans attribute Mandatory trans attribute container transaction assembly descriptor In this example for all meth...

Page 145: ...nsaction boundaries demarcation In any case the distribution aspects of the transactions are completely transparent to the bean provider and to the application assembler This means that a transaction may involve beans located on several JOnAS servers and that the platform itself will handle management of the global transaction It will perform the two phase commit protocol between the different ser...

Page 146: ...OnAS server which embeds a Java Transaction Monitor 2 Case 2 The three beans are located on different JOnAS servers one of them running the Java Transaction Monitor which manages the global transaction 3 Case 3 The three beans are located on different JOnAS servers the Java Transaction Monitor is running outside of any JOnAS server 4 Case 4 The three beans are located on different JOnAS servers Ea...

Page 147: ... with the same server configuration case 1 is the more appropriate If the beans should run on different machines case 4 is the more appropriate since it favors local transaction management If the beans should run on the same machine but require different server configurations case 2 is a good approach ...

Page 148: ...140 Chapter 11 Transactional Behavior of EJB Applications ...

Page 149: ...esses the environment using JNDI with names starting with java comp env 12 2 Environment Entries The bean provider declares all the bean environment entries in the deployment descriptor via the env entry element The deployer can set or modify the values of the environment entries A bean accesses its environment entries with a code similar to the following InitialContext ictx new InitialContext Con...

Page 150: ... resources for example JMS destinations by using logical names Resource environment references are defined in the standard deployment descriptor resource env ref resource env ref name jms stockQueue resource env ref name resource env ref type javax jms Queue resource env ref type resource env ref Binding of the resource environment references to administered objects in the target operational en vi...

Page 151: ...ean1 In the following example the ejb link element has been added to the ejb ref in the referring bean SSA and a part of the description of the target bean SS1 is shown session ejb name SSA ejb name ejb ref ejb ref name ejb ses1 ejb ref name ejb ref type session ejb ref type home tests SS1Home home remote tests SS1 remote ejb link SS1 ejb link ejb ref session session ejb name SS1 ejb name home tes...

Page 152: ...ession ejb name SS1 ejb name jndi name SS1Home_one jndi name jndi local name SS1LocalHome_one jndi local name jonas session The bean locates the home interface of the other Enterprise Bean using the EJB reference with the following code InitialContext ictx new InitialContext Context myenv ictx lookup java comp env SS1Home home SS1Home javax rmi PortableRemoteObject narrow myEnv lookup ejb ses1 SS1...

Page 153: ...ty requirements for the application is the small set of security roles rather than a large number of individual methods 13 2 1 Security Roles The application assembler can define one or more security roles in the deployment descriptor The application assembler then assigns groups of methods of the Enterprise Beans home and remote interfaces to the security roles in order to define the security vie...

Page 154: ...iptor method permission role name tomcat role name method ejb name Op ejb name method name method name method method permission 13 3 Programmatic Security Management Because not all security policies can be expressed declaratively the EJB architecture also provides a simple programmatic interface that the Bean programmer can use to access the security context from the business methods The javax ej...

Page 155: ...deployment de scriptor all the security role names used in the Enterprise Bean code Declaring the security roles references in the code allows the application assembler or deployer to link the names of the security roles used in the code to the actual security roles defined for an assembled application through the security role elements enterprise beans session ejb name Op ejb name ejb class sb Op...

Page 156: ...figuration described in the deployment descriptor The programmer makes these role references available to the Bean deployer or application assembler via the security role ref elements included in the session or entity elements of the deployment descriptor Then the Bean deployer or application assembler must map the security roles defined in the deployment descriptor to the specific roles of the ta...

Page 157: ... made up of The standard xml deployment descriptor in the format defined in the EJB 2 1 specification Refer to JONAS_ROOT xml ejb jar_2_1 xsd or http java sun com xml ns j2ee ejb jar_2_1 xsd This deployment descriptor must be stored with the name META INF ejb jar xml in the EJB JAR file The JOnAS specific XML deployment descriptor in the format defined in JONAS_ROOT xml jonas ejb jar_X_Y xsd This ...

Page 158: ...150 Chapter 14 EJB Packaging ...

Page 159: ...Enterprise Beans as stand alone application components in which case the EJB JAR must be installed in the JONAS_ROOT ejbjars directory The deployer may also choose to include them in WAR or EAR packaging which is presented in the following sections 15 1 2 The Deployment and Installation of Web and J2EE Applications Once the packaging of the application components has been completed as described in...

Page 160: ...ROOT examples src directory to build and install all ejb jar jar files for the examples To write a build xml file for ANT use the ejbjar task which is one of the optional EJB tasks defined in ANT see http jakarta apache org ant manual index html The ejbjar task contains a nested element called jonas which implements the deployment process described above interposi tion classes generation and EJB J...

Page 161: ...ployed in a web container created during the startup If the WAR file was not added in the jonas service web descriptors list the web components can be dynamically deployed using the jonas admin command or JonasAdmin tool 15 4 Deploying and Installing a J2EE Application Before deploying a J2EE application in the JOnAS application server first package its components in an EAR file as explained in Ch...

Page 162: ...154 Chapter 15 Application Deployment and Installation Guide ...

Page 163: ...ion components or as J2EE application components In both cases a WAR file will be created but the content of this file is different in the two situations In the first case the WAR contains the Web components and the Enterprise Beans In the second case the WAR does not contain the Enterprise Beans The EJB JAR file containing the Enterprise Beans is packed together with the WAR file containing the W...

Page 164: ......

Page 165: ...describes the web application etc resources web Contains HTML pages and images JSP pages can also be placed here src org objectweb earsample servlets Servlet sources src org objectweb earsample beans Beans sources If beans from another application will be used the bean directory is not needed 16 2 The JSP Pages Java Server Pages JSP is a technology that allows regular static HTML to be mixed with ...

Page 166: ...rm web secured where the jsp files communicate with the EJB via a proxy Java bean ViewProxy java http www objectweb org jonas current examples alarm beans org objectweb alarm beans ViewProxy java 16 3 The Servlets Servlets are modules of Java code that run in an application server for answering client requests Servlets are not tied to a specific client server protocol However they are most commonl...

Page 167: ...er out res getWriter out println html head title Your cart title head out println body out println h1 Content of your cart h1 br out println table The header of the table out println tr out println td font color lightgreen Product Reference font td out println td font color lightgreen Product Name font td out println td font color lightgreen Product Price font td out println tr Each iteration of t...

Page 168: ...mple the servlet gets the Remote Home interface OpHome registered in JNDI using an EJB reference then creates a new instance of the Session Bean import javax naming Context import javax naming InitialContext remote interface import org objectweb earsample beans secusb Op import org objectweb earsample beans secusb OpHome Context initialContext null try initialContext new InitialContext catch Excep...

Page 169: ...calHome thru JNDI OpLocalHome opLocalHome null try opLocalHome OpLocalHome initialContext lookup java comp env ejb OpLocal catch Exception e out println li Cannot lookup java comp env ejb OpLocal e li return This is found in the web xml file ejb local ref ejb ref name ejb OpLocal ejb ref name ejb ref type Session ejb ref type local home org objectweb earsample beans secusb OpLocalHome local home l...

Page 170: ... wants to start transactions via the UserTransaction import javax transaction UserTransaction We want to start transactions from client get UserTransaction UserTransaction utx null try utx UserTransaction initialContext lookup java comp UserTransaction catch Exception e out println li Cannot lookup java comp UserTransaction e li return try utx begin opLocal buy 10 opLocal buy 20 utx commit catch E...

Page 171: ...t descriptor must be the file name of the standard XML de ployment descriptor prefixed by jonas The parser gets the specified schema via the classpath schemas are packaged in the JONAS_ROOT lib common ow_jonas jar file The standard deployment descriptor web xml should contain structural information that includes the following The servlet s description including servlet s name servlet s class or js...

Page 172: ...oding ISO 8859 1 web app xmlns http java sun com xml ns j2ee xmlns xsi http www w3 org 2001 XMLSchema instance xsi schemaLocation http java sun com xml ns j2ee http java sun com xml ns j2ee web app_2_4 xsd version 2 4 servlet servlet name Op servlet name servlet class org objectweb earsample servlets ServletOp servlet class servlet servlet mapping servlet name Op servlet name url pattern secured O...

Page 173: ... ejb link secusb jar Op ejb link ejb ref reference on a local bean ejb local ref ejb ref name ejb OpLocal ejb ref name ejb ref type Session ejb ref type local home org objectweb earsample beans secusb OpLocalHome local home local org objectweb earsample beans secusb OpLocal local ejb link secusb jar Op ejb link ejb local ref web app Example of a specific Web Deployment Descriptor jonas web xml xml...

Page 174: ...ntext root jonas web app 17 3 Tips Although some characters such as are legal it is good practice to replace them with XML entity references The following is a list of the predefined entity references for XML lt less than gt greater than amp ampersand apos apostrophe quot quotation mark ...

Page 175: ...d in JONAS_ROOT xml jonas web_X_Y xsd classes a directory that contains the servlet classes and utility classes lib a directory that contains JAR archives of libraries tag libraries and any utility libraries called by server side classes If the Web application uses Enterprise Beans it can also contain ejb jars This is necessary to give to the Web components the visibility of the EJB classes Howeve...

Page 176: ...168 Chapter 18 WAR Packaging ...

Page 177: ...ains information for the J2EE Client programmer that is the person in charge of developing the client components on the client side Table of Contents 19 Launching J2EE Client Applications 171 20 Defining the Client Deployment Descriptor 173 21 Client Packaging 177 ...

Page 178: ......

Page 179: ...the client container on a remote computer copy the client jar and invoke the client container by typing java jar path_to_your client jar The client that must be launched by the client container is given as an argument of the client container For example java jar client jar myApplication ear or java jar client jar myClient jar 19 2 Configuring the Client Container 19 2 1 JNDI Access Defining the JN...

Page 180: ...s classes provided by the cp flag 19 2 4 Specifying the Client to Use EAR Case An EAR can contain many Java clients which are described in the application xml file inside the moduleµ javaµ elements To invoke the client container with an ear such as java jar client jar my ear specify the Java client to use if there are many clients Otherwise it will take the first client To specify the JAR client t...

Page 181: ...or that is specific to JOnAS The JOnAS specific deploy ment descriptor s XML schema is located in JONAS_ROOT xml jonas client_X_Y xsd The file name of the JOnAS specific XML deployment descriptor must be jonas client xml JOnAS interprets the DOCTYPE tag at the parsing of the deployment descriptor XML files The parser first tries to get the specified DTD via the classpath then it uses the specified...

Page 182: ... Session ejb ref type home org objectweb earsample beans secusb OpHome home remote org objectweb earsample beans secusb Op remote ejb link secusb jar EarOp ejb link ejb ref resource ref res ref name url jonas res ref name res type java net URL res type res auth Container res auth resource ref callback handler org objectweb jonas security auth callback LoginCallbackHandler callback handler applicat...

Page 183: ...lient 20 3 Tips Although some characters such as are legal it is good practice to replace them with XML entity references The following is a list of the predefined entity references for XML lt less than gt greater than amp ampersand apos apostrophe quot quotation mark ...

Page 184: ...176 Chapter 20 Defining the Client Deployment Descriptor ...

Page 185: ...ment descriptor in the format defined in JONAS_ROOT xml jonas client_X_Y xsd The manifest of this client JAR must contain the name of the class to launch containing the main method This is defined by the value of the Main Class attribute of the manifest file For a stan dalone client not bundled in an EAR all the EJB classes except the skeleton on which lookups will be performed must be included 21...

Page 186: ...178 Chapter 21 Client Packaging ...

Page 187: ...ntains information for the J2EE Application Assembler that is the person in charge of combining one or more components ejb jars and or wars to create a J2EE application Table of Contents 22 Defining the EAR Deployment Descriptor 181 23 EAR Packaging 183 ...

Page 188: ......

Page 189: ... is application xml and it must be located in the top level META INF directory The parser gets the specified schema via the classpath schemas are packaged in the JONAS_ROOT lib common ow_jonas jar file Some J2EE application examples are provided in the JOnAS distribution The Alarm demo The Cmp2 example The EarSample example The Blueprints Petstore application The standard deployment descriptor sho...

Page 190: ...tp java sun com xml ns j2ee application_1_4 xsd version 1 4 Á À display nameÁ Ear Security À display nameÁ À descriptionÁ Application with alt dd and security À descriptionÁ À moduleÁ À webÁ À web uriÁ admin war À web uriÁ À context rootÁ admin À context rootÁ À webÁ À moduleÁ À moduleÁ À ejbÁ ejb jar À ejbÁ À alt ddÁ altdd xml À alt ddÁ À moduleÁ À security roleÁ À role nameÁ admin À role nameÁ À...

Page 191: ...described in Chapter 5 JOnAS Class Loader Hierar chy The beans EJB JAR One or more EJB JARs which contain the beans of the J2EE application The libraries JAR One or more jars which contain the libraries tag libraries and any utility libraries used for the J2EE application The J2EE deployment descriptor The standard XML deployment descriptor in the format defined in the J2EE 1 4 specification refer...

Page 192: ...184 Chapter 23 EAR Packaging ...

Page 193: ...ormation for advanced JOnAS users Table of Contents 24 JOnAS Services 187 25 JOnAS and the Connector Architecture 193 26 JMS User s Guide 197 27 Ant EJB Tasks Using EJB JAR 211 28 Login Modules in a Java Client 215 29 Web Services with JOnAS 217 ...

Page 194: ......

Page 195: ...jonas properties file must be modified to make JOnAS aware of this service 24 1 1 Defining the Service Class A JOnAS service is represented by a class that implements the interface org objectweb jonas service Service and thus should implement the following methods public void init Context ctx throws ServiceException public void start throws ServiceException public void stop throws ServiceException...

Page 196: ... defines the set of services comma separated that will be started with JOnAS in the order of this list Add a jonas service serv1 class property specifying the service class Add as many jonas service serv1 XXX properties specifying the service initialization param eters as will be made available to the service class via the Context argument of the init method This is illustrated as follows jonas se...

Page 197: ...owing Service name Service class registry RegistryServiceImpl ejb EJBServiceImpl ear EarServiceImpl dbm DatabaseServiceImpl jms JmsServiceImpl jmx JmxServiceImpl jtm TransactionServiceImpl mail MailServiceImpl resource ResourceServiceImpl security JonasSecurityServiceImpl ws AxisWSService If all of these services are required they will be launched in the following order registry jmx security jtm d...

Page 198: ...jonas service web class org objectweb jonas web catalina CatalinaJWebContainerServiceImpl jonas service web descriptors war war jonas service web parsingwithvalidation true jonas service ear class org objectweb jonas ear EarServiceImpl jonas service ear descriptors j2ee application ear jonas service ear parsingwithvalidation true jonas service jms class org objectweb jonas jms JmsServiceImpl jonas...

Page 199: ...efined for Services Its type is java lang RuntimeException and it can encapsulate any java lang Throwable 24 2 3 The ServiceManager The org objectweb jonas service ServiceManager class is responsible for creating initial izing and launching the services It can also return a service from its name and list all the services ...

Page 200: ...192 Chapter 24 JOnAS Services ...

Page 201: ...de available by an EIS vendor The RA provides an interface the Common Client Interface or CCI to the enterprise application EJBs for accessing the EIS The RA also provides standard interfaces for plugging into the applica tion server so that the EIS and application server can collaborate to keep all system level mechanisms transparent from the application components The application performs busine...

Page 202: ...equires that you build a JOnAS specific resource adapter configuration file that will be included in the resource adapter This jonas ra XML file is used to configure the resource adapter in the operational environment and reflects the values of all properties declared in the deployment descriptor for the resource adapter plus additional JOnAS specific configuration properties JOnAS provides a depl...

Page 203: ...195 Place the RAR file in the autoload directory of JONAS_BASE default value is JONAS_BASE rars autoload Note that it may be different if jonas service resource autoload in jonas properties is configured differently Add the RAR jonas admin a xxx rar ...

Page 204: ...196 Chapter 25 JOnAS and the Connector Architecture ...

Page 205: ...hive file is also provided 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 A JMS provider can be integrated within JOnAS by deploying a corresponding resource adapter This is the preferred method as the JMS service will eventually become deprecated in future JOnAS releases Also this method allows de...

Page 206: ...should be used to get JMS con nection factories Note that starting with JMS 1 1 it is recommended that you use only the javax jms ConnectionFactory rather than javax jms QueueConnectionFactory or javax jms TopicConnectionFactory However the JMS 1 1 implementation is fully backwards compatible and existing applications will work as is The standard deployment descriptor should contain the following ...

Page 207: ...forming a message sending JMS operation looks like the following void sendMyMessage ConnectionFactory cf ConnectionFactory ctx lookup java comp env jms conFact Queue queue Queue ctx lookup java comp env jms stockQueue Connection conn cf createConnection Session sess conn createSession true Session AUTO_ACKNOWLEDGE MessageProducer mp sess createProducer Destination queue ObjectMessage msg sess crea...

Page 208: ...nectionFactory ictx lookup java comp env jms conFactSender Topic topic Topic ictx lookup java comp env jms topiclistener Connection conn cf createConnection Session session conn createSession true Session AUTO_ACKNOWLEDGE MessageConsumer mc session createConsumer Destination topic ObjectMessage message session createObjectMessage message setObject s mc send message session close conn close 26 2 4 ...

Page 209: ...ions will work as is 26 3 Some Programming Rules and Restrictions When Using JMS within EJB This section presents some programming restrictions and rules for using JMS operations within entity components 26 3 1 Connection Management Depending on the JMS implementation and the application it may be desirable to keep the JMS connections open for the life of the bean instance or for the duration of t...

Page 210: ...ined in each method that performs JMS operations For an Entity Bean an instance may be passivated and only the persistent part of the bean state is maintained Therefore it is recommended that the JMS objects be initialized and defined in each method performing JMS operations If these objects are defined in the bean state they can be initialized in the ejbActivate method if the connection is create...

Page 211: ...n close To have the session operations involved in the transaction the session creation and close should be inside the transaction boundaries and the connection creation and close operations can either be both outside the transaction boundaries or both inside the transaction boundaries as follows public class EjbCompBean implements SessionBean public void doSomethingWithJMS Connection conn qcf cre...

Page 212: ...y an application component to create a QueueConnection TCF TopicConnectionFactory To be used by an application component to create a TopicConnection JCF ConnectionFactory To be used by any other Java component for instance a client to create a connection JQCF QueueConnectionFactory To be used by any other Java component for instance a client to create a QueueConnection JTCF TopicConnectionFactory ...

Page 213: ...th JOnAS release 4 1 it is recommended that you deploy a JMS resource adapter instead of using the jms service How to do this is explained in Section 3 7 Configuring JMS Resource Adapters 26 5 Running an EJB Performing JMS Operations All that is necessary to have an Enterprise Bean perform JMS operations is jonas start The Message Oriented Middleware the JMS provider implementation is automaticall...

Page 214: ...umber for JORAM Changing the default JORAM port number requires a JORAM specific configuration operation modifying the a3servers xml configuration file located in the directory where JORAM is ex plicitly launched A default a3servers xml file is provided in the JONAS_ROOT conf direc tory this a3servers xml file specifies that the MOM runs on the localhost using the JORAM default port number To laun...

Page 215: ...be created An EJB client EjbCompClient which calls the sendMsg method of the EjbComp bean and creates an Account entity bean both within the same transaction For a transaction commit the JMS mes sage is actually sent and the record corresponding to the entity bean in the database is created For a rollback the message is not sent and nothing is created in the database A pure JMS client MsgReceptor ...

Page 216: ...ndi nameÍ Ì jonas resourceÍ Ì jonas resource envÍ Ì resource env ref nameÍ jms topiclistener Ì resource env ref nameÍ Ì jndi nameÍ sampleTopic Ì jndi nameÍ Ì jonas resource envÍ Note that the EjbComp SessionBean will use the administered objects automatically created by JOnAS in the default JMS configuration Because the administered objects are now accessible it is possible to perform JMS operatio...

Page 217: ...ull utx begin aJmsBean sendMsg Hello commit sending a JMS message aDataBean home2 create 222 JMS Sample OK 0 utx commit utx begin aJmsBean sendMsg Hello rollback sending a JMS message aDataBean home2 create 223 JMS Sample KO 0 utx rollback The result of this client execution will be that The Hello commit message will be sent and the 222 JMS Sample OK 0 record will be created in the database corres...

Page 218: ...nerSimple mc setMessageListener listener conn start System in read waiting for messages session close conn close public MyListenerSimple implements javax jms MessageListener MyListenerSimple public void onMessage javax jms Message msg try if msg null System out println Message message null else if msg instanceof ObjectMessage String m String ObjectMessage msg getObject System out println JMS clien...

Page 219: ...B descriptors are added to the JAR file they are automatically renamed META INF ejb jar xml and META INF jonas ejb jar xml Furthermore this naming behavior can be modified by specifying attributes in the ejbjar task for example basejarname basenameterminator and flatdestdir as well as the iplanet ele ment for example suffix 27 1 ejbjar Parameters Attribute Description Required destdir The base dir...

Page 220: ... if you prefer to run GenIC at deployment time If omitted it defaults to false No mappernames List of JORM mapper names separated by commas used for CMP2 0 to indicate for which mappers the container classes should be generated No jvmopts Additional args to pass to the GenIC JVM No As noted above the jonas element supports additional Ñ classpathÒ nested elements Note To avoid java lang OutOfMemory...

Page 221: ...e does require the deployment descriptors to use the naming standard This creates only one EJB JAR file TheEJBJar jar Õ ejbjar srcdir build classes descriptordir descriptor dir basejarname TheEJBJar Ö Õ jonas destdir deploymentjars dir jonasroot jonas root suffix jar orb genic org Ö Õ include name ejb jar xml Ö Õ exclude name jonas ejb jar xml Ö Õ ejbjarÖ ...

Page 222: ...214 Chapter 27 Ant EJB Tasks Using EJB JAR ...

Page 223: ...Clients org objectweb jonas security auth spi ClientLoginModule required globalCtx true This file is used when a Java client is launched with jclient as a result of the following property being set by jclient Djava security auth login config JONAS_ROOT conf jaas config For more information about the JAAS authentication refer to the JAAS authentication tutorial see http java sun com j2se 1 4 1 docs...

Page 224: ...ntext loginContext new LoginContext jaasclient handler2 Finally call the login method on the LoginContext instance loginContext login If there are no exceptions the authentication is successful If the supplied password is incorrect authentication can fail ...

Page 225: ...p www w3 org tr SOAP JAX RPC Java API for XML RPC v1 1 The Java API for XML based RPC RPC Remote Procedure Call enables a client to execute procedures on other systems The RPC mechanism is often used in a distributed client server model in which the server defines a service as a collection of procedures that may be called by remote clients In the context of Web Services RPCs are represented by the...

Page 226: ...scribed with XMLSchema the messages to send and receive composition parameters the portTypes abstract view of a Port the bindings concrete description of PortType SOAP GET POST the services set of Ports and the Port the port is associated with a unique endpoint URL that defines the location of the Web Service A Web Service for J2EE is a component with some methods exposed and accessible by HTTP th...

Page 227: ...e exposed all or some of its methods as a Web Service endpoint In the ejb jar xml standard descriptor a Session Bean exposed as a Web Service must now use the new service endpoint tag Here the developer defines the fully qualified interface name of the Web Service Notice that no other interfaces home remote localhome local are needed with a Session Bean exposed as Web Service Typically an SSB must...

Page 228: ...m developerworks opensource jsr109 xsd j2ee_web_services_1_1 xsd is used to constrain the XML 29 2 4 Simple Example expose a JAX RPC Endpoint of webservices xml webservices xmlns http java sun com xml ns j2ee xmlns xsi http www w3 org 2001 XMLSchema instance xsi schemaLocation http java sun com xml ns j2ee http www ibm com webservices xsd j2ee_web_services_1_1 xsd version 1 1 Ø display nameØ Simpl...

Page 229: ...nal jonas webservices xml The jonas webservices xml file is collocated with the webservices xml It is an optional De ployment Descriptor required only in some cases Its role is to link a webservices xml to the Web Application in charge of the SOAP request dispatching In fact it is only needed for an EJB JAR the only one that depends on another servlet to be accessible with HTTP HTTPS that does not...

Page 230: ...nt that performs a lookup on a Web Service must declare a dependency the service ref element in the standard deployment descriptor web xml application client xml or ejb jar xml Example of service ref Û service refÜ Û Optional A Web Services description that can be used in administration tool Ü Û descriptionÜ Sample WebService Client Û descriptionÜ Û Optional The WebService reference name used in A...

Page 231: ...ependency on the container to resolving a Service Endpoint Interface to a WSDL port It optionally associates the Service Endpoint Interface with a particular port component Ý Þ port component refÝ Þ service endpoint interfaceÝ org objectweb ws beans ssbendpoint MyService Þ service endpoint interfaceÝ Þ Define a link to a port component declared in another unit of the application Ý Þ port component...

Page 232: ...ice ß service ref nameà ß Define the physical name of the resource à ß jndi nameà webservice_1 ß jndi nameà ß A list of init param used for specific configuration of the service à ß jonas init paramà ß param nameà param ß param nameà ß param valueà name ß param valueà ß jonas init paramà ß jonas service refà 29 4 WsGen WsGen is a new JOnAS tool that works in the same way as GenIC It takes an archi...

Page 233: ...ise the EJB JAR task cannot find them and will produce an error This task is a directory based task and as such forms an implicit fileset see http ant apache org manual index html This defines which files relative to the srcdir will be processed The WsGen task supports all the attributes of fileset to refine the set of files to be included in the implicit fileset Attribute Description Required src...

Page 234: ...226 Chapter 29 Web Services with JOnAS ...

Page 235: ...ributed Message Beans in JOnAS 4 1 245 34 How to use Axis in JOnAS 249 35 Using WebSphere MQ JMS 253 36 Web Service Interoperability between JOnAS and BEA WebLogic 257 37 RMI IIOP Interoperability between JOnAS and BEA WebLogic 263 38 Interoperability between JOnAS and CORBA 265 39 How to Migrate the New World Cruises Application to JOnAS 269 40 Configuring JDBC Resource Adapters 275 41 Configurin...

Page 236: ......

Page 237: ...cant changes conf server xml is a customized Tomcat 5 configuration file while in JOnAS 3 3 x it was a Tomcat 4 configuration file Also package names of JOnAS related security files have changed for example org objectweb jonas security realm web catalina50 JACC replaces org objectweb jonas security realm JRealmCatalina41 The JAAS classname realm is org objectweb jonas security realm web catalina50...

Page 238: ...deployed by the JOnAS resource service jonas service resource resources in jonas properties Note that it is currently not possible to simultaneously run EJB 2 0 MDBs and EJB 2 1 MDBs in the same server It is anticipated that a JMS connector able to handle both EJB 2 0 and EJB 2 1 MDBs will be available soon at which time the JOnAS JMS service will become deprecated For more details refer to Sectio...

Page 239: ...S already includes jUDDI v0 8 as a preconfigured Web application However you can find the latest jUDDI version at http ws apache org juddi 31 4 Installation Steps jUDDI needs a minimum of configuration steps in order to be successfuly deployed inside JOnAS Note The first step can be ignored if you use the JOnAS provided juddi war 31 4 1 Create the juddi Web Application 31 4 1 1 Compilation 1 Go to...

Page 240: ...an safely be removed axis jar commons discovery jar commons logging jar jaxrpc jar saaj jar wsdl4j jar By default jUDDI includes a jonas web xml descriptor in JUDDI_HOME conf This descriptor specifies the jndi name of the DataSource used in jUDDI its default value is jdbc juddiDB This value will be used in the ã datasourceä properties of JOnAS 31 4 2 Create the Database 31 4 2 1 Retrieve the SQL s...

Page 241: ...ipts table creation tmodels insertions and publishers insertions 31 4 3 Configure JOnAS Datasource As jUDDI uses a DataSource to connect to the database JOnAS must be configured to create this DataSource Create a file named ws juddi datasource properties for example and fill it in according to the database you use MySQL DataSource configuration example datasource name is the jndi name set in jonas...

Page 242: ... war available at the context juddi Open your web browser and go to the URL http localhost 9000 juddi happyjuddi jsp to confirm that the juddi setup is successful If the URL opens you can access your UDDI server through any UDDIv2 0 compliant browser inquiryURL http localhost 9000 juddi inquiry publishURL http localhost 9000 juddi publish 31 5 Links UDDI web site http uddi org jUDDI web site http ...

Page 243: ...ession Replication technique based on the group communi cation protocol JavaGroups to provide failover at the Servlet JSP level For load balancing at the EJB level a clustered JNDI called CMI is used 32 1 Cluster Architecture The architecture with all the clustering functionality available in JOnAS is Apache as the front end HTTP server JOnAS Tomcat as J2EE Container and a shared database At the s...

Page 244: ...eved Failover at Servlet JSP Level This feature ensures that if one JSP Servlet server goes down an other server is able to transparently take over that is the request will be switched to another server without service disruption This means that it will not be necessary to start over thus achieving continuity However failover at EJB level is not available This means that no State Replication is pr...

Page 245: ...che httpd conf Create a file named tomcat_jk conf which must be included in APACHE_HOME conf httpd conf This file loads the module mod_jk LoadModule jk_module libexec mod_jk so AddModule mod_jk c Next configure mod_jk Location of the worker file JkWorkersFile etc httpd conf jk workers properties Location of the log file JkLogFile etc httpd jk logs mod_jk log Log level debug info error or emerg JkL...

Page 246: ...ver xml of the JOnAS installation directory add a unique route to the Catalina engine Replace the line ç Engine name Standalone defaultHost localhost debug 0 è with ç Engine jvmRoute worker1 name Standalone defaultHost localhost debug 0 è Note The jvmRoute name should be the same as the name of the associated worker defined in worker properties This will ensure the Session affinity 32 2 2 Configur...

Page 247: ...e clauseê where c_number é jdbc where clauseê é finder method jdbc mappingê é finder method jdbc mappingê é jonas methodê é method nameê findAll é method nameê é jonas methodê é jdbc where clauseê é jdbc where clauseê é finder method jdbc mappingê é jdbc mappingê é jonas entityê é jonas ejb jarê 32 2 3 Running a Web Application The web application is now ready to run 1 Start the jonas servers serv...

Page 248: ...based on the concept of virtual synchrony and probabilistic broadcasting The following describes the steps for achieving Session replication with JOnAS mod_jk is used to illustrate the Session Replication Therefore first perform the configuration steps presented in the section Section 32 2 Load Balancing at the Web Level with mod_jk On the JOnAS servers open the JONAS_BASE conf server xml file and...

Page 249: ...imeout 100 tcpThreadCount 2 useDirtyFlag true í î Managerí î Contextí Note The multicast address and port must be identically configured for all JOnAS Tomcat instances 32 3 1 Running your Web Application The web application is now ready to run in the cluster 1 Start the JOnAS servers service jonas start 2 Restart Apache usr local apache2 bin apachectl restart 3 Use a browser to access the welcome ...

Page 250: ...istribution of the beans in the cluster An answer to a lookup is a special clustered stub containing stubs to each instance known in the cluster Each method call on the home of the bean can be issued by the stub to a new instance to balance the load on the cluster The default algorithm used for load distribution is currently a weighted round robin 32 4 2 CMI Configuration In the build properties o...

Page 251: ...roperties file carol cmi url cmi server1 port1 server2 port2 Notes The multicast address and group name must be the same for all JOnAS servers in the cluster If Tomcat Replication associated to cmi is used the multicast addresses of the two configurations must be different 32 5 Preview of a Coming Version A solution that enables failover at EJB level is currently under development This signifies s...

Page 252: ...er with the mod_jk module 32 7 References Working with mod_jk http jakarta apache org tomcat tomcat 3 3 doc mod_jk howto html Tomcat Workers Howto http jakarta apache org tomcat tomcat 3 3 doc Tomcat Workers HowTo html Apache JServ Protocol version 1 3 ajp13 Apache Tomcat Howto http www johnturner com howto apache tomcat howto html Apache 1 3 23 Tomcat 4 0 2 Load Balancing http www ubeans com tomc...

Page 253: ... hosts a simple bean that provides a method for sending a message on a JORAM queue JOnAS B hosts a Message Driven Bean that listens on the same JORAM queue Each JOnAS instance has a dedicated collocated JORAM server server s0 for JOnAS A s1 for JOnAS B Those two servers are aware of each other The queue is hosted by JORAM server s1 An additional JNDI service is provided by the JORAM servers This s...

Page 254: ...ource to be deployed and each should remove jms from its list of services 33 3 Specific Configuration JOnAS A embeds JORAM server s0 The jonas ra xml descriptor packaged in the joram_for_jonas_ra rar archive file must provide the following information ñ jonas config propertyò ñ jonas config property nameò HostName ñ jonas config property nameò ñ jonas config property valueò hostA ñ jonas config pr...

Page 255: ...rl pkgs org objectweb jonas naming fr dyade aaa jndi2 scn naming factory host hostA scn naming factory port 16400 For JOnAS B the file looks as follows and should be put in the right conf directory java naming factory url pkgs org objectweb jonas naming fr dyade aaa jndi2 scn naming factory host hostB scn naming factory port 16400 33 4 The Beans The simple bean on JOnAS A needs to connect to its l...

Page 256: ...same queue to which the Message Driven Bean on JOnAS B listens To do this its activation properties should be set as follows õ activation configö õ activation config propertyö õ activation config property nameö destination õ activation config property nameö õ activation config property valueö scn comp sharedQueue õ activation config property valueö õ activation config propertyö õ activation config...

Page 257: ...nly way to distinguish between them for access is by the ù service nameú not by the ù context rootú ù service nameú In addition the EJB JAR files that contain the Web Services must be included in the Webapp The accessed EJB s are packaged with the Axis Webapp in an EAR archive With this approach the EJB JAR files do not have to be included in the Webapp WEB INF lib directory different Applications...

Page 258: ...ng is deployed and running use the following URL to view the deployed Web Services http yourserver port yourwebapp servlet AxisServlet This page will display a link for each Web Service with the WSDL file automatically generated by Axis from the Java Interfaces Use the following URL to access your Web Service add WSDL for the associated WSDL file http yourserver port yourwebapp services û Service ...

Page 259: ...Chapter 34 How to use Axis in JOnAS 251 p ý portþ the port of the listening http daemon default 9000 h ý hostþ the hostname of the server running the JOnAS server default localhost ...

Page 260: ...252 Chapter 34 How to use Axis in JOnAS ...

Page 261: ...ects are bound to the JOnAS registry JMS lookups then return the WebSphere MQ JMS objects and messaging takes place through these objects Given the complex configuration of WebSphere MQ JMS objects it is not possible to create these objects from JOnAS Therefore during the starting phase a JOnAS server expects WebSphere MQ JMS objects to have already been bound to the registry It thus becomes neces...

Page 262: ...application server Its configuration files are in JONAS_EJB conf Libraries must be added in JONAS_EJB lib ext In the jonas properties files set the registry service as remote jonas service registry mode remote In the carol properties file declare the rmi protocol and set the correct port carol protocols rmi carol rmi url jrmi localhost 2000 In lib ext the following libraries must be added com ibm ...

Page 263: ...hem For example if the following destinations are declared jonas service jms topics sampleTopic jonas service jms queues sampleQueue The server expects to find the following JMS objects in the registry A Queue bound with name sampleQueue A Topic bound with name sampleTopic If one of the declared destinations cannot be retrieved the following message appears and the server stops JOnAS error org obj...

Page 264: ... MQ s Java bin directory launch the JMSAdmin tool JMSAdmin 2 Create the required JMS objects Starting the EJB server 1 Clean the local CLASSPATH set export CLASSPATH 2 Set the JONAS_BASE variable so that it points towards JONAS_EJB 3 Start the JOnAS server jonas start n EJB Starting an EJB client 1 Add in the jclient classpath the ibm com mq jar and ibm com mqjms jar libraries 2 Launch the client ...

Page 265: ...he webservice are contained in webserviceclient jar 36 2 Accessing a JOnAS Web Service from a WebLogic Server s EJB 36 2 1 Web Service Development on JOnAS Refer to Chapter 34 How to use Axis in JOnAS which describes how to develop and deploy web services on JOnAS 36 2 1 1 EJB Creation on JOnAS To create a web service based on an EJB first create a stateless EJB Then create a web application war o...

Page 266: ...do this two tags can be used beanMapping qName ns local xmlns ns someNameSpace languageSpecificType java my class This maps the QName someNameSpace local with the class my class typeMapping qname ns local wmlns ns someNamespace languageSpecificType java my class serializer my java Serializer deserializer my java DeserializerFactory encodingStyle http schemas xmlsoap org soap encoding where QName s...

Page 267: ...lasses For example try WSNAME_Impl tsl new WSNAME_Impl access web service impl EJB_endpoint tsp tsl getEJB_endpoint access WS endpoint interface ComplexType tr tsp method param catch Exception e e printStackTrace System err 36 2 2 3 Deploy the EJB on WebLogic Server Deploy this EJB using the WebLogic administration console 36 3 Accessing a WebLogic Web Service from a JOnAS EJB 36 3 1 Web Service D...

Page 268: ...velopment for JOnAS This EJB provides access to the web service deployed on WebLogic from JOnAS 36 3 2 1 Generation of Web Service Client Class To access a web service generate a client class using the Axis tool WSDL2Java webservice url wsdl This command creates four classes WSNAME_Locator java Service implementation WSNAME_Port java Java Interface WSNAME_PortStub java Stub class WSNAME java Servi...

Page 269: ...Chapter 36 Web Service Interoperability between JOnAS and BEA WebLogic 261 36 3 2 3 Deploy the EJB on JOnAS Deploy the EJB using the JOnAS administration console or command ...

Page 270: ...262 Chapter 36 Web Service Interoperability between JOnAS and BEA WebLogic ...

Page 271: ...ails about configuring the communication protocol refer to the Section 3 3 Configuring the Communication Protocol and JNDI For the JOnAS server to use RMI IIOP the JOnAS configuration requires modification The iiop protocol must be selected in the file carol properties This modification will allow an EJB to be created using the RMI IIOP protocol 37 1 2 EJB Proxy on WebLogic To call an EJB deployed...

Page 272: ...hen creating the build xml For example wlappc debug debug source ejb jar iiop true classpath class path 37 2 2 EJB Proxy on JOnAS To call an EJB deployed on WebLogic Server that is accessible through RMI IIOP specify the JNDI URL of the server name containing the EJB to call This URL is of the iiop server port type For example try Properties h new Properties h put Context PROVIDER_URL iiop server ...

Page 273: ...o use RMI IIOP Choose the iiop protocol in the file carol properties Refer also to the Section 3 3 Configuring the Communication Protocol and JNDI for details about configuring the communication protocol These modifications will make it possible to create an EJB using the RMI IIOP protocol 38 1 2 Using RMIC to Create IDL Files Used by the CORBA Client To call an EJB deployed on JOnAS that is acces...

Page 274: ...idlj fclient emitAll package1 Hello idl The idlj tool also generates bugged classes Be sure to put the _read and _write method in comments in the classes _Exception java CreateException java RemoveException java Additionally the classes OutputStream java PrintStream java PrintWriter java Writer java and FilterOuputStream java must extend Serializable and then replace org omg CORBA_2_3 portable Out...

Page 275: ...erated files Warning Compile the file corresponding to the client parts the files Hello java HelloHome java _Exception java and _ Stub java Helper java ValueFactory java Operation java represents the name of the interface 38 2 Accessing a CORBA Service by an EJB Deployed on JOnAS Server 38 2 1 Setting up the CORBA Service Create the CORBA service 1 Create the idl file corresponding to this service...

Page 276: ...cifying the host and the port 4 Get the environment 5 Get the Java object corresponding to the CORBA service with the environment 6 Call the method on this object Example code try String h new String 4 h 0 ORBInitialPort h 1 port h 2 ORBInitialHost h 3 host ORB orb ORB init h null get a reference on the context handling all services org omg CORBA Object objRef orb resolve_initial_references NameSe...

Page 277: ...lass uses a local object in GlueBean constructor However it must use a remote object because it is a class calling an EJB Therefore modify the comment in this class with the following If using the remote interface the call would look like this cruiseManagerHome CruiseManagerHome javax rmi PortableRemoteObject narrow result CruiseManagerHome class Using the local interface the call looks like this ...

Page 278: ...s step download the file AirService wsdl that corresponds to the SUN web service description or use the URL containing this file Then use the command java org apache axis wsdl WSDL2java file_name This command generates four Java files AirService java the service interface AirServiceLocator java the service implementation AirServiceServantInterface the endpoint interface AirServiceServantInterfaceB...

Page 279: ...ESS_PROPERTY endPointAddress by Get our port interface AirService_pkg AirService service new AirService_pkg AirServiceLocator AirService_pkg AirServiceServantInterface port service getAirServiceServantInterfacePort Additionally the exception throw new com sun xml rpc client ClientTransportException null new Object e is replaced by throw new Exception e 39 2 3 Web Application Finally create the web...

Page 280: ...name beanJndiName value ejb CruiseManager you can use remote interfaces to access the EJB parameter name homeInterfaceName value cruisePack CruiseManagerHome parameter name remoteInterfaceName value cruisePack CruiseManager Specify allowed methods for Web Service access for all parameter name allowedMethods value createPassenger getAllDates getByDepartdate typeMapping xmlns ns urn AirService types...

Page 281: ... call the JOnAS web service instantiate the service implementation Then call the method getAirService to get the end point interface and call the appropriate method AirService_JOnAS Client CruiseManagerService cms new AirService_JOnAS Client CruiseManagerServiceLocator AirService_JOnAS Client CruiseManager cmi cms getAirService Object result cmi method 39 3 3 JSP Files To access the JOnAS web serv...

Page 282: ...lient CruiseManagerServiceLocator AirServiceLocator class PalmTree jpg aboutus jsp air_icon gif airbook jsp airclient jsp airdates jsp airdone jsp airlist jsp clear gif crubook jsp crudone jsp cruise_icon gif cruises jsp flights jsp index jsp nwcl_banner gif nwcl_banner_a gif nwcl_styles css WEB INF web xml ...

Page 283: ... databases The JDBC RA provides a generic driver wrapper that emulates the XADataSource interface on a regular JDBC driver It is important to note that this driver wrapper does not ensure a real two phase commit for distributed database transactions The generic JDBC RAs of JOnAS provide implementations of the DriverManager DataSource PooledConnection and XAConnection interfaces These can be config...

Page 284: ...value oracle jdbc driver OracleDriver jonas config property value jonas config property jonas config property jonas config property name mapperName jonas config property name jonas config property value rdb oracle jonas config property value jonas config property 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 i...

Page 285: ... jonas config property value jonas jonas config property value jonas config property jonas config property jonas config property name password jonas config property name jonas config property value jonas jonas config property value jonas config property jonas config property jonas config property name loginTimeout jonas config property name jonas config property value jonas config property value j...

Page 286: ...ntation for a complete updated list 40 3 ConnectionManager Configuration Each RAR uses a connection manager that can be configured via the additional properties described in the following table The Postgres1 jonas ra xml file provides an example of the settings These settings all have default values and they are not required Property name Description Default Value pool init Initial number of conne...

Page 287: ...ig property name jonas config property value jonas jonas config property value jonas config property jonas config property jonas config property name password jonas config property name jonas config property value jonas jonas config property value jonas config property jonas config property jonas config property name loginTimeout jonas config property name jonas config property value jonas config ...

Page 288: ...ution of the following RAConfig tool command Refer to Section 6 7 RAConfig for a complete description RAConfig dm p MySQL JONAS_ROOT rars autoload JOnAS_jdbcDM MySQL This command will create a MySQL rar file based on the MySQL properties file as specified by the p parameter It will also include the rarlink to the JOnAS_jdbcDM rar as specified by the dm parameter The jonas ra xml created by the pre...

Page 289: ...le Useful for deploying multiple connection factories without having to deploy the complete RAR file again When this is used the only entry in the RAR is META INF jonas ra xml native lib Directory where additional files in the RAR should be deployed Logging Tags log enabled Determines if logging should be enabled for the RAR log topic Log topic to use for the PrintWriter logger which allows a sepa...

Page 290: ...arlink native lib nativelib native lib log enabled false log enabled log topic com xxx rar1 log topic jonas config property jonas config property name ip jonas config property name jonas config property value www xxx com jonas config property value jonas config property jonas resource The following portion of a jonas ra xml file shows the configuration of a JDBC RAR file jonas resource jndiname jd...

Page 291: ...ary key fields 1 1 bidirectional relationships 101 111 1 1 unidirectional relationships 99 1 N bidirectional relationships 104 1 N unidirectional relationships 103 N 1 unidirectional relationships 106 N M bidirectional relationships 109 N M unidirectional relationships 107 113 command reference 59 Communication and Naming Service overview 5 communication protocol choosing 23 component interface of...

Page 292: ...anaged transactions 137 declarative transaction management 135 distributed transaction management 137 running 15 transactional behavior 135 EJB class loader 56 EJB container creating from an EJB JAR file 28 EJB Container Service overview 5 EJB implementation class 94 EJB Packaging 149 ejbjar example 212 parameters 211 using 211 endpoint JAX RPC 219 Stateless Session Bean SSB 219 Enterprise Bean pe...

Page 293: ...38 configuring for a mail factory 42 Database Service 7 development and deployment environment 10 development environments 11 EAR Container Service 6 EJB Container Service 5 features 2 future development 13 getting started with 15 interoperability with CORBA 265 J2EE Connector Architecture Service 9 Java standard conformance 3 key features 3 Mail Service 10 Management Service 10 Messaging Service ...

Page 294: ... 215 M mail mail service 27 configuring 41 mail factory configuring 42 Mail Service overview 10 Management Service overview 10 MBeans expose management methods 10 MDB Message Driven Beans administering 121 description 119 developing 119 overview 119 running 122 transactional aspects 124 Message Driven Bean pool tuning 126 Message Driven Beans MDB administering 121 description 119 developing 119 ov...

Page 295: ...configuring 42 session replication configuring Apache Tomcat and JOnAS for 239 SQL requests tracing through P6Spy 53 Stateless Session Bean SSB endpoint 219 stateless session bean pool tuning 77 T Tomcat configuring for a cluster 238 trace properties syntax 25 transaction context propagation 24 transactions and JMS 200 W WAR packaging 167 web WEB Container 27 configuring 28 web applications deploy...

Page 296: ......

Reviews: