821-0193

326
Sun GlassF ish Communica tions Serv er 2.0 Deve loper' s Guide Sun Micro syste ms, Inc. 4150 Ne twork Cir cle Santa Clara, CA 95054 U.S.A. PartNo: 821–01 93–10 Octob er 2009

Upload: arteepu4

Post on 08-Aug-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 1/326

Sun GlassFish CommunicationsServer 2.0 Developer's Guide

Sun Microsystems, Inc.4150 Network CircleSanta Clara, CA 95054U.S.A.

PartNo: 821–0193–10October 2009

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 2/326

Copyright2009 SunMicrosystems, Inc. 4150 Network Circle, Santa Clara,CA 95054 U.S.A. Allrightsreserved.

SunMicrosystems, Inc. hasintellectual property rightsrelatingto technology embodied in theproduct that is describedin this document.In particular, andwithoutlimitation, these intellectualpropertyrights mayinclude oneor more U.S. patents or pending patentapplications in theU.S. andin other countries.

U.S. Government Rights– Commercial sotware. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicableprovisionso theFARand itssupplements.

This distribution may include materials developed by thirdparties.Partso theproduct maybe derived rom Berkeley BSDsystems, licensed rom theUniversity o Caliornia. UNIX is a registered trademarkin theU.S. andothercountries, exclusivelylicensed through X/OpenCompany, Ltd.

Sun, SunMicrosystems, theSun logo, theSolaris logo, theJavaCofeeCup logo, docs.sun.com,Java,and Solaris aretrademarks or registered trademarks o SunMicrosystems, Inc. or itssubsidiariesin theU.S. andothercountries. AllSPARC trademarks areused under license andare trademarks or registered trademarks o SPARCInternational,Inc. in theU.S. andothercountries. Products bearing SPARCtrademarks arebasedupon an architecturedeveloped by SunMicrosystems, Inc.

The OPENLOOK and SunTM GraphicalUser Interacewas developedby SunMicrosystems, Inc. orits users andlicensees. Sunacknowledges thepioneering efortso Xerox in researching anddeveloping theconcept o visualor graphicaluser interaces orthe computer industry.Sun holds a non-exclusive licenseromXeroxtotheXeroxGraphical UserInterace,whichlicense also coversSun'slicenseeswho implementOPENLOOK GUIs andotherwise complywith Sun's written licenseagreements.

Products covered by andinormationcontained in this publication arecontrolled by U.S. ExportControl laws andmay be subjectto theexport or importlaws inother countries. Nuclear,missile,chemicalor biological weapons or nuclear maritime enduses or endusers,whether director indirect,are strictly prohibited. Exportor reexport to countriessubject to U.S. embargo or to entities identiedon U.S. exportexclusion lists,including, butnot limited to,the deniedpersons andspecially designated nationals lists is strictly prohibited.

DOCUMENTATIONIS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANYIMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPTTOTHEEXTENTTHAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

Copyright2009 SunMicrosystems, Inc. 4150 Network Circle, Santa Clara,CA 95054 U.S.A. Tous droitsréservés.

SunMicrosystems, Inc. détient lesdroits de propriétéintellectuellerelatisà la technologie incorporée dans le produit quiest décritdans ce document.En particulier,

et ce sans limitation, cesdroits de propriétéintellectuellepeuvent inclure un ou plusieursbrevets américains ou desapplications de breveten attente auxEtats-Uniset dans d'autres pays.

Cette distribution peut comprendredes composants développéspar des tierces personnes.

Certainescomposants de ce produit peuvent être dérivées du logiciel Berkeley BSD, licenciéspar l'Universitéde Caliornie. UNIX estune marquedéposée auxEtats-Uniset dans d'autres pays; elle estlicenciée exclusivementpar X/OpenCompany,Ltd.

Sun, SunMicrosystems, le logo Sun, le logo Solaris, le logo Java Cofee Cup, docs.sun.com,Java et Solaris sont desmarques de abrique ou desmarques déposées deSunMicrosystems, Inc., ou sesliales, auxEtats-Uniset dans d'autres pays. Toutesles marques SPARC sont utiliséessous licence et sontdes marques de abrique oudesmarques déposées de SPARCInternational,Inc. auxEtats-Uniset dans d'autres pays. Lesproduitsportant lesmarques SPARCsont basés surune architecturedéveloppéepar Sun Microsystems, Inc.

L'interace d'utilisation graphiqueOPENLOOK et Suna étédéveloppée parSun Microsystems, Inc. pour ses utilisateurset licenciés. Sunreconnaît leseforts de

pionniersde Xerox pour la rechercheet le développement du concept desinteraces d'utilisation visuelle ou graphiquepour l'industrie de l'inormatique.Sun détientunelicence nonexclusive de Xerox surl'interaced'utilisation graphiqueXerox, cette licence couvrant égalementles licenciésde Sunqui mettent en place l'interaced'utilisation graphiqueOPENLOOK et qui, en outre,se conorment auxlicencesécrites de Sun.

Lesproduitsqui ont l'objet de cette publication et lesinormations qu'il contient sontrégispar la legislation américaine en matière de contrôle desexportations etpeuvent être soumisau droit d'autres pays dans le domaine desexportations et importations. Lesutilisations nales, ou utilisateursnaux, pour desarmesnucléaires,des missiles, des armeschimiques ou biologiquesou pour le nucléaire maritime, directementou indirectement, sont strictementinterdites. Les exportations ouréexportations vers despays sous embargo desEtats-Unis,ou vers desentités gurantsur leslistes d'exclusion d'exportation américaines, y compris, mais de manièrenonexclusive, la liste de personnesqui ontobjet d'un ordre de ne pasparticiper,d'uneaçondirecte ou indirecte, auxexportations desproduitsou desservicesquisont régispar la legislationaméricaine en matière de contrôle des exportations et la listede ressortissants spéciquement designés, sont rigoureusement interdites.

LA DOCUMENTATION EST FOURNIE "EN L'ETAT" ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITESSONT FORMELLEMENTEXCLUES, DANS LA MESUREAUTORISEE PAR LA LOI APPLICABLE, Y COMPRISNOTAMMENT TOUTE GARANTIEIMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L'APTITUDE A UNE UTILISATIONPARTICULIEREOU A L'ABSENCE DE CONTREFACON.

091112@22749

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 3/326

Contents

Preace ...................................................................................................................................................19

Part I Development Tasks andTools ........................................................................................................... 25

1 Setting Up a Development Environment ........................................................................................27

Installing and Preparing the Server or Development .................................................................... 27

The Sailn Project ............................................................................................................................... 28Usage Proles ........................................................................................................................ ............... 28

High Availability Features .................................................................................................................. 29

Development Tools ............................................................................................................................. 29

The asadmin Command .............................................................................................................. 29

The Admin Console ..................................................................................................................... 30

The asant Utility .......................................................................................................................... 30

The verifier Tool ...................................................................................................................... 30

The NetBeans IDE ........................................................................................................................ 30

The Migration Tool ..................................................................................................................... 31

Debugging Tools .......................................................................................................................... 31

Proling Tools .............................................................................................................................. 31

The Eclipse IDE .................................................................................................................. .......... 31

Sample Applications ............................................................................................................................ 31

2 Class Loaders ........................................................................................................................................33

The Class Loader Hierarchy ............................................................................................................... 33

Delegation ............................................................................................................................................ 37

Using the Java Optional Package Mechanism .................................................................................. 37

Using the Endorsed Standards Override Mechanism ..................................................................... 37Class Loader Universes ............................................................................................................ ........... 38

3

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 4/326

Application-Specic Class Loading .................................................................................................. 38

Circumventing Class Loader Isolation ............................................................................................. 39

Using the System Class Loader ................................................................................................... 40Using the Common Class Loader .............................................................................................. 40

Sharing Libraries Across a Cluster ............................................................................................. 40

Packaging the Client JAR or One Application in Another Application ............................... 41

▼ To Package the Client JAR or One Application in Another Application ............................. 41

3 The asant Utility ..................................................................................................................................43Communications Server asant Tasks ............................................................................................... 44

The sun-appserv-deploy Task ................................................................................................. 44

The sun-appserv-undeploy Task ............................................................................................. 48

The sun-appserv-instance Task ............................................................................................. 51

The sun-appserv-component Task ........................................................................................... 54

The sun-appserv-admin Task ................................................................................................... 57

The sun-appserv-jspc Task ..................................................................................................... 58

The sun-appserv-update Task ................................................................................................. 60

The wsgen Task ............................................................................................................................. 60

The wsimport Task ...................................................................................................................... 62

Reusable Subelements ......................................................................................................................... 63

The server Subelement .............................................................................................................. 63

The component Subelement ........................................................................................................ 66The fileset Subelement ............................................................................................................ 68

JBI Tasks ......................................................................................................................................... ...... 68

4 DebuggingApplications ....................................................................................................................69

Enabling Debugging ........................................................................................................................... 69

▼ To Set the Server to Automatically Start Up in Debug Mode ................................................. 70JPDA Options ...................................................................................................................................... 70

Generating a Stack Trace or Debugging .......................................................................................... 71

Application Client Debugging ........................................................................................................... 71

Sun GlassFish Message Queue Debugging ....................................................................................... 72

Enabling Verbose Mode ..................................................................................................................... 72

Communications Server Logging ...................................................................................................... 72SIP Message Inspection Log Adapter ................................................................................................ 73

Contents

Sun GlassFishCommunications Server2.0 Developer's Guide • October 20094

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 5/326

Proling Tools ..................................................................................................................................... 74

The NetBeans Proler ................................................................................................................. 75

The HPROF Proler .................................................................................................................... 75The JProbe Proler ...................................................................................................................... 76

Part II DevelopingApplications andApplicationComponents .............................................................. 79

5 Securing Applications .........................................................................................................................81

Security Goals ...................................................................................................................................... 82

Communications Server Specic Security Features ........................................................................ 82

Container Security .............................................................................................................................. 83

Declarative Security ..................................................................................................................... 83

Programmatic Security ................................................................................................................ 84

Roles, Principals, and Principal to Role Mapping ........................................................................... 84

Realm Conguration .......................................................................................................................... 86Supported Realms ........................................................................................................................ 86

How to Congure a Realm .......................................................................................................... 87

How to Set a Realm or an Application or Module ................................................................... 87

Creating a Custom Realm ........................................................................................................... 87

Using Identity Authentication ........................................................................................................... 89

Conguring a Realm or Identity Authentication .................................................................... 89

Conguring sip.xml or Identity Authentication ................................................................... 89

Conguring sun-sip.xml or Identity Authentication .......................................................... 90

Conguring the Identity Message Root Certicate ................................................................. 90

Using P-Asserted Identity Authentication ....................................................................................... 91

Conguring a Trust ..................................................................................................................... 91

Conguring sun-sip.xml or P-Asserted Identity Authentication ....................................... 91

Creating a Custom Trust Handler or P-Asserted Identity Authentication ................................. 92JACC Support ...................................................................................................................................... 93

Pluggable Audit Module Support ...................................................................................................... 93

Conguring an Audit Module .................................................................................................... 93

The AuditModule Class ............................................................................................................... 93

The server.policy File ..................................................................................................................... 95

Deault Permissions ..................................................................................................................... 95Changing Permissions or an Application ................................................................................ 95

Contents

5

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 6/326

Enabling and Disabling the Security Manager ......................................................................... 97

Conguring Message Security or Web Services ............................................................................. 98

Message Security Providers ........................................................................................................ 99Message Security Responsibilities ............................................................................................ 100

Application-Specic Message Protection ............................................................................... 102

Understanding and Running the Sample Application .......................................................... 105

Programmatic Login ......................................................................................................................... 107

Programmatic Login Precautions ............................................................................................ 108

Granting Programmatic Login Permission ............................................................................ 108

The ProgrammaticLogin Class ................................................................................................ 109

User Authentication or Single Sign-on .......................................................................................... 110

6 DevelopingWeb Services .................................................................................................................113

Creating Portable Web Service Artiacts ........................................................................................ 114

Deploying a Web Service .................................................................................................................. 114

Web Services Registry ....................................................................................................................... 115

The Web Service URI, WSDL File, and Test Page ......................................................................... 116

JBI Runtime ...................................................................................................................................... .. 117

Using the jbi.xml File .............................................................................................................. 118

Using Application Server Descriptors ..................................................................................... 118

Using the Woodstox Parser .............................................................................................................. 119

7 Using the JavaPersistenceAPI ........................................................................................................121

Speciying the Database .................................................................................................................... 122

Additional Database Properties ....................................................................................................... 124

Conguring the Cache ...................................................................................................................... 124

Setting the Logging Level .................................................................................................................. 124

Using Lazy Loading ........................................................................................................................... 125Primary Key Generation Deaults ................................................................................................... 125

Automatic Schema Generation ........................................................................................................ 126

Annotations ............................................................................................................................... . 126

Supported Data Types ............................................................................................................... 127

Generation Options ................................................................................................................... 128

Query Hints ..................................................................................................................... ................... 131

Changing the Persistence Provider ................................................................................................. 132

Contents

Sun GlassFishCommunications Server2.0 Developer's Guide • October 20096

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 7/326

Restrictions and Optimizations ....................................................................................................... 133

Extended Persistence Context Failover ................................................................................... 133

Using @OrderBy with a Shared Session Cache ...................................................................... 133Using BLOB or CLOB Types with the Inet Oraxo JDBC Driver .......................................... 134

Database Case Sensitivity .......................................................................................................... 134

Sybase Finder Limitation .......................................................................................................... 135

MySQL Database Restrictions .................................................................................................. 135

8 DevelopingWeb andSIP Applications ...........................................................................................139Using Servlets ........................................................................................................................ ............. 139

Invoking a Servlet With a URL ................................................................................................. 140

Servlet Output .................................................................................................................. .......... 141

Caching Servlet Results ............................................................................................................. 141

About the Servlet Engine ........................................................................................................... 145

Using JavaServer Pages ..................................................................................................................... 146

JSP Tag Libraries and Standard Portable Tags ....................................................................... 147

JSP Caching ...................................................................................................................... ........... 147

Options or Compiling JSP Files .............................................................................................. 151

Creating and Managing Sessions ..................................................................................................... 151

Conguring Sessions ................................................................................................................. 151

Session Managers ....................................................................................................................... 154

Advanced Web Application Features .............................................................................................. 159

Internationalization Issues ........................................................................................................ 159

Virtual Servers ............................................................................................................................ 160

Deault Web Modules ................................................................................................................ 161

Class Loader Delegation ............................................................................................................ 162

Using the default-web.xml File .............................................................................................. 162

Conguring Logging and Monitoring in the Web Container .............................................. 163Conguring Idempotent URL Requests ................................................................................. 163

Header Management ................................................................................................................. 164

Conguring Valves and Catalina Listeners ............................................................................ 164

Alternate Document Roots ....................................................................................................... 165

Redirecting URLs ....................................................................................................................... 167

Enabling Comet Support .......................................................................................................... 167

Using a context.xml File ............................................................................................................ 167

Contents

7

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 8/326

Enabling WebDav ...................................................................................................................... 168

Using mod_jk ............................................................................................................................. 169

Advanced JVM Options or SIP Requests ............................................................................... 171

9 Using EnterpriseJavaBeansTechnology .......................................................................................173

Summary o EJB 3.0 Changes ........................................................................................................... 173

Value Added Features ....................................................................................................................... 174

Read-Only Beans ........................................................................................................................ 174

The pass-by-reference Element ........................................................................................... 175Pooling and Caching .................................................................................................................. 175

Bean-Level Container-Managed Transaction Timeouts ...................................................... 176

Priority Based Scheduling o Remote Bean Invocations ....................................................... 177

Immediate Flushing ................................................................................................................... 177

EJB Timer Service .............................................................................................................................. 178

Using Session Beans .......................................................................................................................... 179

About the Session Bean Containers ......................................................................................... 179

Stateul Session Bean Failover .................................................................................................. 180

Session Bean Restrictions and Optimizations ........................................................................ 185

Using Read-Only Beans .................................................................................................................... 186

Read-Only Bean Characteristics and Lie Cycle ..................................................................... 186

Read-Only Bean Good Practices .............................................................................................. 187

Rereshing Read-Only Beans .................................................................................................... 187Deploying Read-Only Beans .................................................................................................... 189

Using Message-Driven Beans .......................................................................................................... 189

Message-Driven Bean Conguration ...................................................................................... 189

Message-Driven Bean Restrictions and Optimizations ........................................................ 191

Handling Transactions With Enterprise Beans ............................................................................. 192

Flat Transactions ........................................................................................................................ 193

Global and Local Transactions ................................................................................................. 193

Commit Options ........................................................................................................................ 193

Administration and Monitoring .............................................................................................. 194

10 Using Container-Managed Persistence .........................................................................................195

Communications Server Support or CMP .................................................................................... 195

CMP Mapping ................................................................................................................................. .. 196

Contents

Sun GlassFishCommunications Server2.0 Developer's Guide • October 20098

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 9/326

Mapping Capabilities ................................................................................................................ 196

The Mapping Deployment Descriptor File ............................................................................. 196

Mapping Considerations .......................................................................................................... 197Automatic Schema Generation or CMP ....................................................................................... 200

Supported Data Types or CMP ............................................................................................... 201

Generation Options or CMP ................................................................................................... 203

Schema Capture ...................................................................................................................... ........... 206

Automatic Database Schema Capture ..................................................................................... 206

Using the capture-schema Utility ........................................................................................... 206

Conguring the CMP Resource ....................................................................................................... 207

Perormance-Related Features ......................................................................................................... 207

Version Column Consistency Checking ................................................................................. 208

Relationship Preetching ........................................................................................................... 208

Read-Only Beans ........................................................................................................................ 209

Deault Fetch Group Flags ................................................................................................................ 210

Conguring Queries or 1.1 Finders ............................................................................................... 210About JDOQL Queries .............................................................................................................. 210

Query Filter Expression ..................................................................................................... ........ 211

Query Parameters ................................................................................................................ ...... 212

Query Variables ................................................................................................................. ......... 212

JDOQL Examples ....................................................................................................................... 213

CMP Restrictions and Optimizations ............................................................................................. 214Disabling ORDER BY Validation ............................................................................................ 214

Setting the Heap Size on DB2 ................................................................................................... 215

Eager Loading o Field State ..................................................................................................... 215

Restrictions on Remote Interaces ........................................................................................... 215

PostgreSQL Case Insensitivity .................................................................................................. 215

No Support or lock-when-loaded on Sybase ....................................................................... 216

Sybase Finder Limitation .......................................................................................................... 216

Date and Time Fields ................................................................................................................. 216

Set RECURSIVE_TRIGGERS to false on MSSQL ...................................................................... 217

MySQL Database Restrictions .................................................................................................. 217

11 DevelopingJava Clients ...................................................................................................................221

Introducing the Application Client Container .............................................................................. 221

Contents

9

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 10/326

ACC Security .............................................................................................................................. 221

ACC Naming .............................................................................................................................. 222

ACC Annotation ........................................................................................................................ 222Java Web Start ............................................................................................................................. 222

Developing Clients Using the ACC ................................................................................................. 223

▼ To Access an EJB Component From an Application Client ................................................. 223

▼ To Access a JMS Resource From an Application Client ........................................................ 225

Using Java Web Start ................................................................................................................. 226

Running an Application Client Using the appclient Script ................................................ 232

Using the package-appclient Script ..................................................................................... 232

The client.policy File ............................................................................................................ 232

Using RMI/IIOP Over SSL ........................................................................................................ 232

Connecting to a Remote EJB Module Through a Firewall .................................................... 234

12 DevelopingConnectors ....................................................................................................................235

Connector Support in the Communications Server ..................................................................... 236

Connector Architecture or JMS and JDBC ........................................................................... 236

Connector Conguration ......................................................................................................... 236

Deploying and Conguring a Stand-Alone Connector Module ................................................. 237

▼ To Deploy and Congure a Stand-Alone Connector Module ............................................. 237

Redeploying a Stand-Alone Connector Module ........................................................................... 238

Deploying and Conguring an Embedded Resource Adapter .................................................... 238Advanced Connector Conguration Options ............................................................................... 239

Thread Pools ............................................................................................................................... 239

Security Maps ............................................................................................................................. 239

Overriding Conguration Properties ...................................................................................... 240

Testing a Connector Connection Pool .................................................................................... 240

Handling Invalid Connections ................................................................................................. 241

Setting the Shutdown Timeout ................................................................................................. 241

Using Last Agent Optimization o Transactions ................................................................... 242

Inbound Communication Support ................................................................................................. 242

Conguring a Message Driven Bean to Use a Resource Adapter ................................................ 243

13 DevelopingLiecycle Listeners ........................................................................................................247

Server Lie Cycle Events .................................................................................................................... 247

Contents

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200910

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 11/326

The LifecycleListener Interace ................................................................................................. 248

The LifecycleEvent Class .............................................................................................................. 248

The Server Liecycle Event Context ................................................................................................. 249Deploying a Liecycle Module .......................................................................................................... 249

Considerations or Liecycle Modules ............................................................................................ 250

14 Developing Custom MBeans ............................................................................................................251

The MBean Lie Cycle ....................................................................................................................... 252

MBean Class Loading .............................................................................................................. ......... 253Creating, Deleting, and Listing MBeans ......................................................................................... 253

The asadmin create-mbean Command ................................................................................. 253

The asadmin delete-mbean Command ................................................................................. 254

The asadmin list-mbeans Command ................................................................................... 254

The MBeanServer in the Communications Server ........................................................................ 255

Enabling and Disabling MBeans ..................................................................................................... 256Handling MBean Attributes ............................................................................................................. 256

Part III Using Services and APIs ................................................................................................................... 259

15 Using the JDBC API or Database Access ....................................................................................... 261

General Steps or Creating a JDBC Resource ................................................................................. 261Integrating the JDBC Driver ..................................................................................................... 262

Creating a Connection Pool ...................................................................................................... 262

Testing a JDBC Connection Pool ............................................................................................. 263

Creating a JDBC Resource ........................................................................................................ 263

Creating Applications That Use the JDBC API ............................................................................. 263

Sharing Connections ................................................................................................................. 264Obtaining a Physical Connection From a Wrapped Connection ........................................ 264

Marking Bad Connections ........................................................................................................ 264

Using Non-Transactional Connections .................................................................................. 265

Using JDBC Transaction Isolation Levels ............................................................................... 266

Allowing Non-Component Callers ......................................................................................... 267

Restrictions and Optimizations ....................................................................................................... 267

Disabling Stored Procedure Creation on Sybase .................................................................... 267

Contents

11

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 12/326

16 Using theTransactionService .........................................................................................................269

Transaction Resource Managers ..................................................................................................... 269

Transaction Scope ............................................................................................................................. 270Distributed Transaction Recovery .................................................................................................. 271

Conguring the Transaction Service .............................................................................................. 272

The Transaction Manager, the Transaction Synchronization Registry, andUserTransaction .............................................................................................................................. 272

Transaction Logging ......................................................................................................................... 273

Storing Transaction Logs in a Database ......................................................................................... 273

Recovery Workarounds .................................................................................................................... 274

17 Using the Java Naming andDirectory Interace .......................................................................... 277

Accessing the Naming Context ........................................................................................................ 277

Global JNDI Names ................................................................................................................... 278

Accessing EJB Components Using the CosNaming Naming Context .................................. 279

Accessing EJB Components in a Remote Application Server ............................................... 279

Naming Environment or Liecycle Modules ......................................................................... 280

Conguring Resources ..................................................................................................................... 281

External JNDI Resources .......................................................................................................... 281

Custom Resources ...................................................................................................................... 281

Using a Custom jndi.properties File .......................................................................................... 282

Mapping Reerences .......................................................................................................................... 282

18 Using the JavaMessage Service ......................................................................................................285

The JMS Provider .............................................................................................................................. 286

Message Queue Resource Adapter .................................................................................................. 287

Generic Resource Adapter ............................................................................................................... 287

Administration o the JMS Service .................................................................................................. 287Conguring the JMS Service ..................................................................................................... 288

The Deault JMS Host ................................................................................................................ 289

Creating JMS Hosts .................................................................................................................... 289

Checking Whether the JMS Provider Is Running .................................................................. 289

Creating Physical Destinations ................................................................................................ 289

Creating JMS Resources: Destinations and Connection Factories ...................................... 290

Restarting the JMS Client Ater JMS Conguration ..................................................................... 291

Contents

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200912

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 13/326

JMS Connection Features ................................................................................................................. 291

Connection Pooling ................................................................................................................... 291

Connection Failover .................................................................................................................. 292Load-Balanced Message Inow ....................................................................................................... 292

Transactions and Non-Persistent Messages ................................................................................... 293

Authentication With ConnectionFactory .................................................................................... 293

Message Queue varhome Directory ................................................................................................. 294

Delivering SOAP Messages Using the JMS API ............................................................................. 294

▼ To Send SOAP Messages Using the JMS API ......................................................................... 294

▼ To Receive SOAP Messages Using the JMS API ..................................................................... 296

19 Using the JavaMail API .....................................................................................................................297

Introducing JavaMail ........................................................................................................................ 297

Creating a JavaMail Session .............................................................................................................. 298

JavaMail Session Properties .............................................................................................................. 298

Looking Up a JavaMail Session ........................................................................................................ 298

Sending and Reading Messages Using JavaMail ............................................................................ 299

▼ To Send a Message Using JavaMail .......................................................................................... 299

▼ To Read a Message Using JavaMail .......................................................................................... 300

20 Usingthe ApplicationServer Management Extensions ............................................................. 301

About AMX ........................................................................................................................... ............. 302

AMX MBeans ........................................................................................................................ ............ 303

Conguration MBeans .............................................................................................................. 304

Monitoring MBeans .................................................................................................................. 304

Utility MBeans ........................................................................................................................... 304

Java EE Management MBeans .................................................................................................. 304

Other MBeans .................................................................................................................... ........ 305MBean Notications .................................................................................................................. 305

Access to MBean Attributes ...................................................................................................... 305

Dynamic Client Proxies ........................................................................................................... ......... 306

Connecting to the Domain Administration Server ....................................................................... 306

Examining AMX Code Samples ...................................................................................................... 307

The SampleMain Class ............................................................................................................... 307

Connecting to the DAS .............................................................................................................. 307

Contents

13

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 14/326

Starting an Communications Server ....................................................................................... 308

Deploying an Archive ................................................................................................................ 309

Displaying the AMX MBean Hierarchy .................................................................................. 309Setting Monitoring States .......................................................................................................... 309

Accessing AMX MBeans ........................................................................................................... 309

Accessing and Displaying the Attributes o an AMX MBean ............................................... 309

Listing AMX MBean Properties ............................................................................................... 309

Perorming Queries ................................................................................................................... 309

Monitoring Attribute Changes ................................................................................................. 310

Undeploying Modules ............................................................................................................... 310

Stopping an Communications Server ..................................................................................... 310

Running the AMX Samples .............................................................................................................. 310

▼ To Run the AMX Sample .......................................................................................................... 310

Index ................................................................................................................................................... 313

Contents

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200914

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 15/326

Tables

TABLE 2–1 Sun GlassFish Communications Server Class Loaders ......................................... 35

TABLE 3–1 The sun-appserv-deploy Subelements ................................................................. 45TABLE 3–2 The sun-appserv-deploy Attributes .....................................................................45

TABLE 3–3 The sun-appserv-undeploy Subelements ............................................................49

TABLE 3–4 The sun-appserv-undeploy Attributes ................................................................. 49

TABLE 3–5 The sun-appserv-instance Subelements ............................................................51

TABLE 3–6 The sun-appserv-instance Attributes ................................................................. 51

TABLE 3–7 The sun-appserv-component Subelements ..........................................................55

TABLE 3–8 The sun-appserv-component Attributes ............................................................... 55

TABLE 3–9 The sun-appserv-admin Subelements ................................................................... 57

TABLE 3–10 The sun-appserv-admin Attributes .......................................................................57

TABLE 3–11 The sun-appserv-jspc Attributes .......................................................................... 58

TABLE 3–12 The sun-appserv-update Attributes .....................................................................60

TABLE 3–13 The wsgen Attributes ................................................................................................. 61

TABLE 3–14 The wsimport Attributes ..........................................................................................62TABLE 3–15 The server Attributes ............................................................................................... 64

TABLE 3–16 The component Attributes ........................................................................................66

TABLE 7–1 Java Type to SQL Type Mappings ..........................................................................127

TABLE 7–2 Schema Generation Properties .............................................................................. 129

TABLE 7–3 The asadmin deploy and asadmin deploydir Generation Options ............... 130

TABLE 7–4 The asadmin undeploy Generation Options ...................................................... 131

TABLE 8–1 URL Fields or Servlets Within an Application .................................................... 140

TABLE 8–2 The cache Attributes ...............................................................................................149

TABLE 8–3 The flush Attributes ...............................................................................................150

TABLE 8–4 Object Types Supported or Java EE Web or SIP Application Session StateFailover ..................................................................................................................... 154

TABLE 9–1 Object Types Supported or Java EE Stateul Session Bean State Failover ........181

TABLE 10–1 Java Type to JDBC Type Mappings or CMP .......................................................201TABLE 10–2 Mappings o JDBC Types to Database Vendor Specic Types or CMP ..........202

15

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 16/326

TABLE 10–3 The sun-ejb-jar.xml Generation Elements ...................................................... 204

TABLE 10–4 The asadmin deploy and asadmin deploydir Generation Options or CMP.................................................................................................................................... 204

TABLE 10–5 The asadmin undeploy Generation Options or CMP ......................................205

TABLE 15–1 TransactionIsolationLevels .................................................................................. 266

TABLE 16–1 Schema or txn_log_table ....................................................................................274

Tables

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200916

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 17/326

Figures

FIGURE 2–1 Class Loader Runtime Hierarchy ............................................................................ 34

17

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 18/326

18

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 19/326

Preace

This Developer's Guide describes how to create and run JavaTM Platorm, Enterprise Edition

(Java EE platorm) applications that ollow the open Java standards model or Java EEcomponents and APIs in the Sun Java System Communications Server environment. Topicsinclude developer tools, security, debugging, and creating liecycle modules. This book isintended or use by sotware developers who create, assemble, and deploy Java EE applicationsusing Sun GlassFish servers and sotware.

This preace contains inormation about and conventions or the entire Sun GlassFishTM

Communications Server documentation set.

Communications Server Documentation SetThe Uniorm Resource Locator (URL) or Communications Server documentation ishttp://docs.sun.com/coll/1343.10 . For an introduction to Communications Server, reerto the books in the order in which they are listed in the ollowing table.

TABLE P–1 Books in the Communications Server Documentation Set

Book Title Description

Documentation Center  Communications Server documentation topics organized by task and subject.

Release Notes Late-breaking inormation about the sotware and the documentation. Includes acomprehensive, table-based summary o the supported hardware, operating system, JavaDevelopment Kit (JDKTM), and database drivers.

Quick Start Guide How to get started with the Communications Server product.

Installation Guide Installing the sotware and its components.

 Application Deployment Guide Deployment o applications and application components to the Communications Server.Includes inormation about deployment descriptors.

Developer’s Guide Creating and implementing Java Platorm, Enterprise Edition (Java EE platorm) applicationsintended to run on the Communications Server that ollow the open Java standards model or

Java EE components and APIs. Includes inormation about developer tools, security,debugging, and creating liecycle modules.

19

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 20/326

TABLE P–1 Booksin the CommunicationsServer Documentation Set (Continued)

Book Title Description

 Java EE 5 Tutorial  Using Java EE 5 platorm technologies and APIs to develop Java EE applications.

 Java WSIT Tutorial  Developing web applications using the Web Service Interoperability Technologies (WSIT).Describes how, when, and why to use the WSIT technologies and the eatures and optionsthat each technology supports.

 Administration Guide System administration or the Communications Server, including conguration, monitoring,security, resource management, and web services management.

High Availability Administration

GuideSetting up clusters, working with node agents, and using load balancers.

 Administration Reerence Editing the Communications Server congurationle, domain.xml.

Perormance Tuning Guide Tuning the Communications Server to improve perormance.

Reerence Manual  Utility commands available with the Communications Server; written in man page style.Includes the asadmin command line interace.

Related Documentation

For documentation about other stand-alone Sun GlassFish server products, go to the ollowing:

■ Message Queue documentation (http://docs.sun.com/coll/1343.4)■ Identity Server documentation (http://docs.sun.com/app/docs/prod/ident.mgmt#hic )■ Directory Server documentation (http://docs.sun.com/coll/1224.1)■ Web Server documentation (http://docs.sun.com/coll/1308.3)

A JavadocTM tool reerence or packages provided with the Communications Server is located athttp://glassfish.dev.java.net/nonav/javaee5/api/index.html . Additionally, theollowing resources might be useul:

■ The Java EE 5 Specications (http://java.sun.com/javaee/5/javatech.html )■ The Java EE Blueprints (http://java.sun.com/reference/blueprints/index.html )

For inormation on creating enterprise applications in the NetBeansTM

Integrated DevelopmentEnvironment (IDE), see http://www.netbeans.org/kb/55/index.html .

For inormation about the Java DB database included with the Communications Server, seehttp://developers.sun.com/javadb/ .

The GlassFish Samples project is a collection o sample applications that demonstrate a broadrange o Java EE technologies. The GlassFish Samples are bundled with the Java EE SotwareDevelopment Kit (SDK), and are also available rom the GlassFish Samples project page athttps://glassfish-samples.dev.java.net/ .

Preace

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200920

P

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 21/326

Deault Paths and File Names

The ollowing table describes the deault paths and le names that are used in this book.

TABLE P–2 Deault Paths and File Names

Placeholder Description Deault Value

as-install  Represents the base installation directory orCommunications Server.

SolarisTM and Linux installations, non-root user:

user’s-home-directory /SUNWappserver

Solaris and Linux installations, root user:

/opt/SUNWappserver

Windows, all installations:

SystemDrive:\Sun\AppServer

domain-root-dir  Represents the directory containing alldomains.

All installations:

as-install /domains/

domain-dir  Represents the directory or a domain.

In conguration les, you might seedomain-dir represented as ollows:

${com.sun.aas.instanceRoot}

domain-root-dir /domain-dir 

instance-dir  Represents the directory or a server instance. domain-dir /instance-dir 

samples-dir  Represents the directory containing sampleapplications.

as-install /samples

docs-dir  Represents the directory containingdocumentation.

as-install /docs

Typographic Conventions

The ollowing table describes the typographic changes that are used in this book.

TABLE P–3 TypographicConventions

Typeace Meaning Example

AaBbCc123 The names o commands, les, anddirectories, and onscreen computeroutput

Edit your .login le.

Use ls -a to list all les.

machine_name% you have mail.

Preace

21

Preace

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 22/326

TABLE P–3 Typographic Conventions (Continued)

Typeace Meaning Example

AaBbCc123 What you type, contrasted with onscreen

computer output

machine_name% su

Password:

 AaBbCc123 A placeholder to be replaced with a realname or value

The command to remove a le is rm flename.

 AaBbCc123 Book titles,new terms, and terms to beemphasized (note that some emphasizeditems appear bold online)

Read Chapter 6 in the User's Guide.

A cache is a copy that is stored locally.

Do not save the le.

Symbol ConventionsThe ollowing table explains symbols that might be used in this book.

TABLE P–4 SymbolConventions

Symbol Description Example Meaning

[ ] Contains optional argumentsand command options.

ls [-l] The -l option is not required.

{ | } Contains a set o choices or arequired command option.

-d {y|n} The -d option requires that you useeither the y argument or the n

argument.

${ } Indicates a variablereerence.${com.sun.javaRoot} Reerences the value o the

com.sun.javaRoot variable.

- Joins simultaneous multiplekeystrokes.

Control-A Press t he C ontrol k ey while y ou p resstheAkey.

+ Joins consecutive multiplekeystrokes.

Ctrl+A+N Press the C ontrol k ey, release i t, a ndthen press the subsequent keys.

→ Indicates menu item

selection in a graphical userinterace.

File→New →Templates From the File menu, chooseNew.

From the New submenu, chooseTemplates.

Preace

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200922

Preace

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 23/326

Documentation, Support, andTrainingThe Sun web site provides inormation about the ollowing additional resources:

■ Documentation (http://www.sun.com/documentation/)■ Support (http://www.sun.com/support/)■ Training (http://www.sun.com/training/)

Third-Party Web Site Reerences

Third-party URLs are reerenced in this document and provide additional, related inormation.

Note – Sun is not responsible or the availability o third-party web sites mentioned in thisdocument. Sun does not endorse and is not responsible or liable or any content, advertising,products, or other materials that are available on or through such sites or resources. Sun will notbe responsible or liable or any actual or alleged damage or loss caused or alleged to be caused by or in connection with use o or reliance on any such content, goods, or services that are available

on or through such sites or resources.

Sun Welcomes Your CommentsSun is interested in improving its documentation and welcomes your comments andsuggestions.

To share your comments, go to http://docs.sun.com and click Feedback. In the online orm,provide the document title and part number. The part number is a seven-digit or nine-digitnumber that can be ound on the title page o the book or at the top o the document.

Preace

23

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 24/326

24

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 25/326

Development Tasks andTools

P A R T I

25

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 26/326

26

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 27/326

Setting Up a Development Environment

This chapter gives guidelines or setting up an application development environment in the SunJavaTM System Communications Server. Setting up an environment or creating, assembling,deploying, and debugging your code involves installing the mainstream version o theCommunications Server and making use o development tools. In addition, sampleapplications are available. These topics are covered in the ollowing sections:

■ “Installing and Preparing the Server or Development” on page 27■ “The Sailn Project” on page 28■ “Usage Proles” on page 28■ “High Availability Features” on page 29■ “Development Tools” on page 29■ “Sample Applications” on page 31

Installing and Preparing the Server or DevelopmentFor more inormation about stand-alone Communications Server installation, see the SunGlassFish Communications Server 2.0 Installation Guide.

The ollowing components are included in the ull installation.

■ JDK

Communications Server core■ Java 2 Platorm, Standard Edition (Java SE) 6■ Java EE 6 compliant application server■ Admin Console■ asadmin utility ■ Other development and deployment tools■ Sun Java System Message Queue sotware■ The Java Business Integration runtime (JBI runtime)■

Java DB database, based on the Derby database rom Apache (http://db.apache.org/derby/manuals)

1C H A P T E R 1

27

The Sailfn Project

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 28/326

■ Load balancer plug-ins or web servers

The NetBeansTM Integrated Development Environment (IDE) bundles the GlassFish edition o 

the Communications Server, so inormation about this IDE is provided as well.Ater you have installed Communications Server, you can urther optimize the server ordevelopment in these ways:

■ Locate utility classes and libraries so they can be accessed by the proper class loaders. Formore inormation, see “Using the System Class Loader” on page 40 or “Using the CommonClass Loader” on page 40.

■ Set up debugging. For more inormation, see Chapter 4, “Debugging Applications.”

■ Congure the Java Virtual Machine (JVMTM) sotware. For more inormation, see Chapter22, “Java Virtual Machine and Advanced Settings,” in Sun GlassFish CommunicationsServer 2.0 Administration Guide.

The Sailfn Project

Communications Server 2.0 is developed through the Sailn project open-source community athttps://sailfin.dev.java.net/ . The Sailn project provides a structured process ordeveloping the Communications Server platorm that makes the new eatures o Java EE 5available aster, while maintaining the most important eature o Java EE: compatibility. Itenables Java developers to access the Communications Server source code and to contribute tothe development o the Communications Server. The Sailn project is designed to encouragecommunication between Sun engineers and the community.

Usage ProflesWhen you install a domain, the usage prole you select determines the eatures that areavailable by deault. Here is a summary o the usage proles:

■ developer prole - Provides a lightweight eature set optimized or developers, with oneserver instance and no clustering eatures.

■ cluster prole - Provides the complete GlassFish eature set, including clustering eatures.

For more inormation about usage proles, see “Usage Proles” in Sun GlassFishCommunications Server 2.0 Administration Guide.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200928

DevelopmentTools

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 29/326

High Availability FeaturesHigh availability eatures such as load balancing and session ailover are discussed in detail in

the Sun GlassFish Communications Server 2.0 High Availability Administration Guide. Thisbook describes the ollowing eatures in the ollowing sections:

■ For inormation about HTTP session persistence, see “Distributed Sessions and Persistence”on page 153.

■ For inormation about checkpointing o the stateul session bean state, see “Stateul SessionBean Failover” on page 180.

■ For inormation about ailover and load balancing or Java clients, seeChapter 11,

“Developing Java Clients.”■ For inormation about load balancing or message-driven beans, see“Load-BalancedMessage Inow” on page 292.

Development ToolsThe ollowing general tools are provided with the Communications Server:

■ “The asadmin Command” on page 29■ “The Admin Console” on page 30■ “The asant Utility” on page 30■ “The verifier Tool” on page 30

The ollowing development tools are provided with the Communications Server ordownloadable rom Sun:

■ “The NetBeans IDE” on page 30■ “The Migration Tool” on page 31

The ollowing third-party tools might also be useul:

■ “Debugging Tools” on page 31■ “Proling Tools” on page 31■ “The Eclipse IDE” on page 31

The asadmin Command

The asadmin command allows you to congure a local or remote server and perorm bothadministrative and development tasks at the command line. For general inormation aboutasadmin, seethe Sun GlassFish Communications Server 2.0 Reerence Manual .

The asadmin command is located in the as-install /bin directory. Type asadmin help or a list

o subcommands.

Chapter 1 • Setting Up a Development Environment 29

DevelopmentTools

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 30/326

The Admin Console

The Admin Console lets you congure the server and perorm both administrative and

development tasks using a web browser. For general inormation about the Admin Console,click the Help button in the Admin Console. This displays the Communications Server onlinehelp.

To access the Admin Console, type http://host :4848 (developer prole) orhttps://host :4848 (cluster prole) in your browser. The host is the name o the machine onwhich the Communications Server is running. By deault, the host is localhost. For example:

http://localhost:4848

The asant Utility

Apache Ant 1.6.5 is provided with the Communications Server and can be launched rom thebin directory using the command asant. The Communications Server also providesserver-specic tasks or administration and deployment; see Chapter 3, “The asant Utility.”

The sample applications that can be used with the Communications Server use Ant build.xmlles; see “Sample Applications” on page 31.

For more inormation about Ant, see the Apache Sotware Foundation web site athttp://ant.apache.org/.

The verifier Tool

The verifier tool checks a Java EE application le, including Java classes and deploymentdescriptors, or compliance with Java EE specications. Java EE application les are Java archive(JAR), web archive (WAR), resource adapter archive (RAR), or enterprise archive (EAR) les.Use the verifier tool to check whether an application complies with the Java EE specicationand to make applications portable across application servers. The verifier tool can belaunched rom the command line. For more inormation, see“The verier Utility” in SunGlassFish Communications Server 2.0 Application Deployment Guide.

The NetBeans IDE

The NetBeans IDE allows you to create, assemble, and debug code rom a single, easy-to-useinterace. The GlassFish edition o the Communications Server is bundled with the NetBeans5.5 IDE. To download the NetBeans IDE, see http://www.netbeans.org. This site alsoprovides documentation on how to use the NetBeans IDE with the bundled Communications

Server.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200930

Sample Applications

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 31/326

You can also use the Communications Server with the Sun Java Studio 8 sotware, which is builton the NetBeans IDE. For more inormation, see http://developers.sun.com/prodtech/

javatools/jsenterprise/.

The MigrationTool

The Migration Tool converts and reassembles Java EE applications and modules developed onother application servers. This tool also generates a report listing how many les aresuccessully and unsuccessully migrated, with reasons or migration ailure. For moreinormation and to download the Migration Tool, seehttp://java.sun.com/j2ee/tools/

migration/index.html.

DebuggingTools

You can use several debugging tools with the Communications Server. For more inormation,see Chapter 4, “Debugging Applications.”

ProflingTools

You can use several prolers with the Communications Server. For more inormation, see“Proling Tools” on page 74.

The Eclipse IDEA plug-in or the Eclipse IDE is available at http://glassfishplugins.dev.java.net/ . Thissite also provides documentation on how to register the Communications Server and useSun-specic deployment descriptors.

Sample Applications

Sample applications that you can examine and deploy to the Communications Server areavailable. I you installed the Communications Server as part o installing the Java EE 5 SDKbundle rom Java EE 5 Downloads (http://java.sun.com/javaee/5/downloads/ ), thesamples may already be installed. You can download these samples separately rom theCodeSamples (http://java.sun.com/javaee/reference/code/index.jsp ) page i you installedthe Communications Server without them initially.

Most Communications Server samples have the ollowing directory structure:

■ The docs directory contains instructions or how to use the sample.

Chapter 1 • Setting Up a Development Environment 31

Sample Applications

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 32/326

■ The build.xml le denes asant targets or the sample. See Chapter 3, “The asant Utility.”

■ The src/java directory under each component contains source code or the sample.

■ The src/conf directory under each component contains the deployment descriptors.

With a ew exceptions, sample applications ollow the standard directory structure describedhere: http://java.sun.com/blueprints/code/projectconventions.html .

The samples-install-dir /bp-project/main.xml le denes properties common to all sampleapplications and implements targets needed to compile, assemble, deploy, and undeploy sample applications. In most sample applications, the build.xml le imports main.xml.

In addition to the Java EE 5 sample applications, samples are also available on the GlassFish website at https://glassfish-samples.dev.java.net/ .

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200932

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 33/326

Class Loaders

Understanding Communications Server class loaders can help you determine where to placesupporting JAR and resource les or your modules and applications. For general inormationabout J2SE class loaders, see Understanding Network Class Loaders (http://java.sun.com/

developer/technicalArticles/Networking/classloaders/ ).

In a Java Virtual Machine (JVM), the class loaders dynamically load a specic Java class leneeded or resolving a dependency. For example, when an instance o java.util.Enumeration

needs to be created, one o the class loaders loads the relevant class into the environment. Thissection includes the ollowing topics:

■ “The Class Loader Hierarchy” on page 33■ “Delegation” on page 37■ “Using the Java Optional Package Mechanism” on page 37■

“Using the Endorsed Standards Override Mechanism” on page 37■ “Class Loader Universes” on page 38■ “Application-Specic Class Loading” on page 38■ “Circumventing Class Loader Isolation” on page 39

The Class Loader Hierarchy

Class loaders in the Communications Server runtime ollow a delegation hierarchy that isillustrated in the ollowing gure and ully described inTable 2–1.

2C H A P T E R 2

33

The ClassLoaderHierarchy

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 34/326

The ollowing table describes the class loaders in the Communications Server.

BootstrapClass Loader

SystemClass Loader

Shared ChainClass Loader

CommonClass Loader

MBeanClass Loader

ConnectorClass Loader

WebClass Loader

JSP EngineClass Loader

One class loader instance for each application or stand-alone module

ApplicationClass Loader

LifeCycleModuleClass Loader

FIGURE 2–1 ClassLoaderRuntime Hierarchy 

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200934

The Class Loader Hierarchy

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 35/326

TABLE 2–1 Sun GlassFish Communications Server Class Loaders

Class Loader Description

Bootstrap The Bootstrap class loaderloadsthebasicruntimeclassesprovided bytheJVM, plusany classesrom JAR les present in the system extensions directory. It is parent to theSystem class loader. To add JAR les to the system extensions, directory, see “Using theJava Optional Package Mechanism” on page 37.

System TheSystemclass loaderloads CommunicationsServer launchclasses.Itis parent totheShared Chainclass loader. It is created based on the system-classpath attribute o thejava-config element in the domain.xml le. In the developer prole, select theCommunications Server component in the Admin Console and the JVM Settings tab. Inthe cluster prole, select the JVM Settings component under the relevant conguration.Then select the Path Settings tab and edit the System Classpath eld. See “Using theSystem Class Loader” on page 40 and “java-cong” in Sun GlassFish Communications

Server 2.0 Administration Reerence.

Add the classes to the system-classpath attribute o the domain administration server(DAS) in addition to the system-classpath attribute on the server instances that usethe classes. The deault name or the DAS conguration is server-config.

Shared ChainThe Shared Chain class loader loads most o the core Communications Server classes. It

is parent to the MBean class loader and the Common class loader. Classes specied by the classpath-prefix and classpath-suffix attributes o the java-config elementinthe domain.xml le are added to this class loader. In the developer prole, select theCommunications Server component in the Admin Console and the JVM Settings tab. Inthe cluster prole, select the JVM Settings component under the relevant conguration.Then select the Path Settings tab and edit the Classpath Prex or Classpath Sux eld.

The environment classpath is included i env-classpath-ignored="false" issetinthejava-config element.

Use classpath-prefix to place libraries ahead o Communications Serverimplementation classes in the shared chain. The classpath-prefix is ideal or placingdevelopment and diagnostic patches. To avoid overriding implementation classes, useclasspath-suffix to place libraries ater implementation classes in the shared chain.

Add the classes to the classpath-prefix or classpath-suffix attribute o the DAS inaddition to the corresponding attribute on the server instances that use the classes. Thedeault name or the DAS conguration is server-config.

MBean TheMBean class loaderloads the MBeanimplementation classes.See “MBean Class

Loading” on page 253.

Common The Common class loader loads classesinthe domain-dir /lib/classes directory,ollowed by JAR les in the domain-dir /lib directory. It is parent to the Connector classloader. No special classpath settings are required. The existence o these directories isoptional; i they do not exist, the Common class loader is not created. See “Using theCommon Class Loader”on page 40.

Chapter 2 • Class Loaders 35

The ClassLoaderHierarchy

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 36/326

TABLE 2–1 Sun GlassFish Communications ServerClass Loaders (Continued)

Class Loader Description

Connector The Connector class loaderis a singleclassloader instancethat loads individually 

deployed connector modules, which are shared across all applications. It is parent to theLieCycleModule class loader and the Application class loader.

LieCycleModule The LieCycleModule class loader is created once per liecycle module. Eachlifecycle-module element’s classpath attribute is used to construct its own classloader. For more inormation on liecycle modules, see Chapter 13, “DevelopingLiecycle Listeners.”

Application The Application classloader loads the classes in a specic enabled individually deployedmodule or Java EEapplication. One instance o this class loader is present in each classloader universe; see “Class Loader Universes”on page 38. The Application class loader iscreated with a list o URLs that point to the locations o the classes it needs to load. It isparent to the Web class loader.

The Application class loader loads classes in the ollowing order:

1. Classes specied by the library-directory element in the application.xml

deployment descriptor or the –-libraries option during deployment; see

“Application-Specic Class Loading” on page 38

2. Classes specied by the application's or module's location attribute in thedomain.xml le, determined during deployment

3. Classes in the classpaths o the application's sub-modules

4. Classes in the application's or module's stubs directory 

The location attribute points to domain-dir /applications/j2ee-apps/app-name ordomain-dir /applications/j2ee-modules/module-name.

The stubs directory is domain-dir /generated/ejb/j2ee-apps/app-name or

domain-dir /generated/ejb/j2ee-modules/module-name.

Web The Web class loader loads the servlets and other classes in a specic enabled web orSIPmodule or a Java EEapplication that contains a web or SIP module. This class loader ispresent in each classloader universe that contains a web or SIP module; see “ClassLoader Universes” on page 38. One instance is created or each web or SIP module. TheWeb class loader is created with a list o URLs that point to the locations o the classes itneeds to load. The classesit loads are in WEB-INF/classes or WEB-INF/lib/*.jar.It isparent to the JSP Engine class loader.

JSP Engine The JSP Engineclassloader loads compiledJSPclasses oenabledJSPles.This classloader is present in each class loader universe that contains a JSP page;see “Class LoaderUniverses” on page 38. The JSP Engine class loader is created with a list o URLs thatpoint to the locations o the classesit needs to load.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200936

Using the Endorsed StandardsOverrideMechanism

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 37/326

DelegationNote that the class loader hierarchy is not a Java inheritance hierarchy, but a delegation

hierarchy. In the delegation design, a class loader delegates classloading to its parent beoreattempting to load a class itsel. A class loader parent can be either the System class loader oranother custom class loader. I the parent class loader cannot load a class, the class loaderattempts to load the class itsel. In efect, a class loader is responsible or loading only the classesnot available to the parent. Classes loaded by a class loader higher in the hierarchy cannot reerto classes available lower in the hierarchy.

The Java Servlet specication recommends that the Web class loader look in the local class

loader beore delegating to its parent. You can make the Web class loader ollow the delegationinversion model in the Servlet specication by setting delegate="false" in the class-loader

element o the sun-web.xml or sun-sip.xml le.ItissaetodothisonlyoraweborSIPmodule that does not interact with any other modules. For details, see“class-loader” in SunGlassFish Communications Server 2.0 Application Deployment Guide.

The deault value is delegate="true", which causes the Web class loader to delegate in the samemanner as the other class loaders. You must use delegate="true" or a web or SIP application

that accesses EJB components or that acts as a web service client or endpoint. For details aboutsun-web.xml or sun-sip.xml,see Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide.

Using the Java Optional Package MechanismOptional packages are packages o Java classes and associated native code that application

developers can use to extend the unctionality o the core platorm.

To use the Java optional package mechanism, copy the JAR les into the domain-dir /lib/ext

directory, then restart the server.

For more inormation, see Optional Packages - An Overview (http://java.sun.com/javase/

6/docs/technotes/guides/extensions/extensions.html ) and Understanding ExtensionClass Loading (http://java.sun.com/docs/books/tutorial/ext/basics/load.html ).

Using the Endorsed Standards Override MechanismEndorsed standards handle changes to classes and APIs that are bundled in the JDK but aresubject to change by external bodies.

To use the endorsed standards override mechanism, copy the JAR les into the

domain-dir /lib/endorsed directory, then restart the server.

Chapter 2 • Class Loaders 37

ClassLoaderUniverses

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 38/326

For more inormation and the list o packages that can be overridden, see Endorsed StandardsOverride Mechanism (http://java.sun.com/javase/6/docs/technotes/guides/

standards/).

Class Loader UniversesAccess to components within applications and modules installed on the server occurs withinthe context o isolated class loader universes, each o which has its own Application, EJB, Web,and JSP Engine class loaders.

■ ApplicationUniverse– Each Java EE application has its own class loader universe, which

loads the classes in all the modules in the application.■ IndividuallyDeployedModuleUniverse– Each individually deployed EJB JAR, web

WAR, SIP SAR, or liecycle module has its own class loader universe, which loads the classesin the module.

A resource such as a le that is accessed by a servlet, JSP, or EJB component must be in one o the ollowing locations:

A directory pointed to by the Libraries eld or --libraries option used during deployment■ A directory pointed to by the library-directory element in the application.xml

deployment descriptor

■ A directory pointed to by the class loader’s classpath; or example, the web class loader’sclasspath includes these directories:

module-name/WEB-INF/classes

module-name/WEB-INF/lib

Application-Specifc Class LoadingYou can speciy application-specic library classes during deployment in one o the ollowingways:

■ Use the Admin Console. Open the Applications component, then go to the page or the type

o application or module. Select the Deploy button. Type the comma-separated paths in theLibraries eld. For details, click the Help button in the Admin Console.

■ Use the asadmin deploy command with the --libraries option and speciy comma-separated paths. For details, see theSun GlassFish Communications Server 2.0Reerence Manual .

Application libraries are included in the Application class loader. Paths to libraries can berelative or absolute. A relative path is relative to domain-dir /lib/applibs. I thepath is

absolute, the path must be accessible to the domain administration server (DAS). The

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200938

C i i S i ll h i h lib i ll l

CircumventingClass Loader Isolation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 39/326

Communications Server automatically synchronizes these libraries to all remote clusterinstances when the cluster is restarted. However, libraries specied by absolute paths are notguaranteed to be synchronized.

Tip – You can use application-specic class loading to speciy a diferent XML parser than thedeault Communications Server XML parser. For details, see http://blogs.sun.com/

sivakumart/entry/classloaders_in_glassfish_an_attempt .

You can also use application-specic class loading to access diferent versions o a library romdiferent applications.

I multiple applications or modules reer to the same libraries, classes in those libraries areautomatically shared. This can reduce the memory ootprint and allow sharing o staticinormation. However, applications or modules using application-specic libraries are notportable. Other ways to make libraries available are described in “Circumventing Class LoaderIsolation” on page 39.

For general inormation about deployment, see the Sun GlassFish Communications Server 2.0

 Application Deployment Guide.

Note – I you see an access control error message when you try to use a library, you may need togrant permission to the library in the server.policy le. For more inormation, see “ChangingPermissions or an Application” on page 95.

Circumventing Class Loader IsolationSince each application or individually deployed module class loader universe is isolated, anapplication or module cannot load classes rom another application or module. This preventstwo similarly named classes in diferent applications rom interering with each other.

To circumvent this limitation or libraries, utility classes, or individually deployed modulesaccessed by more than one application, you can include the relevant path to the required classes

in one o these ways:■ “Using the System Class Loader” on page 40■ “Using the Common Class Loader” on page 40■ “Sharing Libraries Across a Cluster” on page 40■ “Packaging the Client JAR or One Application in Another Application” on page 41

Using the System class loader or Common class loader requires a server restart and makes alibrary accessible to all applications or modules deployed on servers that share the same

conguration.

Chapter 2 • Class Loaders 39

U i th S t Cl L d

Circumventing Class Loader Isolation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 40/326

Using the System Class Loader

To use the System class loader, do one o the ollowing, then restart the server:

■ Use the Admin Console. In the developer prole, select the Communications Servercomponent and select the JVM Settings tab. In the cluster prole, select the JVM Settingscomponent under the relevant conguration. Then select the Path Settings tab and edit theSystem Classpath eld. For details, click the Help button in the Admin Console.

■ Edit the system-classpath attribute o the java-config element in the domain.xml le.For details about domain.xml,seethe Sun GlassFish Communications Server 2.0

 Administration Reerence.

Using the System class loader makes an application or module accessible to all applications ormodules deployed on servers that share the same conguration.

Add the classes to the system-classpath attribute o the DAS in addition to thesystem-classpath attribute on the server instances that use the classes. The deault name orthe DAS conguration is server-config.

Using the Common Class Loader

To use the Common class loader, copy the JAR les into the domain-dir /lib directory or copy the .class les into the domain-dir /lib/classes directory, then restart the server.

Using the Common class loader makes an application or module accessible to all applications

or modules deployed on servers that share the same conguration.

For example, using the Common class loader is the recommended way o adding JDBC driversto the Communications Server. For a list o the JDBC drivers currently supported by theCommunications Server, see the Sun GlassFish Communications Server 2.0 Release Notes. Forcongurations o supported and other drivers, see“Congurations or Specic JDBC Drivers”in Sun GlassFish Communications Server 2.0 Administration Guide.

Sharing Libraries Across a Cluster

To share libraries across a specic cluster, copy the JAR les to thedomain-dir /config/cluster-confg-name/lib directory. Then add the path to the JAR les tothe System class loader as explained in “Using the System Class Loader” on page 40 ortotheShared Chain class loader as explained in Table 2–1.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200940

CircumventingClass Loader Isolation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 41/326

Note – Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domains

that are created with the cluster prole. For inormation about proles, see“Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

Packaging the Client JAR or One Application inAnother Application

By packaging the client JAR or one application in a second application, you allow an EJB orweb component in the second application to call an EJB component in the rst (dependent)application, without making either o them accessible to any other application or module.

As an alternative or a production environment, you can have the Common class loader loadthe client JAR o the dependent application as described in“Using the Common Class Loader”on page 40. Restart the server to make the dependent application accessible to all applications ormodules deployed on servers that share the same conguration.

▼ To Package the Client JAR or One Application inAnother Application

Deploy the dependent application.

Add the dependent application’s client JAR fle to the calling application.

■ For a calling EJB component, add the client JAR le at the same level as the EJB component.Then add a Class-Path entry to the MANIFEST.MF le o the calling EJB component. TheClass-Path entry has this syntax:

Class-Path: flepath1.jar flepath2.jar ...

Each flepath is relative to the directory or JAR le containing the MANIFEST.MF le. Fordetails, see the Java EE specication.

■ For a calling web component, add the client JAR le under the WEB-INF/lib directory.

I you need to package theclient JARwith both theEJB and web components, set

delegate="true" inthe class-loader element o the sun-web.xml fle.

This changes the Web class loader so that it ollows the standard class loader delegation model

and delegates to its parent beore attempting to load a class itsel.

1

2

3

Chapter 2 • Class Loaders 41

For most applications, packaging the client JAR le with the calling EJB component is sucient

Circumventing Class Loader Isolation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 42/326

For most applications, packaging the client JAR le with the calling EJB component is sucient.You do not need to package the client JAR le with both the EJB and web components unlessthe web component is directly calling the EJB component in the dependent application.

Deploy the calling application.

The calling EJB or web component must speciy in its sun-ejb-jar.xml or sun-web.xml le theJNDI name o the EJB component in the dependent application. Using an ejb-link mappingdoes not work when the EJB component being called resides in another application.

You do not need to restart the server.

4

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200942

3C H A P T E R 3

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 43/326

The asant Utility

Apache Ant 1.6.5 is provided with Communications Server and can be launched rom thebin

directory using the command asant. The Communications Server also provides server-specictasks, which are described in this section.

Make sure you have done these things beore using asant:

1. Include as-install /bin in the PATH environment variable (/usr/sfw/bin or Sun JavaTM

Enterprise System, or Java ES, on Solaris). The Ant script provided with theCommunications Server, asant, is located in this directory. For details on how to use asant,see the Sun GlassFish Communications Server 2.0 Reerence Manual .

2. I you are executing platorm-specic applications, such as the exec or cvs task, theANT_HOME environment variable must be set to the Ant installation directory.

■ The ANT_HOME environment variable or Java ES on Solaris is /usr/sfw and must

include the ollowing paths.■ /usr/sfw/bin – the Ant binaries (shell scripts)■ /usr/sfw/doc/ant – HTML documentation■ /usr/sfw/lib/ant – Java classes that implement Ant

■ The ANT_HOME environment variable or all other platorms is as-install /lib.

3. Set up your password le. The argument or the passwordfile option o each Ant task is ale. This le contains the password in the ollowing ormat.

AS_ADMIN_PASSWORD= password 

For more inormation about password les, see the Sun GlassFish CommunicationsServer 2.0 Reerence Manual .

This section covers the ollowing asant-related topics:

■ “Communications Server asant Tasks” on page 44■

“Reusable Subelements” on page 63■ “JBI Tasks” on page 68

3C H A P T E R 3

43

For more inormation about Ant, see the Apache Sotware Foundation web site at

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 44/326

phttp://ant.apache.org/.

For inormation about standard Ant tasks, see the Ant documentation athttp://ant.apache.org/manual/ .

Note – Variables in the examples in this chapter, such as ${asinstalldir}, reerence valuesdened in build.xml or properties les.

Communications Server asant Tasks

Use the asant tasks provided by the Communications Server or assembling, deploying, andundeploying modules and applications, and or conguring the server. The tasks are as ollows:

■ “The sun-appserv-deploy Task” on page 44■ “The sun-appserv-undeploy Task” on page 48■ “The sun-appserv-instance Task” on page 51■ “The sun-appserv-component Task” on page 54■ “The sun-appserv-admin Task” on page 57■ “The sun-appserv-jspc Task” on page 58■ “The sun-appserv-update Task” on page 60■ “The wsgen Task” on page 60■ “The wsimport Task” on page 62

The sun-appserv-deploy Task 

Deploys any o the ollowing to a local or remote Communications Server instance.

■ Enterprise application (EAR le)■ Web application (WAR le)■ SIP application (SAR le)■ Enterprise Java Bean (EJB-JAR le)■ Enterprise connector (RAR le)■ Application client

Subelements o sun-appserv-deploy

The ollowing table describes subelements or the sun-appserv-deploy task. These are objects

upon which this task acts.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200944

TABLE 3–1 The sun-appserv-deploy Subelements

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 45/326

Element Description

“The server Subelement” on page 63 An Communications Server instance“The component Subelement” on page 66 A component to be deployed

“The fileset Subelement” on page 68 A set o component lesthat match specied parameters

Attributes o sun-appserv-deploy

The ollowing table describes attributes or the sun-appserv-deploy task.

TABLE 3–2 The sun-appserv-deploy Attributes

Attribute Deault Description

file none (optional i a component or fileset subelement is present, otherwise required) Thecomponent to deploy. I this attribute reers to a le, it must be a valid archive. I thisattribute reers to a directory, it must contain a valid archive in which all componentshave beenexploded. I upload issetto false, this must be an absolute path on the

server machine.

name le name withoutextension

(optional) The display name or the component being deployed.

force true (optional) I true, the component is overwritten i it already exists on the server. I false, sun-appserv-deploy ails i the component exists.

retrievestubs client stubs notsaved

(optional) The directory where client stubs are saved. This attribute is inherited by nested component elements.

precompilejsp false (optional) I true, all JSP les ound in an enterprise application (.ear)orwebapplication (.war) are precompiled. This attribute is ignored or other componenttypes. This attribute is inherited by nested component elements.

verify false (optional) I true, syntax and semantics or all deployment descriptors areautomatically veried or correctness. This attribute is inherited by nested component

elements.

contextroot le name without

extension

(optional) The context root ora web module (WAR le) or SIP module (SAR le).

This attribute is ignored i the component is not a WAR or SAR le.

Chapter 3 • Theasant Utility 45

TABLE 3–2 The sun-appserv-deploy Attributes (Continued)

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 46/326

Attribute Deault Description

dbvendorname sun-ejb-jar.xml

entry 

(optional) The name o the database vendor or which tables can be created. Allowed

 values are javadb, db2, mssql, oracle, postgresql, pointbase, derby (also orCloudScape), and sybase, case-insensitive.

I not specied, the value o the database-vendor-name attribute insun-ejb-jar.xml is used.

I no value is specied, a connectionis made to the resource specied by thejndi-name subelement o the cmp-resource element in the sun-ejb-jar.xml le,and the database vendor name is read. I the connection cannot be established, or i the value is not recognized, SQL-92 compliance is presumed.

For details, see “Generation Options or CMP” on page 203.

createtables sun-ejb-jar.xml

entry (optional) I true, causes database tables to be created or beans that need them. I false, does not create tables. I not specied, the value o thecreate-tables-at-deploy attribute in sun-ejb-jar.xml is used.

For details, see “Generation Options” on page 128 and “Generation Options orCMP” on page 203.

dropandcreatetables sun-ejb-jar.xml

entry (optional) I true, and i tables were automatically created when this application waslast deployed, tables rom the earlier deployment are dropped and resh ones arecreated.

I true, and i tables were not automaticallycreated when this application was lastdeployed, no attempt is made to drop any tables.I tables with the same names asthose that would have been automatically created are ound, the deploymentproceeds, but a warning indicates that tables could not be created.

I false, settings o create-tables-at-deploy or drop-tables-at-undeploy in thesun-ejb-jar.xml le are overridden.

For details, see “Generation Options” on page 128 and “Generation Options orCMP” on page 203.

uniquetablenames sun-ejb-jar.xml

entry (optional) I true, species that table names are unique within each application serverdomain. I not specied, the value o the use-unique-table-names property insun-ejb-jar.xml is used.

For details, see “Generation Options or CMP” on page 203.

enabled true (optional) I true, enables the component.

deploymentplan none (optional)A deploymentplanis a JARle containingSun-specic descriptors.Usethis attribute when deploying an EAR le that lacks Sun-specic descriptors.

availabilityenabled false (optional) I true, enables high availability eatures, including persistence o HTTPor SIP sessions and checkpointing o the stateul session bean state.

generatermistubs false (optional) I true, generates the static RMI-IIOP stubs and puts them in the clientJAR le.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200946

TABLE 3–2 The sun-appserv-deploy Attributes (Continued)

Attrib te Dea lt Description

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 47/326

Attribute Deault Description

upload true (optional) I true, the component is transerred to the server or deployment. I the

component is being deployed on the local machine, set upload to false to reducedeployment time. I a directory is specied or deployment, upload must be false.

virtualservers deault virtualserver only 

(optional) A comma-separated list o virtual servers to be deployment targets. Thisattribute applies only to application (.ear),SIP(.sar),orweb(.war) componentsand is ignored or other component types. This attribute is inherited by nestedserver elements.

user admin (optional) The user name used when logging into the application serveradministration instance. This attribute is inherited by nested server elements.

passwordfile none (optional)Filecontaining passwords. The password romthisle isretrieved orcommunication with the application server administration instance. This attribute isinherited by nested server elements.

host localhost (optional) Target server. When deploying to a remote server, use the ully qualiedhost name. This attribute is inherited by nested server elements.

port 4848 (optional) The administration port on the target server. This attribute is inherited by nested server elements.

target name o deaultinstance

(optional) Target application server instance. This attribute is inherited by nestedserver elements.

asinstalldir see description (optional) The installation directory or the local Communications Serverinstallation, which is used to nd the administrative classes. I not specied, thecommand checks i the asinstalldir parameter has been set. Otherwise,administrative classes must be in the systemclasspath.

Examples o sun-appserv-deployHere is a simple application deployment script with many implied attributes:

<sun-appserv-deploy

file="${assemble}/simpleapp.ear"passwordfile="${passwordfile}" />

Here is an equivalent script showing all the implied attributes:

<sun-appserv-deploy

file="${assemble}/simpleapp.ear"name="simpleapp"force="true"precompilejsp="false"verify="false"upload="true"user="admin"

passwordfile="${passwordfile}"

Chapter 3 • Theasant Utility 47

host="localhost"port="4848"

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 48/326

port= 4848

target="${default-instance-name}"asinstalldir="${asinstalldir}" />

This example deploys multiple components to the same Communications Server instancerunning on a remote server:

<sun-appserv-deploy passwordfile="${passwordfile}" host="greg.sun.com"asinstalldir="/opt/sun" >

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"contextroot="test"/>

<component file="${assemble}/simplebean.jar"/>

</sun-appserv-deploy>

This example deploys multiple components to two Communications Server instances runningon remote servers. In this example, both servers are using the same admin password. I this werenot the case, each password could be specied in the server element.

<sun-appserv-deploy passwordfile="${passwordfile}" asinstalldir="/opt/sun" >

<server host="greg.sun.com"/><server host="joe.sun.com"/>

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"contextroot="test"/>

<component file="${assemble}/simplebean.jar"/>

</sun-appserv-deploy>

This example deploys the same components as the previous example because the three

components match the fileset criteria, but note that it is not possible to set somecomponent-specic attributes. All component-specic attributes (name and contextroot)usetheir deault values.

<sun-appserv-deploy passwordfile="${passwordfile}" host="greg.sun.com"asinstalldir="/opt/sun" >

<fileset dir="${assemble}" includes="**/*.?ar" />

</sun-appserv-deploy>

The sun-appserv-undeploy Task 

Undeploys any o the ollowing rom a local or remote Communications Server instance.

■ Enterprise application (EAR le)■ Web application (WAR le)■ SIP application (SAR le)

■ Enterprise Java Bean (EJB-JAR le)

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200948

■ Enterprise connector (RAR le)■ Application client

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 49/326

■ Application client

Subelements o sun-appserv-undeploy

The ollowing table describes subelements or the sun-appserv-undeploy task. These areobjects upon which this task acts.

TABLE 3–3 The sun-appserv-undeploy Subelements

Element Description

“The server Subelement” on page 63 An Communications Server instance

“The component Subelement” on page 66 A component to be deployed

“The fileset Subelement” on page 68 A set o component lesthat match specied parameters

Attributes o sun-appserv-undeploy

The ollowing table describes attributes or the sun-appserv-undeploy task.

TABLE 3–4 The sun-appserv-undeploy Attributes

Attribute Deault Description

name le name withoutextension

(optional i a component or fileset subelement is present or the file attribute is specied,otherwise required) The display name or the component being undeployed.

file none (optional) The component to undeploy. I this attribute reers to a le, it must be a valid

archive. I this attribute reers to a directory, it must contain a valid archive in which allcomponents have been exploded.

droptables sun-ejb-jar.xml

entry (optional) I true, causes database tables that were automatically created when the bean(s)were lastdeployed to be droppedwhen the bean(s) are undeployed. I false, does not droptables.

I not specied, the value o the drop-tables-at-undeploy attribute in sun-ejb-jar.xml

is used.

Fordetails, see “Generation Options” on page 128 and “Generation Options or CMP” onpage 203.

cascade false (optional) I true, deletes all connection pools and connector resources associated with theresource adapter being undeployed.

I false, undeployment ails i any pools or resources are still associated with the resourceadapter.

This attribute is applicable to connectors (resource adapters) and applications withconnector modules.

Chapter 3 • Theasant Utility 49

TABLE 3–4 The sun-appserv-undeploy Attributes (Continued)

Attribute Deault Description

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 50/326

user admin (optional) The user name used when logging into the application server administration

instance. This attribute is inherited by nested server elements.passwordfile none (optional)Filecontainingpasswords.The password romthisle isretrieved or

communication with the application server administration instance. This attribute isinherited by nested server elements.

host localhost (optional) Target server. When deploying to a remote server, use the ully qualied hostname. This attribute is inherited by nested server elements.

port 4848 (optional) The administration port on the target server. This attribute is inherited by nested

server elements.

target name o deaultinstance

(optional) Target application server instance. This attribute is inherited by nested server

elements.

asinstalldir see description (optional) The installation directory or the local Communications Server installation,which is used to nd the administrative classes. I not specied, the command checks to seei the asinstalldir parameter has been set. Otherwise, administrative classes must be inthe system classpath.

Examples o sun-appserv-undeploy

Here is a simple application undeployment script with many implied attributes:

<sun-appserv-undeploy name="simpleapp" passwordfile="${passwordfile}" />

Here is an equivalent script showing all the implied attributes:

<sun-appserv-undeployname="simpleapp"

user="admin"

passwordfile="${passwordfile}"

host="localhost"

port="4848"

target="${default-instance-name}"

asinstalldir="${asinstalldir}" />

This example demonstrates using the archive les (EAR and WAR, in this case) or theundeployment, using the component name (or undeploying the EJB component in thisexample), and undeploying multiple components.

<sun-appserv-undeploy passwordfile="${passwordfile}">

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-undeploy>

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200950

As with the deployment process, components can be undeployed rom multiple servers in asingle command. This example shows the same three components being removed rom two

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 51/326

g p p gdiferent instances o the Communications Server. In this example, the passwords or bothinstances are the same.

<sun-appserv-undeploy passwordfile="${passwordfile}">

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-undeploy>

The sun-appserv-instance Task 

Starts, stops, restarts, creates, or removes one or more application server instances.

Note – Some topics in the documentation pertain to eatures that are available only in domains

that are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see“Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

Subelements o sun-appserv-instance

The ollowing table describes subelements or the sun-appserv-instance task. These areobjects upon which this task acts.

TABLE 3–5 The sun-appserv-instance Subelements

Element Description

“The server Subelement” on page 63 An Communications Server instance

Attributes o sun-appserv-instance

The ollowing table describes attributes or the sun-appserv-instance task.

TABLE 3–6 The sun-appserv-instance Attributes

Attribute Deault Description

action none The control command or the targetapplicationserver.Validvalues are start, stop, create,anddelete. A restart sends the stop command ollowed by the start command. The restart

command is not supported on Windows.

Chapter 3 • Theasant Utility 51

TABLE 3–6 The sun-appserv-instance Attributes (Continued)

Attribute Deault Description

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 52/326

debug false (optional) Deprecated. I action issetto start, species whether the server starts in debug mode.

This attribute is ignored or other values o action. I true, the instance generates additionaldebugging output throughout its lietime. This attribute is inherited by nested server elements.

nodeagent none (required i  action is create, otherwiseignored) The name o the node agent on which the instanceis being created.

cluster none (optional, applicable only i  action is create) The clustered instance to be created. The server’sconguration is inherited rom the named cluster.

The config and cluster attributes are mutually exclusive. I both are omitted, a stand-alone server

instance is created.config none (optional, applicable only i  action is create) The conguration or the new stand-alone instance.

The conguration must exist and must not be default-config (the cluster conguration template)or an already reerenced stand-alone conguration (including the administration serverconguration server-config).

The config and cluster attributes are mutually exclusive. I both are omitted, a stand-alone serverinstance is created.

property none (optional, applicable only i  action is create) Denes systemproperties or the server instance.These properties override port settings in the server instance’s conguration. The ollowingproperties are dened: http-listener-1-port, http-listener-2-port, orb-listener-1-port,SSL-port, SSL_MUTUALAUTH-port, JMX_SYSTEM_CONNECTOR_port.

System properties can be changed ater instance creation using the system property commands. Fordetails, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

user admin (optional) The user name used when logging into the application server administration instance.This attribute is inherited by nested server elements.

passwordfile none (optional) File containing passwords. The password rom this le is retrieved or communicationwith the application server administration instance. This attribute is inherited by nested server

elements.

host localhost (optional) Target server. I it is a remote server, use the ully qualied host name. This attribute isinherited by nested server elements.

port 4848 (optional) The administration port on the target server. This attribute is inherited by nested server

elements.

instance name o deaultinstance

(optional) Target application server instance. This attribute is inherited by nested server elements.

asinstalldir seedescription

(optional) The installation directory or the local Communications Server installation, which is usedto nd the administrative classes. I not specied, the command checks to seei the asinstalldir

parameter has been set. Otherwise, administrative classes must be in the system classpath.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200952

Examples o sun-appserv-instance

This example starts the local Communications Server instance:

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 53/326

This example starts the local Communications Server instance:

<sun-appserv-instance action="start" passwordfile="${passwordfile}"instance="${default-instance-name}"/>

Here is an equivalent script showing all the implied attributes:

<sun-appserv-instance

action="start"

user="admin"

passwordfile="${passwordfile}"

host="localhost"port="4848"instance="${default-instance-name}"

asinstalldir="${asinstalldir}" />

Multiple servers can be controlled using a single command. In this example, two servers arerestarted, and in this case each server uses a diferent password:

<sun-appserv-instance action="restart"

instance="${default-instance-name}"/>

<server host="greg.sun.com" passwordfile="${password.greg}"/>

<server host="joe.sun.com" passwordfile="${password.joe}"/>

</sun-appserv-instance>

This example creates a new Communications Server instance:

<sun-appserv-instance

action="create" instanceport="8080"

passwordfile="${passwordfile}"

instance="development" />

Here is an equivalent script showing all the implied attributes:

<sun-appserv-instance

action="create"

instanceport="8080"

user="

admin"passwordfile="${passwordfile}"

host="localhost"port="4848"

instance="development"asinstalldir="${asinstalldir}" />

Instances can be created on multiple servers using a single command. This example creates anew instance named qa on two diferent servers. In this case, both servers use the same

password.

Chapter 3 • Theasant Utility 53

<sun-appserv-instance

action="create"

instanceport "8080"

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 54/326

instanceport= 8080

instance="qa"

passwordfile="${passwordfile}>

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

</sun-appserv-instance>

These instances can also be removed rom their respective servers:

<sun-appserv-instance

action="delete"instance="qa"

passwordfile="${passwordfile}>

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

</sun-appserv-instance>

Diferent instance names and instance ports can also be specied using attributes o the server

subelement:

<sun-appserv-instance action="create" passwordfile="${passwordfile}>

<server host="greg.sun.com" instanceport="8080" instance="qa"/>

<server host="joe.sun.com" instanceport="9090"

instance="integration-test"/>

</sun-appserv-instance>

The sun-appserv-component Task 

Enables or disables the ollowing Java EE component types that have been deployed to theCommunications Server.

■ Enterprise application (EAR le)■ Web application (WAR le)

■ SIP application (SAR le)■ Enterprise Java Bean (EJB-JAR le)■ Enterprise connector (RAR le)■ Application client

You do not need to speciy the archive to enable or disable a component: only the componentname is required. You can use the component archive, however, because it implies thecomponent name.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200954

Subelements o sun-appserv-component

The ollowing table describes subelements or the sun-appserv-component task. These are

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 55/326

g pp p

objects upon which this task acts.

TABLE 3–7 The sun-appserv-component Subelements

Element Description

“The server Subelement” on page 63 An Communications Server instance

“The component Subelement” on page 66 A component to be deployed

“The fileset Subelement” on page 68 A set o component les that match specied parameters

Attributes o sun-appserv-component

The ollowing table describes attributes or the sun-appserv-component task.

TABLE 3–8 The sun-appserv-component Attributes

Attribute Deault Description

action none The control command or the targetapplicationserver.Validvalues are enable and disable.

name le namewithoutextension

(optional i a component or fileset subelement is present or the file attribute is specied,otherwise required) The display name or the component being enabled or disabled.

file none (optional)The component toenable ordisable. Ithis attribute reersto a le,it mustbe a validarchive. I this attribute reers to a directory, it must containa valid archive in which all

components have been exploded.user admin (optional) The user name used when logging into the application server administration instance.

This attribute is inherited by nested server elements.

passwordfile none (optional) File containing passwords. The password rom this le is retrieved or communicationwith the application server administration instance. This attribute is inherited by nested server

elements.

host localhost (optional) Target server. When enabling or disabling a remote server, use the ully qualied host

name. This attribute is inherited by nested server elements.port 4848 (optional) The administration port on the target server. This attribute is inherited by nested

server elements.

target name o deaultinstance

(optional) Target application server instance. This attribute is inherited by nested server

elements.

Chapter 3 • Theasant Utility 55

TABLE 3–8 The sun-appserv-component Attributes (Continued)

Attribute Deault Description

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 56/326

asinstalldir see

description

(optional) The installation directory or the local Communications Server installation, which is

used to nd the administrative classes. I not specied, the command checks to seei theasinstalldir parameter has been set. Otherwise, administrative classes must be in the systemclasspath.

Examples o sun-appserv-component

Here is a simple example o disabling a component:

<sun-appserv-component

action="disable"name="simpleapp"

passwordfile="${passwordfile}" />

Here is a simple example o enabling a component:

<sun-appserv-component

action="enable"name=

"simpleapp

"passwordfile="${passwordfile}" />

Here is an equivalent script showing all the implied attributes:

<sun-appserv-component

action="enable"name="simpleapp"

user="admin"

passwordfile="${passwordfile}"host="localhost"

port="4848"

target="${default-instance-name}"

asinstalldir="${asinstalldir}" />

This example demonstrates disabling multiple components using the archive les (EAR andWAR, in this case) and using the component name (or an EJB component in this example).

<sun-appserv-component action="disable" passwordfile="${passwordfile}">

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-component>

Components can be enabled or disabled on multiple servers in a single task. This exampleshows the same three components being enabled on two diferent instances o the

Communications Server. In this example, the passwords or both instances are the same.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200956

<sun-appserv-component action="enable" passwordfile="${passwordfile}">

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 57/326

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/><component name="simplebean" />

</sun-appserv-component>

The sun-appserv-admin Task 

Enables arbitrary administrative commands and scripts to be executed on the Communications

Server. This is useul or cases where a specic Ant task has not been developed or a set o related commands are in a single script.

Subelements o sun-appserv-admin

The ollowing table describes subelements or the sun-appserv-admin task. These are objectsupon which this task acts.

TABLE 3–9 The sun-appserv-admin Subelements

Element Description

“The server Subelement” on page 63 An Communications Server instance

Attributes o sun-appserv-admin

The ollowing table describes attributes or the sun-appserv-admin task.

TABLE 3–10 The sun-appserv-admin Attributes

Attribute Deault Description

command none (exactly one o these is required: command or explicitcommand) The command to execute. I theuser, passwordfile, host, port, or target attributes are also specied, they are automatically inserted into the command beore execution. I any o these options are specied in thecommand string, the corresponding attribute values are ignored.

explicitcommand none (exactly one o these is required: command or explicitcommand) The exact command to execute.No command processing is done, and all other attributes are ignored.

user admin (optional) The user name used when logging into the application server administrationinstance. This attribute is inherited by nested server elements.

passwordfile none (optional)File containingpasswords. The passwordrom thisle isretrievedorcommunication with the application server administration instance. This attribute is inheritedby nested server elements.

Chapter 3 • Theasant Utility 57

TABLE 3–10 The sun-appserv-admin Attributes (Continued)

Attribute Deault Description

host localhost (optional) Target server I it is a remote server use the ully qualied host name This attribute

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 58/326

host localhost (optional) Target server. I it is a remote server, use the ully qualied host name. This attributeis inherited by nested server elements.

port 4848 (optional) The administration port on the target server. This attribute is inherited by nestedserver elements.

asinstalldir seedescription

(optional) The installation directory or the local Communications Server installation, which isused to nd the administrative classes. I not specied, the command checks i theasinstalldir parameter has beenset. Otherwise, administrative classesmust be in the systemclasspath.

Examples o sun-appserv-admin

Here is an example o executing the create-jms-dest command:

<sun-appserv-admin command="create-jms-dest --desttype topic">

Here is an example o using explicitcommand to execute the create-jms-dest command:

<sun-appserv-admin explicitcommand="create-jms-dest --user adminuser --host localhost

--port 4848 --desttype topic --target server1 simpleJmsDest">

The sun-appserv-jspc Task 

Precompiles JSP source code into Communications Server compatible Java code or initialinvocation by Communications Server. Use this task to speed up access to JSP les or to check the syntax o JSP source code. You can eed the resulting Java code to the javac task to generateclass les or the JSP les.

Attributes o sun-appserv-jspc

The ollowing table describes attributes or the sun-appserv-jspc task.

TABLE 3–11 The sun-appserv-jspc Attributes

Attribute Deault Description

destdir none The destination directory or the generated Javasource les.

srcdir none (exactly one othese is required: srcdir or webapp) The source directory where the JSP les arelocated.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200958

TABLE 3–11 The sun-appserv-jspc Attributes (Continued)

Attribute Deault Description

webapp none (exactly one o these is required: srcdir or webapp) The directory containing the web application

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 59/326

webapp none (exactly one o these is required: srcdir or webapp) The directory containing the web application.All JSP les within the directory are recursively parsed. The base directory must have a WEB-INF

subdirectory beneath it. When webapp is used, sun-appserv-jspc hands of all dependency checking to the compiler.

verbose 2 (optional) The verbosity integer to be passed to the compiler.

classpath none (optional)TheclasspathorrunningtheJSP compiler.

classpathref none (optional)A reerence totheJSP compilerclasspath.

uribase / (optional) The URI context o relative URI reerences in the JSP les. I this context does not exist, it

is derived rom the location o the JSP le relative to the declared or derived value o uriroot. Only pages translated rom an explicitly declared JSP le are afected.

uriroot seedescription

(optional) The root directory o the web application, against which URI les are resolved. I thisdirectory is not specied, the rst JSP le is used to derive it: each parent directory o the rst JSP leis searched ora WEB-INF directory, and the directory closest to the JSP le that has one is used. I noWEB-INF directory is ound, the directory rom which sun-appserv-jspc was calledis used. Only pages translated rom an explicitly declared JSP le (including tag libraries) are afected.

packagenone (optional)Thedestinationpackageor the generated Java classes.

asinstalldir seedescription

(optional) The installation directory or the local Communications Server installation, which isused to nd the administrative classes. I not specied, the command checks i the asinstalldir

parameter has been set. Otherwise, administrative classes must be in the system classpath.

Example o sun-appserv-jspc

The ollowing example uses the webapp attribute to generate Java source les rom JSP les. Thesun-appserv-jspc task is immediately ollowed by a javac task, which compiles the generatedJava les into class les. The classpath value in the javac task must be all on one line with nospaces.

<sun-appserv-jspc

destdir="${assemble.war}/generated"

webapp="${assemble.war}"

classpath="${assemble.war}/WEB-INF/classes"

asinstalldir="${asinstalldir}" />

<javac

srcdir="${assemble.war}/WEB-INF/generated"

destdir="${assemble.war}/WEB-INF/generated"

debug="on"

classpath="${assemble.war}/WEB-INF/classes:${asinstalldir}/lib/

appserv-rt.jar:${asinstalldir}/lib/appserv-ext.jar ">

<include name="**/*.java"/>

</javac>

Chapter 3 • Theasant Utility 59

The sun-appserv-update Task 

Enables deployed applications (EAR les) and modules (EJB JAR, RAR, and WAR les) to be

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 60/326

p y ppupdated and reloaded or ast iterative development. This task copies modied class les, XMLles, and other contents o the archive les to the appropriate subdirectory o thedomain-dir /applications directory, then touches the .reload le to cause dynamic reloadingto occur.

This is a local task and must be executed on the same machine as the Communications Server.

For more inormation about dynamic reloading, see theSun GlassFish Communications

Server 2.0 Application Deployment Guide.

Attributes o sun-appserv-update

The ollowing table describes attributes or the sun-appserv-update task.

TABLE 3–12 The sun-appserv-update Attributes

Attribute Deault Description

file none The componenttoupdate,which must bea valid archive.

domain domain1 (optional) The domain in which the application has been previously deployed.

Example o sun-appserv-update

The ollowing example updates the Java EE application foo.ear, which is deployed to thedeault domain, domain1.

<sun-appserv-update file="foo.ear"/>

The wsgen Task 

Generates JAX-WS portable artiacts used in JAX-WS web services. Reads a web serviceendpoint class and generates all the required artiacts or web service deployment andinvocation.

Attributes o wsgen

The ollowing table describes attributes or the wsgen task.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200960

TABLE 3–13 The wsgen Attributes

Attribute Deault Description

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 61/326

sei none Speciesthe name othe serviceendpointinterace (SEI)class.

destdir currentdirectory 

(optional) Species where to place the output generated classes.

classpath systemclasspath

(optional) Species where to nd the input class les. Same as cp

attribute.

cp systemclasspath

(optional) Species where to nd the input class les. Same asclasspath attribute.

resourcedestdir currentdirectory 

(optional) Species where to place generated resource les such asWSDLles. Used only i the genwsdl attribute is set to true.

sourcedestdir currentdirectory 

(optional) Species where to place generated source les.

keep false (optional) I true, keeps generated les.

verbose false (optional) I true, outputs compiler messages.

genwsdl true (optional) I true, generates a WSDL le.

protocol soap1.1 (optional) Species the protocol to use in the wsdl:binding. Used only i the genwsdl attribute is set to true.

Allowed values are soap1.1 or Xsoap1.2. Xsoap1.2 is not standard andis only used i the extension attribute is set to true.

servicename none (optional) S pecies a particular wsdl:service name or the generatedWSDLle. Used only i the genwsdl attribute is set to true. For example:

servicename="{http://mynamespace/}MyService"

portname none (optional) S pecies a particular wsdl:port name or the generatedWSDL. Used only i the genwsdl attribute is set to true. For example:

portname="{http://mynamespace/}MyPort"

extension false (optional) I true, allows vendor extensions not in the specication. Useo extensions mayresultin applications that are not portable and may not interoperate with other implementations.

Example o wsgen

The ollowing example generates portable artiacts or fromjava.server.AddNumbersImpl ,uses compile.classpath as the classpath, and writes the WSDL le to ${wsdl.dir}.

<wsgen

resourcedestdir="${wsdl.dir}"

Chapter 3 • Theasant Utility 61

sei="fromjava.server.AddNumbersImpl">

<classpath refid="compile.classpath"/>

</wsgen>

CommunicationsServer asant Tasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 62/326

The wsimport Task 

Generates JAX-WS portable artiacts or a given WSDL le. Portable artiacts include serviceendpoint interaces (SEIs), services, exception classes mapped rom the wsdl:fault andsoap:headerfault tags, asynchronous response beans derived rom the wsdl:message tag, andJAXB generated value types. Ater generation, these artiacts can be packaged in a WAR le

with the WSDL and schema documents along with the endpoint implementation and thendeployed.

Attributes o wsimport

The ollowing table describes attributes or the wsimport task.

TABLE 3–14 The wsimport Attributes

Attribute Deault Description

wsdl none Species t he n ame o the W SDL le.

destdir currentdirectory 

(optional) Species where to place the output generated classes.

sourcedestdir current

directory 

(optional) Species where to place generated source les. Used only i thekeep

attribute is set totrue

.keep false (optional) I true, keeps generated les.

verbose false (optional) I true, outputs compiler messages.

binding none (optional)Species external JAX-WS orJAXBbindingles.JAX-WS andJAXB binding les can customize things like package names and beannames. More inormation on JAX-WS and JAXB binding les can be oundin the customization documentation included with this release.

extension false (optional) I true, allows vendor extensionsnot in the specication. Use o extensions may result in applications that are not portable and may notinteroperate with other implementations.

wsdllocation none (optional) Species the value o  @WebService.wsdlLocation [email protected] annotation elements or the generatedSEI and Service interace. This should be setto the URI o the web serviceWSDL le.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200962

TABLE 3–14 The wsimport Attributes (Continued)

Attribute Deault Description

catalog none (optional)Species the catalog le toresolveexternal entityreerences.S d T C l d OAS S C l

Reusable Subelements

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 63/326

Supported ormats are TR9401, XCatalog, and OASIS XML Catalog.Additionally, the Ant xmlcatalog type can be used to resolve entities.

package none (optional)Species the targetpackage, overridinganyWSDL and schemabinding customization or package name, and the deault package namealgorithmdenedin the JAX-WS specication.

Example o wsimport

The ollowing example generates client-side artiacts or AddNumbers.wsdl and stores .class

les in the ${build.classes.home} directory using the custom.xml customization le.

<wsimport

destdir="${build.classes.home}"wsdl="AddNumbers.wsdl"binding="custom.xml">

</wsimport>

Reusable SubelementsReusable subelements o the Ant tasks or the Communications Server are as ollows. These areobjects upon which the Ant tasks act.

■ “The server Subelement” on page 63■ “The component Subelement” on page 66■ “The fileset Subelement” on page 68

The server Subelement

Species an Communications Server instance. Allows a single task to act on multiple serverinstances. The server attributes override corresponding attributes in the parent task; thereore,the parent task attributes unction as deault values.

Note – Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see“Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

Attributes o server

The ollowing table describes attributes or the server element.

Chapter 3 • Theasant Utility 63

TABLE 3–15 The server Attributes

Attribute Deault Description

user admin (optional) The user name used when logging into the Communications Server domain

Reusable Subelements

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 64/326

user admin (optional) The user name used when logging into the Communications Server domain

administration server (DAS).

passwordfile none (optional) File containing passwords. The password rom this le is retrieved or communicationwith the Communications Server DAS.

host localhost (optional) Target server. When targeting a remote server, use the ully qualied host name.

port 4848 (optional) The administration port on the target server.

instance name o 

deaultinstance

(optional) Target application server instance.

instanceport none (applies to “The sun-appserv-instance Task” on page 51 only) Deprecated.

nodeagent none (applies to “The sun-appserv-instance Task” on page 51 only, required i action is create,otherwise ignored) The name o the node agent on which the instance is being created.

debug false (applies to “The sun-appserv-instance Task” on page 51 only, optional) Deprecated. I action

issetto start, species whether the server starts in debug mode. This attribute is ignored or

other values o action. I true, the instance generates additionaldebugging output throughoutits lietime.

upload true (applies to “The sun-appserv-deploy Task” on page 44 only, optional) I true, the component istranserred to the server or deployment. I the component is being deployed on the localmachine, set upload to false to reduce deployment time.

virtualservers deault virtual serveronly 

(applies to “The sun-appserv-deploy Task” on page 44 only, optional) A comma-separated listo virtual servers to be deployment targets. This attribute applies only to application (.ear) orweb(.war) components and is ignored or other component types.

Examples o server

You can control multiple servers using a single task. In this example, two servers are started,each using a diferent password. Only the second server is started in debug mode.

<sun-appserv-instance action="start">

<server host="greg.sun.com" passwordfile="${password.greg}"/>

<server host="joe.sun.com" passwordfile="${password.joe}"debug="true"/>

</sun-appserv-instance>

You can create instances on multiple servers using a single task. This example creates a new instance named qa on two diferent servers. Both servers use the same password.

<sun-appserv-instance action="create" instanceport="8080"

instance="qa" passwordfile="${passwordfile}>

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200964

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

</sun-appserv-instance>

These instances can also be removed rom their respective servers:

Reusable Subelements

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 65/326

These instances can also be removed rom their respective servers:

<sun-appserv-instance action="delete" instance="qa"passwordfile="${passwordfile}>

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

</sun-appserv-instance>

You can speciy diferent instance names and instance ports using attributes o the nested

server element:

<sun-appserv-instance action="create" passwordfile="${passwordfile}>

<server host="greg.sun.com" instanceport="8080" instance="qa"/>

<server host="joe.sun.com" instanceport="9090"instance="integration-test"/>

</sun-appserv-instance>

You can deploy multiple components to multiple servers (see the“The component Subelement”

on page 66) . This example deploys each component to two Communications Server instancesrunning on remote servers. Both servers use the same password.

<sun-appserv-deploy passwordfile="${passwordfile}"asinstalldir="/opt/s1as8" >

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"

contextroot="test"/>

<component file="${assemble}/simplebean.jar"/>

</sun-appserv-deploy>

You can also undeploy multiple components rom multiple servers. This example shows thesame three components being removed rom two diferent instances. Both servers use the samepassword.

<sun-appserv-undeploy passwordfile="${passwordfile}">

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-undeploy>

You can enable or disable components on multiple servers. This example shows the same three

components being enabled on two diferent instances. Both servers use the same password.

Chapter 3 • Theasant Utility 65

<sun-appserv-component action="enable" passwordfile="${passwordfile}">

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

<component file="${assemble}/simpleapp.ear"/>

Reusable Subelements

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 66/326

<component file="${assemble}/simpleservlet.war"/><component name="simplebean" />

</sun-appserv-component>

The component Subelement

Species a Java EE component. Allows a single task to act on multiple components. Thecomponent attributes override corresponding attributes in the parent task; thereore, the parenttask attributes unction as deault values.

Attributes o component

The ollowing table describes attributes or the component element.

TABLE 3–16 The component Attributes

Attribute Deault Description

file none (optional i the parent task is “The sun-appserv-undeploy Task” on page 48 or “Thesun-appserv-component Task” on page 54) The target component. I this attribute reers to a le,it must be a valid archive. I this attribute reers to a directory, it must containa valid archive inwhich all components have been exploded. I upload issetto false, this must be an absolute pathon the server machine.

name le namewithoutextension

(optional) The display name or the component.

force true (applies to “The sun-appserv-deploy Task”on page 44 only, optional) I true, the component isoverwritten i it already exists on the server. I false, the containing element’s operation ails i the component exists.

precompilejsp false (applies to “The sun-appserv-deploy Task”on page 44 only, optional) I true, all JSP les ound

in an enterprise application (.ear) or web application (.war) are precompiled. This attribute isignored or other component types.

retrievestubs client stubsnot saved

(applies to “The sun-appserv-deploy Task”on page 44 only, optional) The directory whereclient stubs are saved.

contextroot le namewithoutextension

(applies to “The sun-appserv-deploy Task”on page 44 only, optional) The context root or aweb module (WAR le). This attribute is ignored i the component is not a WAR le.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200966

TABLE 3–16 The component Attributes (Continued)

Attribute Deault Description

verify false (applies to “The sun-appserv-deploy Task” on page 44 only, optional) I true, syntax andsemantics or all deployment descriptors is automatically veried or correctness.

Reusable Subelements

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 67/326

p y p y

Examples o component

You can deploy multiple components using a single task. This example deploys eachcomponent to the same Communications Server instance running on a remote server.

<sun-appserv-deploy passwordfile="${passwordfile}" host="greg.sun.com"asinstalldir="/opt/s1as8" >

<component file="${assemble}/simpleapp.ear"/><component file="${assemble}/simpleservlet.war"

contextroot="test"/>

<component file="${assemble}/simplebean.jar"/>

</sun-appserv-deploy>

You can also undeploy multiple components using a single task. This example demonstratesusing the archive les (EAR and WAR, in this case) and the component name (or the EJBcomponent).

<sun-appserv-undeploy passwordfile="${passwordfile}">

<component file="${assemble}/simpleapp.ear"/

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-undeploy>

You can deploy multiple components to multiple servers. This example deploys each

component to two instances running on remote servers. Both servers use the same password.

<sun-appserv-deploy passwordfile="${passwordfile}" asinstalldir="/opt/s1as8" >

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"contextroot="test"/>

<component file="${assemble}/simplebean.jar"/>

</sun-appserv-deploy>

You can also undeploy multiple components to multiple servers. This example shows the samethree components being removed rom two diferent instances. Both servers use the samepassword.

<sun-appserv-undeploy passwordfile="${passwordfile}">

<server host="greg.sun.com"/>

<server host="joe.sun.com"/>

Chapter 3 • Theasant Utility 67

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-undeploy>

JBITasks

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 68/326

You can enable or disable multiple components. This example demonstrates disabling multiplecomponents using the archive les (EAR and WAR, in this case) and the component name (orthe EJB component).

<sun-appserv-component action="disable" passwordfile="${passwordfile}">

<component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-component>

You can enable or disable multiple components on multiple servers. This example shows thesame three components being enabled on two diferent instances. Both servers use the samepassword.

<sun-appserv-component action="enable" passwordfile="${passwordfile}">

<server host="greg.sun.com"/>

<server host="joe.sun.com"/><component file="${assemble}/simpleapp.ear"/>

<component file="${assemble}/simpleservlet.war"/>

<component name="simplebean" />

</sun-appserv-component>

The fileset Subelement

Selects component les that match specied parameters. When fileset is included as asubelement, the name and contextroot attributes o the containing element must use theirdeault values or each le in the fileset. For more inormation, see http://ant.apache.org/

manual/CoreTypes/fileset.html .

 JBI TasksThe asant utility supports the Java Business Integration (JBI) Ant tasks. The Ant TasksReerence is included with the Communications Server at as-install /jbi/doc/antdoc/.

For more inormation about JBI in the Communications Server, see “JBI Runtime” on page 117.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200968

4C H A P T E R 4

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 69/326

Debugging Applications

This chapter gives guidelines or debugging applications in the Sun GlassFish CommunicationsServer. It includes the ollowing sections:

■ “Enabling Debugging” on page 69■ “JPDA Options” on page 70■ “Generating a Stack Trace or Debugging” on page 71■

“Application Client Debugging” on page 71■ “Sun GlassFish Message Queue Debugging” on page 72■ “Enabling Verbose Mode” on page 72■ “Communications Server Logging” on page 72■ “SIP Message Inspection Log Adapter” on page 73■ “Proling Tools” on page 74

Enabling DebuggingWhen you enable debugging, you enable both local and remote debugging. To start the server indebug mode, use the --debug option as ollows:

asadmin start-domain --user adminuser --debug [domain-name]

You can then attach to the server rom the Java Debugger (jdb) at its deault Java PlatormDebugger Architecture (JPDA) port, which is 9009. For example, or UNIX® systems:

jdb -attach 9009

For Windows:

jdb -connect com.sun.jdi.SocketAttach:port=9009

For more inormation about the jdb debugger, see the ollowing links:

69

■ Java Platorm Debugger Architecture - The Java Debugger: http://java.sun.com/

products/jpda/doc/soljdb.html

■ Java Platorm Debugger Architecture - Connecting with JDB: http://java.sun.com/

products/jpda/doc/conninv.html#JDB

JPDAOptions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 70/326

Communications Server debugging is based on the JPDA. For more inormation, see“JPDAOptions” on page 70.

You can attach to the Communications Server using any JPDA compliant debugger, includingthat o NetBeans (http://www.netbeans.org), Sun Java Studio, JBuilder, Eclipse, and so on.

You can enable debugging even when the application server is started without the --debug

option. This is useul i you start the application server rom the Windows Start Menu, or i you

want to make sure that debugging is always turned on.

▼ To Set the Server to Automatically Start Up in DebugMode

Use the Admin Console. In the developer profle,select the Communications Server component

andtheJVM Settings tab. In thecluster profle, select theJVM Settings component under the

relevant confguration.

Check theDebugEnabled box.

To speciy a dierentport (rom 9009, thedeault) to usewhen attaching theJVM to a debugger,

speciy address= port-number in theDebugOptions feld.

To addJPDA options, addany desired JPDA debugging options in Debug Options. See “JPDA

Options”on page 70.

For details, click the Help button in the Admin Console rom the JVM Settings page.

 JPDA OptionsThe deault JPDA options in Communications Server are as ollows:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9009

For Windows, you can change dt_socket to dt_shmem.

I you substitute suspend=y, the JVM starts in suspended mode and stays suspended until adebugger attaches to it. This is helpul i you want to start debugging as soon as the JVM starts.

1

2

3

4

See Also

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200970

To speciy a diferent port (rom 9009, the deault) to use when attaching the JVM to adebugger, speciy address= port-number .

You can include additional options. A list o JPDA debugging options is available at

http //java sun com/products/jpda/doc/conninv html#Invocation

Application Client Debugging

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 71/326

http://java.sun.com/products/jpda/doc/conninv.html#Invocation .

Generating a Stack Trace or DebuggingTo generate a Java stack trace or debugging, use the asadmin generate-jvm-report

--type=thread command. The stack trace goes to the domain-dir /logs/server.log le andalso appears on the command prompt screen. For more inormation about the asadmin

generate-jvm-report command, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Application Client DebuggingWhen the appclient script executes the java command to run the Application Client

Container (ACC), which in turn runs the client, it includes on the command line the value o the VMARGS environment variable. You can set this variable to any suitable value. The ollowingexample debugging setup is or Windows systems:

VMARGS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8118

The ollowing example debugging setup is or UNIX-based systems:

set VMARGS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8118

For debugging an application client, you should set suspend to y so you can connect thedebugger to the client beore any code has actually executed. Otherwise, the client may startrunning and execute past the point you want to examine.

You should use diferent ports or the server and client i you are debugging both concurrently.For details about setting the port, see “JPDA Options” on page 70.

For inormation about the appclient script, see Sun GlassFish Communications Server 2.0Reerence Manual .

Chapter 4 • Debugging Applications 71

Sun GlassFish Message Queue Debugging

Sun GlassFish Message Queue has a broker logger, which can be useul or debugging JavaMessage Service (JMS) applications, including message-driven bean applications. You canadjust the logger’s verbosity and you can send the logger output to the broker’s console using

Sun GlassFish Message Queue Debugging

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 72/326

adjust the loggers verbosity, and you can send the logger output to the brokers console usingthe broker’s -tty option. For more inormation, see the Sun GlassFish Message Queue 4.4

 Administration Guide.

Enabling Verbose Mode

To have the server logs and messages printed to System.out on your command prompt screen,you can start the server in verbose mode. This makes it easy to do simple debugging using printstatements, without having to view the server.log le every time.

To start the server in verbose mode, use the --verbose option as ollows:

asadmin start-domain --user adminuser --verbose [domain-name]

On Windows platorms, you must perorm an extra preparation step i you want to useCtrl-Break to print a thread dump. In the as-install /asenv.bat le, changeAS_NATIVE_LAUNCHER="false" to AS_NATIVE_LAUNCHER="true".

When the server is in verbose mode, messages are logged to the console or terminal window inaddition to the log le. In addition, pressing Ctrl-C stops the server and pressing Ctrl-\ (onUNIX platorms) or Ctrl-Break (on Windows platorms) prints a thread dump. On UNIXplatorms, you can also print a thread dump using the jstack command (seehttp://java.sun.com/javase/6/docs/technotes/tools/share/jstack.html )orthecommand kill -QUIT process_id .

Communications Server Logging

You can use the Communications Server’s log les to help debug your applications. Use theAdmin Console. In the developer prole, select the Communications Server component. In thecluster prole, select the Stand-Alone Instances component, and select the instance rom thetable. Then click the View Log Files button in the General Inormation page.

To change logging settings in the developer prole, select the Logging tab. In the cluster prole,select Logger Settings under the relevant conguration.

For details about logging, click the Help button in the Admin Console.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200972

SIP Message Inspection Log Adapter

You can create your own adapter or logging SIP Message Inspection messages. This adaptermust implement the org.jvnet.glassfish.comms.admin.reporter.

smi SmiLogMessageAdapter interace You can use the example

SIP Message Inspection Log Adapter

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 73/326

smi.SmiLogMessageAdapter interace. You can use the exampleorg.jvnet.glassfish.comms.admin.reporter.NullAdapter class as a template:

package org.jvnet.glassfish.comms.admin.reporter;

import javax.servlet.sip.SipServletRequest;

import javax.servlet.sip.SipServletResponse;

public class NullAdapter implements SMILogMessageAdapter {

public String getLogMessageIncomingRequest(SipServletRequest req) {

return null;

}

public String getLogMessageIncomingResponse(SipServletResponse resp) {

return null;

}

public String getLogMessageOutgoingRequest(SipServletRequest req) {

return null;

}

public String getLogMessageOutgoingResponse(SipServletResponse resp) {

return null;

}

public String getLogMessagePostIncomingRequest(SipServletRequest req,

Exception exceptionInCaseOfException) {

return null;

}

public String getLogMessagePostIncomingResponse(SipServletResponse resp,

Exception exceptionInCaseOfException) {

return null;

}

}

An adapter can log servlet or network manager messages. To determine the type o messagesthe adapter logs, set SIP Message Inspection properties in one o the ollowing ways:

■ Use the asadmin set command as ollows:

Chapter 4 • Debugging Applications 73

asadmin set confg .sip-service.property.smiServletAdapter= classpath;classname

asadmin set confg .sip-service.property.smiNetworkManagerAdapter= classpath;classname

The classpath and semicolon delimiter are optional. The classpath can be an additional

classpath outside the container classpath or a local le system path to the class that doesn'tl d k

ProflingTools

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 74/326

classpath outside the container classpath or a local le system path to the class that doesn tinclude package names.

The class name must be ully qualied. Periods and other special characters must beescaped. For example:

asadmin set server-config.sip-service.property.smiServletAdapter=org\.mypkg\.myServletAdapterImpl

For more inormation, see the Sun GlassFish Communications Server 2.0 Reerence Manual .■ Use the properties table in the SIP Service page in the Admin Console to set the

smiServletAdapter and smiNetworkManagerAdapter properties. For more inormation,click the Help button in the Admin Console.

Here are some suggested uses o an adapter or SIP Message Inspection logging:

■ You can log or not or a certain interception method.

■ You can log only or a certain user.■ You can collect inormation rom some methods, store it temporarily (or example session

attributes), then log it.

For more inormation about SIP Message Inspection logging, see “SIP Message Inspection” inSun GlassFish Communications Server 2.0 Administration Guide.

ProflingTools

You can use a proler to perorm remote proling on the Communications Server to discoverbottlenecks in server-side perormance. This section describes how to congure these prolersor use with the Communications Server:

■ “The NetBeans Proler” on page 75■ “The HPROF Proler” on page 75■ “The JProbe Proler” on page 76

Inormation about comprehensive monitoring and management support in the JavaTM 2Platorm, Standard Edition (J2SETM platorm) is available at http://java.sun.com/javase/6/

docs/technotes/guides/management/index.html .

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200974

The NetBeans Profler

For inormation on how to use the NetBeans proler, see http://www.netbeans.org andhttp://blogs.sun.com/

roller/page/bhavani?entry=analyzing the performance of java .

ProflingTools

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 75/326

p g y y g_ _p _ _j .

The HPROF Profler

The Heap and CPU Proling Agent (HPROF) is a simple proler agent shipped with the Java 2SDK. It is a dynamically linked library that interacts with the Java Virtual Machine ProlerInterace (JVMPI) and writes out proling inormation either to a le or to a socket in ASCII or

binary ormat.

HPROF can monitor CPU usage, heap allocation statistics, and contention proles. In addition,it can also report complete heap dumps and states o all the monitors and threads in the Java

 virtual machine. For more details on the HPROF proler, see the technical article athttp://java.sun.com/developer/technicalArticles/Programming/HPROF.html .

Ater HPROF is enabled using the ollowing instructions, its libraries are loaded into the server

process.

▼ To Use HPROF Profling on UNIX

Usethe Admin Console. In the developer profle,select the Communications Server componentandthe JVMSettings tab. In theclusterprofle, select theJVM Settings component under the

relevant confguration.Then select the Profler tab.

Edit the ollowing felds:

■ Proler Name – hprof

■ Proler Enabled – true

■ Classpath – (leave blank)

■ Native Library Path – (leave blank)

■ JVM Option – Select Add, type the HPROF JVM option in the Value eld, then check its

box. The syntax o the HPROF JVM option is as ollows:

-Xrunhprof[:help]|[: param=value, param2=value2, ...]

Here is an example o  params you can use:

-Xrunhprof:file=log.txt,thread=y,depth=3

The file parameter determines where the stack dump is written.

1

2

Chapter 4 • Debugging Applications 75

Using help lists parameters that can be passed to HPROF. The output is as ollows:

Hprof usage: -Xrunhprof[:help]|[:<option>=<value>, ...]

Option Name and Value Description Default--------------------- ----------- -------

ProflingTools

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 76/326

heap=dump|sites|all heap profiling all

cpu=samples|old CPU usage off

format=a|b ascii or binary output a

file=<file> write data to file java.hprof

(.txt for ascii)

net=<host>:<port> send data over a socket write to file

depth=<size> stack trace depth 4

cutoff=<value> output cutoff point 0.0001lineno=y|n line number in traces? y

thread=y|n thread in traces? n

doe=y|n dump on exit? y

Note – Donotuse help in the JVM Option eld. This parameter prints text to the standardoutput and then exits.

The help output reers to the parameters as options, but they are not the same thing as JVMoptions.

Restart the Communications Server.

This writes an HPROF stack dump to the le you specied using the file HPROF parameter.

The JProbe Profler

Inormation about JProbeTM rom Sitraka is available at http://www.quest.com/jprobe/ .

Ater JProbe is installed using the ollowing instructions, its libraries are loaded into the serverprocess.

▼ To Enable Remote ProflingWith JProbe

Install JProbe 3.0.1.1.

For details, see the JProbe documentation.

Confgure Communications Server usingthe Admin Console:

a. In thedeveloper profle, select theCommunications Server component andthe JVMSettings tab. In thecluster profle, select theJVM Settings component under therelevant

confguration. Then select the Profler tab.

3

1

2

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200976

b. Edit theollowing feldsbeore selecting Save andrestarting theserver:

■ Proler Name – jprobe

■ Proler Enabled – true

■ Classpath – (leave blank)

ProflingTools

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 77/326

■ Native Library Path – JProbe-dir /profiler

■ JVM Option – For each o these options, select Add, type the option in the Value eld,then check its box

-Xbootclasspath/p: JProbe-dir /profiler/jpagent.jar

-Xrunjprobeagent

-Xnoclassgc

Note – I any o the conguration options are missing or incorrect, the proler mightexperience problems that afect the perormance o the Communications Server.

When the server starts up with this conguration, you can attach the proler.

Set the ollowing environment variable:

JPROBE_ARGS_0=-jp_input= JPL-fle-path

See Step 6 or instructions on how to create the JPL le.

Start the server instance.

Launch the jpprofiler andattach to Remote Session.The deault port is 4444.

Create theJPL fle using theJProbe Launch Pad. Here are therequired settings:

a. Select Server Side or thetype o application.

b. On theProgramtab, provide theollowingdetails:

■ Target Server – other-server 

■ Server home Directory – as-install 

■ Server class File – com.sun.enterprise.server.J2EERunner

■ Working Directory – as-install 

■ Classpath – as-install /lib/appserv-rt.jar

■ Source File Path – source-code-dir (in case you want to get the line level details)

■ Server class arguments – (optional)

■ Main Package – com.sun.enterprise.server

3

4

5

6

Chapter 4 • Debugging Applications 77

You must also set VM, Attach, and Coverage tabs appropriately. For urther details, see theJProbe documentation. Ater you have created the JPL le, use this an input toJPROBE_ARGS_0.

ProflingTools

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 78/326

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200978

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 79/326

Developing Applications and Application

Components

P A R T I I

79

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 80/326

80

Securing Applications

5C H A P T E R 5

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 81/326

g pp

This chapter describes how to write secure Java EE applications, which contain componentsthat perorm user authentication and access authorization or the business logic o Java EEcomponents.

For inormation about administrative security or the Communications Server, seeChapter 9,“Conguring Security,” in Sun GlassFish Communications Server 2.0 Administration Guide.

For general inormation about Java EE security, see “Chapter 29: Introduction to Security inJava EE” in the Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/

index.html).

This chapter contains the ollowing sections:

■ “Security Goals” on page 82■ “Communications Server Specic Security Features” on page 82

■ “Container Security” on page 83■ “Roles, Principals, and Principal to Role Mapping” on page 84■ “Realm Conguration” on page 86■ “Using Identity Authentication” on page 89■ “Using P-Asserted Identity Authentication” on page 91■ “Creating a Custom Trust Handler or P-Asserted Identity Authentication” on page 92■ “JACC Support” on page 93■ “Pluggable Audit Module Support” on page 93■ “The server.policy File” on page 95■ “Conguring Message Security or Web Services” on page 98■ “Programmatic Login” on page 107■ “User Authentication or Single Sign-on” on page 110

81

Security Goals

In an enterprise computing environment, there are many security risks. The goal o the SunGlassFish Communications Server is to provide highly secure, interoperable, and distributed

component computing based on the Java EE security model. Security goals include:

F ll li i h h J EE i d l Thi i l d EJB d l l b d

Security Goals

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 82/326

■ Full compliance with the Java EE security model. This includes EJB and servlet role-basedauthorization.

■ Support or single sign-on across all Communications Server applications within a singlesecurity domain.

■ Support or web services message security.

■ Security support or application clients.■ Support or several underlying authentication realms, such as simple le and Lightweight

Directory Access Protocol (LDAP). Certicate authentication is also supported or SecureSocket Layer (SSL) client authentication. For Solaris, OS platorm authentication issupported in addition to these.

■ Support or declarative security through Communications Server specic XML-based rolemapping.

■ Support or Java Authorization Contract or Containers (JACC) pluggable authorization asincluded in the Java EE specication and dened by Java Specication Request (JSR) 115(http://www.jcp.org/en/jsr/detail?id=115 ).

■ Support or JavaTM Authentication Service Provider Interace or Containers as included inthe Java EE specication and dened by JSR196(http://www.jcp.org/en/jsr/

detail?id=196).

■ Support or Web Services Interoperability Technologies (WSIT) as described in The WSIT

Tutorial (https://wsit-docs.dev.java.net/releases/m5/ ).

■ Support or P-asserted identity authentication as dened inRFC (Request or Comments)3325 (http://www.ietf.org/rfc/rfc3325.txt).

Communications Server Specifc Security Features

The Communications Server supports the Java EE security model, as well as the ollowingeatures which are specic to the Communications Server:

■ Message security; see “Conguring Message Security or Web Services” on page 98

■ Single sign-on across all Communications Server applications within a single security domain; see “User Authentication or Single Sign-on” on page 110

■ Programmatic login; see “Programmatic Login” on page 107

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200982

Container SecurityThe component containers are responsible or providing Java EE application security. Thecontainer provides two security orms:

■ “Declarative Security” on page 83■ “Programmatic Security” on page 84

Container Security

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 83/326

■ Programmatic Security on page 84

 Annotations (also called metadata) enable a declarative style o programming, and soencompass both the declarative and programmatic security concepts. Users can speciy inormation about security within a class le using annotations. When the application isdeployed, this inormation can either be used by or overridden by the application or moduledeployment descriptor.

Declarative Security

Declarative security means that the security mechanism or an application is declared andhandled externally to the application. Deployment descriptors describe the Java EEapplication’s security structure, including security roles, access control, and authenticationrequirements.

The Communications Server supports the deployment descriptors specied by Java EE and hasadditional security elements included in its own deployment descriptors. Declarative security isthe application deployer’s responsibility. For more inormation about Sun-specic deploymentdescriptors, see the Sun GlassFish Communications Server 2.0 Application Deployment Guide.

There are two levels o declarative security, as ollows:

■ “Application Level Security” on page 83■ “Component Level Security” on page 84

Application Level Security

For an application, roles used by any application container must be dened in @DeclareRoles

annotations in the code or role-name elements in the application deployment descriptor(application.xml). The role names are scoped to the EJB XML deployment descriptors(ejb-jar.xml and sun-ejb-jar.xml les) and to the servlet XML deployment descriptors(web.xml and sun-web.xml les). For an individually deployed web or EJB module, you deneroles using @DeclareRoles annotations or role-name elements in the Java EE deploymentdescriptor les web.xml or ejb-jar.xml.

To map roles to principals and groups, dene matching security-role-mapping elements inthe sun-application.xml, sun-ejb-jar.xml, or sun-web.xml le or each role-name used by the application. For more inormation, see “Roles, Principals, and Principal to Role Mapping”on page 84.

Chapter 5 • Securing Applications 83

Component Level Security

Component level security encompasses web components and EJB components.

A secure web container authenticates users and authorizes access to a servlet or JSP by using the

security policy laid out in the servlet XML deployment descriptors (web.xml and sun-web.xml

les).

Roles, Principals, and Principal to RoleMapping

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 84/326

The EJB container is responsible or authorizing access to a bean method by using the security policy laid out in the EJB XML deployment descriptors (ejb-jar.xml and sun-ejb-jar.xml

les).

Programmatic Security

Programmatic security involves an EJB component or servlet using method calls to the security API, as specied by the Java EE security model, to make business logic decisions based on thecaller or remote user’s security role. Programmatic security should only be used whendeclarative security alone is insucient to meet the application’s security model.

The Java EE specication denes programmatic security as consisting o two methods o theEJB EJBContext interace and two methods o the servlet HttpServletRequest interace. TheCommunications Server supports these interaces as specied in the specication.

For more inormation on programmatic security, see the ollowing:

■ The Java EE Specication■ “Programmatic Login” on page 107

Roles, Principals, and Principal to Role Mapping

For applications, you dene roles in @DeclareRoles annotations or the Java EE deploymentdescriptor le application.xml. You dene the corresponding role mappings in theCommunications Server deployment descriptor le sun-application.xml. For individually deployed web or EJB modules, you dene roles in@DeclareRoles annotations or the Java EE

deployment descriptor les web.xml or ejb-jar.xml. You dene the corresponding rolemappings in the Communications Server deployment descriptor les sun-web.xml orsun-ejb-jar.xml.

For more inormation regarding Java EE deployment descriptors, see the Java EE Specication.For more inormation regarding Communications Server deployment descriptors, seeAppendix A, “Deployment Descriptor Files,” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200984

Each security-role-mapping element in the sun-application.xml, sun-web.xml, orsun-ejb-jar.xml le maps a role name permitted by the application or module to principalsand groups. For example, a sun-web.xml le or an individually deployed web module mightcontain the ollowing:

<sun-web-app>

<security-role-mapping>

Roles, Principals, and Principal to RoleMapping

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 85/326

<security role mapping>

<role-name>manager</role-name>

<principal-name>jgarcia</principal-name>

<principal-name>mwebster</principal-name>

<group-name>team-leads</group-name>

</security-role-mapping>

<security-role-mapping>

<role-name>administrator</role-name>

<principal-name>dsmith</principal-name>

</security-role-mapping>

</sun-web-app>

A role can be mapped to either specic principals or to groups (or both). The principal or groupnames used must be valid principals or groups in the realm or the application or module. Notethat the role-name in this example must match the @DeclareRoles annotations or the

role-name in the security-role element o the corresponding web.xml le.

You can also speciy a custom principal implementation class. This provides more exibility inhow principals can be assigned to roles. A user's JAAS login module now can authenticate itscustom principal, and the authenticated custom principal can urther participate in theCommunications Server authorization process. For example:

<security-role-mapping>

<role-name>administrator</role-name><principal-name class-name="CustomPrincipalImplClass">

dsmith

</principal-name>

</security-role-mapping>

You can speciy a deault principal and a deault principal to role mapping, each o whichapplies to the entire Communications Server instance. The deault principal to role mappingmaps group principals to named roles. Web or SIP modules that omit the run-as element inweb.xml or sip.xml use the deault principal. Applications and modules that omit thesecurity-role-mapping element use the deault principal to role mapping. These deaults arepart o the Security Service, which you can access in the ollowing ways:

■ In the Admin Console, select the Security component under the relevant conguration. Fordetails, click the Help button in the Admin Console.

■ Use the asadmin set command. For details, see the Sun GlassFish CommunicationsServer 2.0 Reerence Manual . For example, you can set the deault principal as ollows.

Chapter 5 • Securing Applications 85

asadmin set --user adminuser server1.security-service.default-principal=dsmith

asadmin set --user adminuser server1.security-service.default-principal-password=secret

You can set the deault principal to role mapping as ollows.

asadmin set --user adminuser server1.security-service.activate-default-principal-to-role-mapping=true

asadmin set --user adminuser server1.security-service.mapped-principal-class=CustomPrincipalImplClass

Realm Confguration

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 86/326

Realm ConfgurationThis section covers the ollowing topics:

■ “Supported Realms” on page 86■ “How to Congure a Realm” on page 87■ “How to Set a Realm or an Application or Module” on page 87■ “Creating a Custom Realm” on page 87

Supported RealmsThe ollowing realms are supported in the Communications Server:

■ file – Stores user inormation in a le. This is the deault realm when you rst install theCommunications Server.

■ ldap – Stores user inormation in an LDAP directory.

■ jdbc – Stores user inormation in a database.

In the JDBC realm, the server gets user credentials rom a database. The Application Serveruses the database inormation and the enabled JDBC realm option in the conguration le.

For digest authentication, a JDBC realm should be created with jdbcDigestRealm as theJAAS context. The realm must be reerenced in a realm-name element in the web.xml orsip.xml le as is standard practice.

For identity authentication or P-asserted identity authentication, a JDBC realm should becreated with assertedRealm as the JAAS context. The realm must be reerenced as

described in “Conguring sun-sip.xml or Identity Authentication” on page 90 or“Conguring sun-sip.xml or P-Asserted Identity Authentication” on page 91.

■ certificate – Sets up the user identity in the Communications Server security context, andpopulates it with user data obtained rom cryptographically veried client certicates.

■ solaris – Allows authentication using Solaris username+password data. This realm is only supported on the Solaris operating system, version 9 and above.

For inormation about conguring realms, see “How to Congure a Realm” on page 87.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200986

How to Confgure a Realm

You can congure a realm in one o these ways:

■ In the Admin Console, open the Security component under the relevant conguration and

go to the Realms page. For details, click the Help button in the Admin Console.

■ Use the asadmin create-auth-realm command to congure realms on local servers. For

Realm Confguration

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 87/326

gdetails, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

HowtoSetaRealmoranApplicationorModule

The ollowing deployment descriptor elements have optional realm or realm-name data

subelements or attributes that override the domain’s deault realm:

■ sun-application element in sun-application.xml

■ login-config element in web.xml

■ as-context element in sun-ejb-jar.xml

■ client-container element in sun-acc.xml

■ client-credential element in sun-acc.xml

I modules within an application speciy realms, these are ignored. I present, the realm denedin sun-application.xml is used, otherwise the domain’s deault realm is used.

For example, a realm is specied in sun-application.xml as ollows:

<sun-application>

...

<realm>ldap</realm>

</sun-application>

For more inormation about the deployment descriptor les and elements, seeAppendix A,“Deployment Descriptor Files,” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide.

Creating a Custom Realm

You can create a custom realm by providing a custom Java Authentication and AuthorizationService (JAAS) login module class and a custom realm class. Note that client-side JAAS loginmodules are not suitable or use with the Communications Server.

JAAS is a set o APIs that enable services to authenticate and enorce access controls upon users.JAAS provides a pluggable and extensible ramework or programmatic user authenticationand authorization. JAAS is a core API and an underlying technology or Java EE security mechanisms. For more inormation about JAAS, reer to the JAAS specication or Java SDK,available at http://java.sun.com/products/jaas/ .

Chapter 5 • Securing Applications 87

For general inormation about realms and login modules, see “Chapter 29: Introduction toSecurity in Java EE” in the Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/

tutorial/doc/index.html).

For Javadoc tool pages relevant to custom realms, go to http://glassfish.dev.java.net/

nonav/javaee5/api/index.html and click on the com.sun.appserv.security package.

Custom login modules must extend the

Realm Confguration

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 88/326

Custom login modules must extend thecom.sun.appserv.security.AppservPasswordLoginModule class. This class implementsjavax.security.auth.spi.LoginModule . Custom login modules must not implementLoginModule directly.

Custom login modules must provide an implementation or one abstract method dened in

AppservPasswordLoginModule :

abstract protected void authenticateUser() throws LoginException

This method perorms the actual authentication. The custom login module must notimplement any o the other methods, such as login(), logout(), abort(), commit(), orinitialize(). Deault implementations are provided in AppservPasswordLoginModule whichhook into the Communications Server inrastructure.

The custom login module can access the ollowing protected object elds, which it inherits romAppservPasswordLoginModule . These contain the user name and password o the user to beauthenticated:

protected String _username;

protected String _password;

The authenticateUser() method must end with the ollowing sequence:

String[] grpList;

// populate grpList with the set of groups to which

// _username belongs in this realm, if any

commitUserAuthentication(grpList);

Custom realms must extend the com.sun.appserv.security.AppservRealm class andimplement the ollowing methods:

public void init(Properties props) throws BadRealmException,

NoSuchRealmException

This method is invoked during server startup when the realm is initially loaded. Theprops

argument contains the properties dened or this realm in domain.xml. The realm can do any initialization it needs in this method. I the method returns without throwing an exception, theCommunications Server assumes that the realm is ready to service authentication requests. I anexception is thrown, the realm is disabled.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200988

public String getAuthType()

This method returns a descriptive string representing the type o authentication done by thisrealm.

public abstract Enumeration getGroupNames(String username) throws

InvalidOperationException, NoSuchUserException

Using Identity Authentication

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 89/326

This method returns an Enumeration (o String objects) enumerating the groups (i any) towhich the given username belongs in this realm.

Using Identity AuthenticationIdentity authentication is based on RFC 4475 and JSR 289. Using identity authentication in aSIP or converged web/SIP application involves the ollowing tasks:

■ “Conguring a Realm or Identity Authentication” on page 89■ “Conguring sip.xml or Identity Authentication” on page 89■ “Conguring sun-sip.xml or Identity Authentication” on page 90■ “Conguring the Identity Message Root Certicate” on page 90

Confguring a Realm or Identity Authentication

For identity authentication, you use a realm o class jdbcRealm, except that you set the JAAScontext value to assertedRealm.See “How to Congure a Realm” on page 87.

Confguring sip.xml or Identity AuthenticationTo congure a SIP or converged web/SIP application or identity authentication, speciy thesecurity-role, security-constraint,and login-config elements in the sip.xml le.

Part o speciying a security-constraint element is speciying one or moreresource-collection subelements. In turn, resource-collection elements have optionalsip-method subelements, which speciy the SIP methods on those resources within a servlet

application to which a security-constraint applies. I no SIP methods are specied, then thesecurity constraint applies to all SIP methods.

The login-config element is the only one that has values unique to identity authentication. Asspecied in JSR 289, identity authentication is available in two modes:REQUIRED or SUPPORTED.In the REQUIRED mode, the identity header must be present in the request. In the SUPPORTED

mode, incoming SIP messages are processed as ollows:

■ I the identity header is present, it is processed.

Chapter 5 • Securing Applications 89

■ I the identity header is not present, the authentication method congured in theauth-method element is applied.

Here is an example login-config with no auth-method or realm-name dened:

<login-config>

<identity-assertion>

<identity-assertion-scheme>Identity</identity-assertion-scheme>

Using Identity Authentication

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 90/326

<identity assertion scheme>Identity</identity assertion scheme>

<identity-assertion-support>REQUIRED</identity-assertion-support>

</identity-assertion>

</login-config>

Here is an example login-config with the auth-method and realm-name dened:

<login-config>

<auth-method>DIGEST</auth-method>

<realm-name>MyAssertedAppRealm</realm-name>

<identity-assertion>

<identity-assertion-scheme>Identity</identity-assertion-scheme>

<identity-assertion-support>SUPPORTED</identity-assertion-support>

</identity-assertion>

</login-config>

For more inormation, see JSR116(http://www.jcp.org/en/jsr/detail?id=116 ),theSIPServlet API Specication.

Confguring sun-sip.xml or Identity Authentication

Set the trust-auth-realm-ref property in the sun-sip.xml le. This property reers to the

jdbcRealm that has assertedRealm as its JAAS context value. See “Conguring a Realm orIdentity Authentication” on page 89.

For example:

<sun-sip-app>

...

<property name="trust-auth-realm-ref" value="MyAssertedAppRealm" />

</sun-sip-app>

Confguring the Identity Message Root Certifcate

To complete the conguration o identity authentication, add the root certicate (CerticateAuthority) o the public key used in the identity message to the cacerts.jks le. For moreinormation, see the keytool command description at http://java.sun.com/javase/6/

docs/technotes/tools/solaris/keytool.html .

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200990

Using P-Asserted Identity AuthenticationP-asserted identity authentication is based on RFC 3325 and JSR 289. Using P-asserted identity authentication in a SIP or converged web/SIP application involves the ollowing tasks, the rst

two o which are the same as or identity authentication:■ “Conguring a Realm or Identity Authentication” on page 89■ “Conguring sip.xml or Identity Authentication” on page 89

Using P-AssertedIdentityAuthentication

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 91/326

Conguring sip.xml or Identity Authentication on page 89■ “Conguring a Trust” on page 91■ “Conguring sun-sip.xml or P-Asserted Identity Authentication” on page 91

Confguring a TrustYou can create a P-asserted identity trust conguration in one o these ways:

■ In the Admin Console, open the Security component under the relevant conguration andgo to the Trust Congurations page. For details, click the Help button in the AdminConsole.

■ Use the asadmin create-trust-config command to create trust congurations on localservers. For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

The deault trust handler trusts all hosts and maps the P-Asserted-Identity header values to aormat suitable or use in authentication and authorization tasks. For example, Cullen

Jennings is mapped to CullenJ. To create a custom trust handler, see “Creating a CustomTrust Handler or P-Asserted Identity Authentication” on page 92.

Confguring sun-sip.xml or P-Asserted IdentityAuthentication

Set the ollowing properties in the sun-sip.xml le:

■ trust-auth-realm-ref — Reers to the jdbcRealm that has assertedRealm as its JAAScontext value. See “Conguring a Realm or Identity Authentication” on page 89.

■ trust-id-ref — Reers to the name o the trust conguration. See “Conguring a Trust”

on page 91.For example:

<sun-sip-app>

...

<property name="trust-auth-realm-ref" value="MyAssertedAppRealm" />

<property name="trust-id-ref" value="MyTrustConfig" />

</sun-sip-app>

Chapter 5 • Securing Applications 91

Creating a Custom Trust Handler or P-Asserted IdentityAuthentication

A trust handler is invoked or every SIP message that the Communications Server receives romor sends to the network. You can create a P-asserted identity trust conguration with a trusthandler in one o these ways:

Creating a CustomTrustHandler or P-AssertedIdentityAuthentication

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 92/326

■ In the Admin Console, open the Security component under the relevant conguration andgo to the Trust Congurations page. To speciy a custom trust handler, select Trust Handleras the Trust Type and enter the name o the trust handler class in the Class Name eld. Fordetails, click the Help button in the Admin Console.

Use the asadmin create-trust-config command to create trust congurations on localservers. To speciy a custom trust handler, use the --trusthandler option ollowed by thename o the trust handler class. For details, see the Sun GlassFish Communications Server 2.0

Reerence Manual .

A custom trust handler must implement thecom.sun.enterprise.security.auth.TrustHandler andcom.sun.enterprise.security.auth.PrincipalMapper interaces along with the ollowing

methods:

public boolean isTrusted(String asserterAddress, String trustedAs,

X509Certificate securityid, Principal [] pAssertedValues);

This method determines i the container can trust the network entity rom which the messagewith the P-Asserted-Identity header was received. This method also validates whether theidentity used to secure the message is trusted. I the network entity and identity can both be

trusted, this method returns true. Parameters are as ollows:■ asserterAddress — Species the IP address or hostname o the network entity rom which

the SIP message was received.

■ trustedAs —Avalueo INTERMEDIATE species that the trust conguration applies toincoming messages. A value o DESTINATION species that the trust conguration applies tooutgoing messages.

■ securityid — Species the asserting security identity. I a secure connection is used, it isthe java.security.cert.X509Certificate . Otherwise, it is null.

■ pAssertedValues — Species the P-Asserted-Identity header values.

public Principal [] mapIdentity(Principal [] assrtId);

This method accepts P-Asserted-Identity header values and returns them in a ormatunderstood by the SIP container.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200992

 JACC SupportJACC (Java Authorization Contract or Containers) is part o the Java EE specication anddened by JSR115(http://www.jcp.org/en/jsr/detail?id=115 ). JACC denes an interace

or pluggable authorization providers. Specically, JACC is used to plug in the Java policy provider used by the container to perorm Java EE caller access decisions. The Java policy provider perorms Java policy decisions during application execution. This provides thirdparties with a mechanism to develop and plug in modules that are responsible or answering

Pluggable Audit Module Support

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 93/326

parties with a mechanism to develop and plug in modules that are responsible or answeringauthorization decisions during Java EE application execution. The interaces and rules used ordeveloping JACC providers are dened in the JACC 1.0 specication.

The Communications Server provides a simple le-based JACC-compliant authorizationengine as a deault JACC provider. To congure an alternate provider using the AdminConsole, open the Security component under the relevant conguration, and select the JACCProviders component. For details, click the Help button in the Admin Console.

Pluggable Audit Module SupportAudit modules collect and store inormation on incoming requests (servlets, EJB components)and outgoing responses. You can create a custom audit module. This section covers theollowing topics:

■ “Conguring an Audit Module” on page 93■ “The AuditModule Class” on page 93

For additional inormation about audit modules, seeAudit Callbacks (http://

developers.sun.com/

prodtech/appserver/reference/techart/ws_mgmt3.html#8.2 ).

Confguring an Audit Module

To congure an audit module, you can perorm one o the ollowing tasks:

■ To speciy an audit module using the Admin Console, open the Security component underthe relevant conguration, and select the Audit Modules component. For details, click theHelp button in the Admin Console.

■ You can use the asadmin create-audit-module command to congure an audit module.For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

The AuditModule Class

You can create a custom audit module by implementing a class that extendscom.sun.appserv.security.AuditModule .

Chapter 5 • Securing Applications 93

For Javadoc tool pages relevant to audit modules, go to http://glassfish.dev.java.net/

nonav/javaee5/api/index.html and click on the com.sun.appserv.security package.

The AuditModule class provides deault “no-op” implementations or each o the ollowingmethods, which your custom class can override.

public void init(Properties props)

Pluggable Audit Module Support

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 94/326

The preceding method is invoked during server startup when the audit module is initially loaded. Theprops argument contains the properties dened or this module in domain.xml.The module can do any initialization it needs in this method. I the method returns withoutthrowing an exception, the Communications Server assumes the module realm is ready toservice audit requests. I an exception is thrown, the module is disabled.

public void authentication(String user, String realm, boolean success)

This method is invoked when an authentication request has been processed by a realm or thegiven user. The success ag indicates whether the authorization was granted or denied.

public void webInvocation(String user, HttpServletRequest req, String type, boolean success)

This method is invoked when a web container call has been processed by authorization. Thesuccess ag indicates whether the authorization was granted or denied. Thereq object is thestandard HttpServletRequest object or this request. The type string is one o hasUserDataPermission or hasResourcePermission (see JSR 115 (http://www.jcp.org/en/

jsr/detail?id=115)).

public void ejbInvocation(String user, String ejb, String method, boolean success)

This method is invoked when an EJB container call has been processed by authorization. Thesuccess ag indicates whether the authorization was granted or denied. Theejb and method

strings describe the EJB component and its method that is being invoked.

public void webServiceInvocation(String uri, String endpoint, boolean success)

This method is invoked during validation o a web service request in which the endpoint is aservlet. The uri is the URL representation o the web service endpoint. The endpoint is the

name o the endpoint representation. The success ag indicates whether the authorization wasgranted or denied.

public void ejbAsWebServiceInvocation(String endpoint, boolean success)

This method is invoked during validation o a web service request in which the endpoint is astateless session bean. The endpoint is the name o the endpoint representation. The success

ag indicates whether the authorization was granted or denied.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200994

The server.policy FileEach Communications Server domain has its own global J2SE policy le, located indomain-dir /config. The le is named server.policy.

The Communications Server is a Java EE compliant application server. As such, it ollows therequirements o the Java EE specication, including the presence o the security manager (theJava component that enorces the policy) and a limited permission set or Java EE application

d

The server.policy File

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 95/326

code.

This section covers the ollowing topics:

■ “Deault Permissions” on page 95■ “Changing Permissions or an Application” on page 95■ “Enabling and Disabling the Security Manager” on page 97

Deault PermissionsInternal server code is granted all permissions. These are covered by theAllPermission grantblocks to various parts o the server inrastructure code. Do not modiy these entries.

Application permissions are granted in the deault grant block. These permissions apply to allcode not part o the internal server code listed previously. The Communications Server doesnot distinguish between EJB and web (or SIP) module permissions. All code is granted theminimal set o web component permissions (which is a superset o the EJB minimal set). Do notmodiy these entries.

A ew permissions above the minimal set are also granted in the deault server.policy le.These are necessary due to various internal dependencies o the server implementation. Java EE

application developers must not rely on these additional permissions. In some cases, deletingthese permissions might be appropriate. For example, one additional permission is grantedspecically or using connectors. I connectors are not used in a particular domain, you shouldremove this permission, because it is not otherwise necessary.

Changing Permissions or an ApplicationThe deault policy or each domain limits the permissions o Java EE deployed applications to

the minimal set o permissions required or these applications to operate correctly. Do not addextra permissions to the deault set (the grant block with no codebase, which applies to all code).Instead, add a new grant block with a codebase specic to the applications requiring the extrapermissions, and only add the minimally necessary permissions in that block.

I you develop multiple applications that require more than this deault set o permissions, youcan add the custom permissions that your applications need. Thecom.sun.aas.instanceRoot

 variable reers to the domain-dir . For example:

Chapter 5 • Securing Applications 95

grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-apps/- " {

...

}

You can add permissions to stub code with the ollowing grant block:

grant codeBase "file:${com.sun.aas.instanceRoot}/generated/-" {

...

}

The server.policy File

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 96/326

}

In general, you should add extra permissions only to the applications or modules that requirethem, not to all applications deployed to a domain. For example:

grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-apps/MyApp/- " {...

}

For a module:

grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-modules/MyModule/- " {

...

}

An alternative way to add permissions to a specic application or module is to edit thegranted.policy le or that application or module. The granted.policy le is located in thedomain-dir /generated/policy/app-or-module-name directory. In this case, you addpermissions to the deault grant block. Do not delete permissions rom this le.

When the application server policy subsystem determines that a permission should not begranted, it logs a server.policy message speciying the permission that was not granted andthe protection domains, with indicated code source and principals that ailed the protectioncheck. For example, here is the rst part o a typical message:

[#|2005-12-17T16:16:32.671-0200|INFO|sun-appserver-pe9.1|

javax.enterprise.system.core.security|_ThreadID=14;_ThreadName=Thread-31;|

JACC Policy Provider: PolicyWrapper.implies, context(null)-

permission((java.util.PropertyPermission java.security.manager write))

domain that failed(ProtectionDomain

(file:/E:/glassfish/domains/domain1/applications/j2ee-modules/cejug-clfds/ ... )

...

Granting the ollowing permission eliminates the message:

grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-modules/cejug-clfds/- " {

permission java.util.PropertyPermission "java.security.manager", "write";

}

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200996

Note – Donotadd java.security.AllPermission to the server.policy le or applicationcode. Doing so completely deeats the purpose o the security manager, yet you still get theperormance overhead associated with it.

As noted in the Java EE specication, an application should provide documentation o theadditional permissions it needs. I an application requires extra permissions but does notdocument the set it needs contact the application author or details

The server.policy File

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 97/326

document the set it needs, contact the application author or details.

As a last resort, you can iteratively determine the permission set an application needs by observing AccessControlException occurrences in the server log.

I this is not sucient, you can add the -Djava.security.debug=failure JVM option to thedomain. Use the ollowing asadmin create-jvm-options command, then restart the server:

asadmin create-jvm-options --user adminuser -Djava.security.debug=failure

For more inormation about the asadmin create-jvm-options command, see the SunGlassFish Communications Server 2.0 Administration Reerence.

You can use the J2SE standard policytool or any text editor to edit the server.policy le. For

more inormation, see http://java.sun.com/docs/books/tutorial/security1.2/tour2/index.html.

For detailed inormation about policy le syntax, see http://java.sun.com/

javase/6/docs/technotes/guides/security/PolicyFiles.html#FileSyntax .

For inormation about using system properties in the server.policy le, seehttp://java.sun.com/

javase/6/docs/technotes/guides/security/PolicyFiles.html#PropertyExp.Forinormation about Communications Server system properties, see “system-property” in Sun

GlassFish Communications Server 2.0 Administration Reerence.

For detailed inormation about the permissions you can set in the server.policy le, seehttp://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html .

The Javadoc or the Permission class is at http://java.sun.com/javase/6/docs/api/java/

security/Permission.html.

Enabling and Disabling the Security Manager

The security manager is disabled in the developer and cluster proles by deault.

In a production environment, you may be able to saely disable the security manager i all o theollowing are true:

Chapter 5 • Securing Applications 97

■ Perormance is critical■ Deployment to the production server is careully controlled■ Only trusted applications are deployed■ Applications don't need policy enorcement

Disabling the security manager may improve perormance signicantly or some types o applications. To disable the security manager, do one o the ollowing:

■ To use the Admin Console, open the Security component under the relevant conguration,

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 98/326

and uncheck the Security Manager Enabled box. Then restart the server. For details, click the Help button in the Admin Console.

■ Use the ollowing asadmin delete-jvm-options command, then restart the server:

asadmin delete-jvm-options --user adminuser -Djava.security.manager

To re-enable the security manager, use the corresponding create-jvm-options command.For more inormation about the create-jvm-options and asadmin delete-jvm-options

commands, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Confguring Message Security or Web ServicesIn message security , security inormation is applied at the message layer and travels along withthe web services message. Web Services Security (WSS) is the use o XML Encryption and XMLDigital Signatures to secure messages. WSS proles the use o various security tokens includingX.509 certicates, Security Assertion Markup Language (SAML) assertions, andusername/password tokens to achieve this.

Message layer security difers rom transport layer security in that it can be used to decouple

message protection rom message transport so that messages remain protected atertransmission, regardless o how many hops they travel.

Note – In this release o the Communications Server, message layer annotations are notsupported.

For more inormation about message security, see the ollowing:■ The Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/

index.html) chapter titled “Chapter 29: Introduction to Security in Java EE”

■ Chapter 10, “Conguring Message Security,” in Sun GlassFish Communications Server 2.0 Administration Guide

■ JSR 196 (http://www.jcp.org/en/jsr/detail?id=196 ), Java Authentication ServiceProvider Interace or Containers

Sun GlassFishCommunications Server2.0 Developer's Guide • October 200998

■ The Liberty Alliance Project specications at http://www.projectliberty.org/

resources/specifications.php

■ The Oasis Web Services Security (WSS) specication at http://docs.oasis-open.org/

wss/2004/01/oasis-200401-wss-soap-message-security-1.0.pdf

■ The Web Services Interoperability Organization (WS-I) Basic Security Prole (BSP)specication at http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html

■ The XML and Web Services Security page at https://xwss.dev.java.net/

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 99/326

■ The WSIT page at https://wsit.dev.java.net/

The ollowing web services security topics are discussed in this section:

■ “Message Security Providers” on page 99■ “Message Security Responsibilities” on page 100■ “Application-Specic Message Protection” on page 102■ “Understanding and Running the Sample Application” on page 105

Message Security Providers

When you rst install the Communications Server, the providers XWS_ClientProvider andXWS_ServerProvider are congured but disabled. You can enable them in one o the ollowingways:

■ To enable the message security providers using the Admin Console, open the Security component under the relevant conguration, select the Message Security component, andselect SOAP. Then select XWS_ServerProvider rom the Deault Provider list andXWS_ClientProvider rom the Deault Client Provider list. For details, click the Helpbutton in the Admin Console.

■ You can enable the message security providers using the ollowing commands.

asadmin set --user adminuser

server-config.security-service.message-security-config.SOAP.default_provider=XWS_ServerProvider

asadmin set --user adminuser

server-config.security-service.message-security-config.SOAP.default_client_provider=XWS_ClientProvider

For more inormation about the asadmin set command, see the Sun GlassFish

Communications Server 2.0 Reerence Manual .

The example described in “Understanding and Running the Sample Application” on page 105uses the ClientProvider and ServerProvider providers, which are enabled when theasant

targets are run. You don’t need to enable these on the Communications Server prior to runningthe example.

I you install the Access Manager, you have these additional provider choices:

Chapter 5 • Securing Applications 99

■ AMClientProvider and AMServerProvider – These providers secure web services andSimple Object Access Protocol (SOAP) messages using either WS-I BSP or Liberty ID-WSFtokens. These providers are used automatically i they are congured as the deaultproviders. I you wish to override any provider settings, you can congure these providers inmessage-security-binding elements in the sun-web.xml, sun-ejb-jar.xml,andsun-application-client.xml deployment descriptor les.

■ AMHttpProvider – This provider handles the initial end user authentication or securingweb services using Liberty ID-WSF tokens and redirects requests to the Access Manager orsingle sign on To use this provider speciy it in the httpservlet sec rity provider

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 100/326

single sign-on. To use this provider, speciy it in the httpservlet-security-provider

attribute o the sun-web-app element in the sun-web.xml le.

Liberty specications can be viewed at http://www.projectliberty.org/resources/

specifications.php. The WS-I BSP specication can be viewed at http://www.ws-i.org/

Profiles/BasicSecurityProfile-1.0.html .

For more inormation about the Sun-specic deployment descriptor les, see theSun GlassFishCommunications Server 2.0 Application Deployment Guide.

For inormation about conguring these providers in the Communications Server, see Chapter10, “Conguring Message Security,” in Sun GlassFish Communications Server 2.0 Administration Guide. For additional inormation about overriding provider settings, see

“Application-Specic Message Protection” on page 102.

You can create new message security providers in one o the ollowing ways:

■ To create a message security provider using the Admin Console, open the Security component under the relevant conguration, and select the Message Security component.For details, click the Help button in the Admin Console.

■ You can use the asadmin create-message-security-provider command to create amessage security provider. For details, see theSun GlassFish Communications Server 2.0Reerence Manual .

In addition, you can set a ew optional provider properties. For more inormation, see theproperty descriptions under “provider-cong” in Sun GlassFish Communications Server 2.0 Administration Reerence.

Message Security ResponsibilitiesIn the Communications Server, the system administrator and application deployer roles areexpected to take primary responsibility or conguring message security. In some situations, theapplication developer may also contribute, although in the typical case either o the other rolesmay secure an existing application without changing its implementation and without involvingthe developer. The responsibilities o the various roles are dened in the ollowing sections:

■ “Application Developer” on page 101

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009100

■ “Application Deployer” on page 101■ “System Administrator” on page 101

Application Developer

The application developer can turn on message security, but is not responsible or doing so.Message security can be set up by the system administrator so that all web services are secured,or set up by the application deployer when the provider or protection policy bound to theapplication must be diferent rom that bound to the container.

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 101/326

The application developer is responsible or the ollowing:

■ Determining i an application-specic message protection policy is required by theapplication. I so, ensuring that the required policy is specied at application assembly which may be accomplished by communicating with the application deployer.

■ Determining i message security is necessary at the Communications Server level. I so,ensuring that this need is communicated to the system administrator, or taking care o implementing message security at the Communications Server level.

Application Deployer

The application deployer is responsible or the ollowing:

■ Speciying (at application assembly) any required application-specic message protectionpolicies i such policies have not already been specied by upstream roles (the developer orassembler)

■ Modiying Sun-specic deployment descriptors to speciy application-specic messageprotection policies inormation (message-security-binding elements) to web serviceendpoint and service reerences

These security tasks are discussed in “Application-Specic Message Protection” on page 102. Asample application using message security is discussed in “Understanding and Running theSample Application” on page 105.

System Administrator

The system administrator is responsible or the ollowing:

■ Conguring message security providers on the Communications Server.

■ Managing user databases.

■ Managing keystore and truststore les.

■ Installing the sample. This is only done i the xms sample application is used to demonstratethe use o message layer web services security.

A system administrator uses the Admin Console to manage server security settings and uses acommand line tool to manage certicate databases. Certicates and private keys are stored in

Chapter 5 • Securing Applications 101

key stores and are managed with keytool. System administrator tasks are discussed in Chapter10, “Conguring Message Security,” in Sun GlassFish Communications Server 2.0 Administration Guide.

Application-Specifc Message Protection

When the Communications Server provided conguration is insucient or your security needs, and you want to override the deault protection, you can apply application-specifc

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 102/326

, y p , y pp y pp p fmessage security to a web service.

Application-specic security is implemented by adding the message security binding to the webservice endpoint, whether it is an EJB or servlet web service endpoint. Modiy Sun-specic XML

les to add the message binding inormation.

Message security can also be specied using a WSIT security policy in the WSDL le. Fordetails, see the WSIT page at https://wsit.dev.java.net/ .

For more inormation about message security providers, see “Message Security Providers” onpage 99.

For more details on message security binding or EJB web services, servlet web services, andclients, see the XML le descriptions in Appendix A, “Deployment Descriptor Files,” in SunGlassFish Communications Server 2.0 Application Deployment Guide.

■ For sun-ejb-jar.xml,see “The sun-ejb-jar.xml File” in Sun GlassFish CommunicationsServer 2.0 Application Deployment Guide.

■ For sun-web.xml,see “The sun-web.xml File” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

For sun-application-client.xml, see “The sun-application-client.xml le” in SunGlassFish Communications Server 2.0 Application Deployment Guide.

This section contains the ollowing topics:

■ “Using a Signature to Enable Message Protection or All Methods” on page 102■ “Conguring Message Protection or a Specic Method Based on Digital Signatures” on

page 103

Using a Signature to Enable Message Protection or All MethodsTo enable message protection or all methods using digital signature, update themessage-security-binding element or the EJB web service endpoint in the application’ssun-ejb-jar.xml le. In this le, add request-protection and response-protection

elements, which are analogous to the request-policy and response-policy elementsdiscussed in Chapter 10, “Conguring Message Security,” in Sun GlassFish CommunicationsServer 2.0 Administration Guide. To apply the same protection mechanisms or all methods,

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009102

leave the method-name element blank. “Conguring Message Protection or a Specic MethodBased on Digital Signatures” on page 103 discusses listing specic methods or using wildcardcharacters.

This section uses the sample application discussed in “Understanding and Running the Sample

Application” on page 105 to apply application-level message security to show only thediferences necessary or protecting web services using various mechanisms.

▼ To Enable Message Protection or All Methods Using Digital Signature

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 103/326

To Enable Message Protection or All Methods Using Digital Signature

In a text editor, openthe application’s sun-ejb-jar.xml fle.

For the xms example, this le is located in the directory app-dir /xms-ejb/src/conf, where

app-dir is dened in “To Set Up the Sample Application” on page 105.

Modiy the sun-ejb-jar.xml fleby addingthe message-security-binding element as

shown:

<sun-ejb-jar>

<enterprise-beans>

<unique-id>1</unique-id>

<ejb>

<ejb-name>HelloWorld</ejb-name><jndi-name>HelloWorld</jndi-name>

<webservice-endpoint>

<port-component-name>HelloIF</port-component-name>

<endpoint-address-uri>service/HelloWorld</endpoint-address-uri>

<message-security-binding auth-layer="SOAP">

<message-security>

<request-protection auth-source="content" />

<response-protection auth-source="content"/>

</message-security>

</message-security-binding>

</webservice-endpoint>

</ejb>

</enterprise-beans>

</sun-ejb-jar>

Compile, deploy, and run theapplication as describedin “To Run the Sample Application”on

page 106.

Confguring Message Protection or a Specifc Method Based on DigitalSignatures

To enable message protection or a specic method, or or a set o methods that can beidentied using a wildcard value, ollow these steps. As in the example discussed in“Using aSignature to Enable Message Protection or All Methods” on page 102, to enable message

1

2

3

Chapter 5 • Securing Applications 103

protection or a specic method, update the message-security-binding element or the EJBweb service endpoint in the application’s sun-ejb-jar.xml le. To this le, addrequest-protection and response-protection elements, which are analogous to therequest-policy and response-policy elements discussed in Chapter 10, “ConguringMessage Security,” in Sun GlassFish Communications Server 2.0 Administration Guide.Theadministration guide includes a table listing the set and order o security operations ordiferent request and response policy congurations.

This section uses the sample application discussed in “Understanding and Running the SampleApplication” on page 105 to apply application level message security to show only the

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 104/326

Application on page 105 to apply application-level message security to show only thediferences necessary or protecting web services using various mechanisms.

To Enable Message Protection or a Particular Method or Set o Methods Using Digital Signature

In a texteditor, openthe application’s sun-ejb-jar.xml fle.

For the xms example, this le is located in the directory app-dir /xms-ejb/src/conf, whereapp-dir is dened in “To Set Up the Sample Application” on page 105.

Modiy the sun-ejb-jar.xml fle by addingthe message-security-binding element as

shown:

<sun-ejb-jar>

<enterprise-beans>

<unique-id>1</unique-id>

<ejb>

<ejb-name>HelloWorld</ejb-name>

<jndi-name>HelloWorld</jndi-name>

<webservice-endpoint>

<port-component-name>HelloIF</port-component-name><endpoint-address-uri>service/HelloWorld</endpoint-address-uri>

<message-security-binding auth-layer="SOAP">

<message-security>

<message>

<java-method>

<method-name>ejbCreate</method-name>

</java-method>

</message>

<message>

<java-method>

<method-name>sayHello</method-name>

</java-method>

</message>

<request-protection auth-source="content" />

<response-protection auth-source="content"/>

</message-security>

1

2

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009104

</message-security-binding>

</webservice-endpoint>

</ejb>

</enterprise-beans>

</sun-ejb-jar>

Compile, deploy, and run theapplication as describedin “To Run the Sample Application”on

page 106.

d di d i h l li i

3

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 105/326

Understanding and Running the Sample Application

This section discusses the WSS sample application. This sample application is installed on your

system only i you installed the J2EE 1.4 samples. I you have not installed these samples, see“To Set Up the Sample Application” on page 105.

The objective o this sample application is to demonstrate how a web service can be securedwith WSS. The web service in the xms example is a simple web service implemented using a JavaEE EJB endpoint and a web service endpoint implemented using a servlet. In this example, aservice endpoint interace is dened with one operation, sayHello, which takes a string thensends a response with Hello prexed to the given string. You can view the WSDL le or theservice endpoint interace at app-dir /xms-ejb/src/conf/HelloWorld.wsdl , where app-dir isdened in “To Set Up the Sample Application” on page 105.

In this application, the client looks up the service using the JNDI namejava:comp/env/service/HelloWorld and gets the port inormation using a static stub toinvoke the operation using a given name. For the name Duke, the client gets the response Hello

Duke!

This example shows how to use message security or web services at the Communications

Server level. For inormation about using message security at the application level, see“Application-Specic Message Protection” on page 102. The WSS message security mechanisms implement message-level authentication (or example, XML digital signature andencryption) o SOAP web services invocations using the X.509 and username/password proleso the OASIS WS-Security standard, which can be viewed rom the ollowing URL:http://docs.oasis-open.org/

wss/2004/01/oasis-200401-wss-soap-message-security-1.0.pdf .

This section includes the ollowing topics:■ “To Set Up the Sample Application” on page 105■ “To Run the Sample Application” on page 106

▼ To Set Up the Sample ApplicationTo have access to this sample application, you must have previously installed the J2EE 1.4samples. I the samples are not installed, ollow the steps in the ollowing section.

BeoreYou Begin

Chapter 5 • Securing Applications 105

Ater you ollow these steps, the sample application is located in the directory as-install /j2ee14-samples/samples/webservices/security/ejb/apps/xms/ orinadirectory o your choice. For easy reerence throughout the rest o this section, this directory isreerred to as simply app-dir .

Gotothe J2EE 1.4 downloadURL (http://java.sun.com/j2ee/1.4/download.html ) in your

browser.

Click on theDownload button or theSamples Bundle.

1

2

ConfguringMessage Security orWeb Services

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 106/326

Click on Accept License Agreement.

Click on theJ2EE SDKSamples link.

Choosea location or the j2eesdk-1_4_03-samples.zip fle.

Saving the le to as-install is recommended.

Unzip thefle.

Unzipping to the as-install /j2ee14–samples directory is recommended. For example, you canuse the ollowing command.

unzip j2eesdk-1_4_03-samples.zip -d j2ee14-samples

▼ To Run the Sample Application

Makesure that the Communications Server is running.

Message security providers are set up when the asant targets are run, so you do not need to

congure these on the Communications Server prior to running this example.

I you are not running HTTP onthe deault port o 8080, changetheWSDLfle or the example to

reect thechange, and change the common.properties fleto reect thechange as well.

The WSDL le or this example is located at app-dir /xms-ejb/src/conf/HelloWorld.wsdl .The port number is in the ollowing section:

<service name="HelloWorld">

<port name="HelloIFPort" binding="tns:HelloIFBinding">

<soap:address location="http://localhost:8080/service/HelloWorld"/>

</port>

</service>

Veriy that the properties in the as-install /samples/common.properties le are set properly oryour installation and environment. I you need a more detailed description o this le, reer tothe “Conguration” section or the web services security applications atas-install /j2ee14–samples/samples/webservices/security/docs/common.html#Logging .

3

4

5

6

1

2

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009106

Change to theapp-dir directory.

Run the ollowing asant targets to compile, deploy, and run the exampleapplication:

a. To compile samples:

asant

b. To deploy samples:

asant deploy

3

4

ProgrammaticLogin

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 107/326

c. To run samples:

asant run

I the sample has compiled and deployed properly, you see the ollowing response on yourscreen ater the application has run:

run:[echo] Running the xms program:[exec] Established message level security :

Hello Duke!

To undeploythe sample, run the ollowing asant target:

asant undeploy

All o the web services security examples use the same web service name (HelloWorld)andwebservice ports. These examples show only the diferences necessary or protecting web servicesusing various mechanisms. Make sure to undeploy an application when you have completedrunning it. I you do not, you receive an Already in Use error and deployment ailures whenyou try to deploy another web services example application.

Programmatic LoginProgrammatic login allows a deployed Java EE application or module to invoke a login method.I the login is successul, a SecurityContext is established as i the client had authenticatedusing any o the conventional Java EE mechanisms. Programmatic login is supported or servletand EJB components on the server side, and or stand-alone or application clients on the clientside. Programmatic login is useul or an application having special needs that cannot beaccommodated by any o the Java EE standard authentication mechanisms.

Note – Programmatic login is specic to the Communications Server and not portable to otherapplication servers.

This section contains the ollowing topics:

■ “Programmatic Login Precautions” on page 108

5

Chapter 5 • Securing Applications 107

■ “Granting Programmatic Login Permission” on page 108■ “The ProgrammaticLogin Class” on page 109

Programmatic Login PrecautionsThe Communications Server is not involved in how the login inormation (user, password) isobtained by the deployed application. Programmatic login places the burden on the applicationdeveloper with respect to assuring that the resulting system meets security requirements. I theapplication code reads the authentication inormation across the network, the application

ProgrammaticLogin

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 108/326

determines whether to trust the user.

Programmatic login allows the application developer to bypass the application

server-supported authentication mechanisms and eed authentication data directly to thesecurity service. While exible, this capability should not be used without some understandingo security issues.

Since this mechanism bypasses the container-managed authentication process and sequence,the application developer must be very careul in making sure that authentication is establishedbeore accessing any restricted resources or methods. It is also the application developer’sresponsibility to veriy the status o the login attempt and to alter the behavior o the applicationaccordingly.

The programmatic login state does not necessarily persist in sessions or participate in singlesign-on.

Lazy authentication is not supported or programmatic login. I an access check is reached andthe deployed application has not properly authenticated using the programmatic login method,access is denied immediately and the application might ail i not coded to account or thisoccurrence. One way to account or this occurrence is to catch the access control or security 

exception, perorm a programmatic login, and repeat the request.

Granting Programmatic Login PermissionThe ProgrammaticLoginPermission permission is required to invoke the programmatic loginmechanism or an application i the security manager is enabled. For inormation about thesecurity manager, see “The server.policy File” on page 95. This permission is not granted by deault to deployed applications because this is not a standard Java EE mechanism.

To grant the required permission to the application, add the ollowing to thedomain-dir /config/server.policy le:

grant codeBase "file: jar-fle-path" {

permission com.sun.appserv.security.ProgrammaticLoginPermission

"login";

};

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009108

The jar-fle-path is the path to the application’s JAR le.

The ProgrammaticLogin Class

The com.sun.appserv.security.ProgrammaticLogin class enables a user to perorm loginprogrammatically.

For Javadoc tool pages relevant to programmatic login, go to http://

glassfish.dev.java.net/nonav/javaee5/api/index.html and click on thecom sun appserv security package

ProgrammaticLogin

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 109/326

com.sun.appserv.security package.

The ProgrammaticLogin class has our login methods, two or servlets or JSP les and two orEJB components.

The login methods or servlets or JSP les have the ollowing signatures:

public java.lang.Boolean login(String user, String password,

javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response)

public java.lang.Boolean login(String user, String password,

String realm, javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response, boolean errors)

throws java.lang.Exception

The login methods or EJB components have the ollowing signatures:

public java.lang.Boolean login(String user, String password)

public java.lang.Boolean login(String user, String password,

String realm, boolean errors) throws java.lang.Exception

All o these login methods accomplish the ollowing:

■ Perorm the authentication■ Return true i login succeeded, false i login ailed

The login occurs on the realm specied unless it is null, in which case the domain’s deaultrealm is used. The methods with no realm parameter use the domain’s deault realm.

I the errors agissetto true, any exceptions encountered during the login are propagated tothe caller. I set to false, exceptions are thrown.

On the client side, realm and errors parameters are ignored and the actual login does not occuruntil a resource requiring a login is accessed. A java.rmi.AccessException with COBRA

NO_PERMISSION occurs i the actual login ails.

The logout methods or servlets or JSP les have the ollowing signatures:

Chapter 5 • Securing Applications 109

public java.lang.Boolean logout(HttpServletRequest request,

HttpServletResponse response)

public java.lang.Boolean logout(HttpServletRequest request,

HttpServletResponse response, boolean errors)

throws java.lang.Exception

The logout methods or EJB components have the ollowing signatures:

public java.lang.Boolean logout()

UserAuthentication or Single Sign-on

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 110/326

public java.lang.Boolean logout(boolean errors)

throws java.lang.Exception

All o these logout methods return true i logout succeeded, false i logout ailed.

I the errors agis set to true, any exceptions encountered during the logout are propagated tothe caller. I set to false, exceptions are thrown.

User Authentication or Single Sign-onThe single sign-on eature o the Communications Server allows multiple web (or SIP)applications deployed to the same virtual server to share the user authentication state. Withsingle sign-on enabled, users who log in to one web application become implicitly logged intoother web applications on the same virtual server that require the same authenticationinormation. Otherwise, users would have to log in separately to each web application whoseprotected resources they tried to access.

A sample application using the single sign-on scenario could be a consolidated airline bookingservice that searches all airlines and provides links to diferent airline web sites. Ater the usersigns on to the consolidated booking service, the user inormation can be used by eachindividual airline site without requiring another sign-on.

Single sign-on operates according to the ollowing rules:

■ Single sign-on applies to web applications congured or the same realm and virtual server.The realm is dened by the realm-name element in the web.xml le. For inormation about

 virtual servers, see Chapter 13, “Conguring the HTTP Service,” in Sun GlassFishCommunications Server 2.0 Administration Guide.

■ As long as users access only unprotected resources in any o the web applications on a virtual server, they are not challenged to authenticate themselves.

■ As soon as a user accesses a protected resource in any web application associated with a virtual server, the user is challenged to authenticate himsel or hersel, using the loginmethod dened or the web application currently being accessed.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009110

■ Ater authentication, the roles associated with this user are used or access control decisionsacross all associated web applications, without challenging the user to authenticate to eachapplication individually.

■ When the user logs out o one web application (or example, by invalidating the

corresponding session), the user’s sessions in all web applications are invalidated. Any subsequent attempt to access a protected resource in any application requires the user toauthenticate again.

The single sign-on eature utilizes HTTP cookies to transmit a token that associates eachrequest with the saved user identity, so it can only be used in client environments that support

UserAuthentication or Single Sign-on

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 111/326

cookies.

To congure single sign-on, set the ollowing properties in the virtual-server element o the

domain.xml le:

■ sso-enabled - I false, single sign-on is disabled or this virtual server, and users mustauthenticate separately to every application on the virtual server. The deault is true.

■ sso-max-inactive-seconds - Species the time ater which a user’s single sign-on recordbecomes eligible or purging i no client activity is received. Since single sign-on appliesacross several applications on the same virtual server, access to any o the applications keepsthe single sign-on record active. The deault value is 5 minutes (300 seconds). Higher values

provide longer single sign-on persistence or the users at the expense o more memory useon the server.

■ sso-reap-interval-seconds - Species the interval between purges o expired singlesign-on records. The deault value is 60.

Here is an example conguration with all deault values:

<virtual-server id="server" ... >

...

<property name="sso-enabled" value="true"/>

<property name="sso-max-inactive-seconds" value="300"/>

<property name="sso-reap-interval-seconds" value="60"/>

</virtual-server>

Chapter 5 • Securing Applications 111

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 112/326

112

Developing Web Services

6C H A P T E R 6

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 113/326

This chapter describes Communications Server support or web services. JavaTM API orXML-Based Web Services (JAX-WS) version 2.0 is supported. Java API or XML-Based RemoteProcedure Calls (JAX-RPC) version 1.1 is supported or backward compatibility. This chaptercontains the ollowing sections:

■ “Creating Portable Web Service Artiacts” on page 114■ “Deploying a Web Service” on page 114■ “Web Services Registry” on page 115■ “The Web Service URI, WSDL File, and Test Page” on page 116■ “JBI Runtime” on page 117■ “Using the Woodstox Parser” on page 119

“Part Two: Web Services” in the Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/

tutorial/doc/index.html) shows how to deploy simple web services to the CommunicationsServer. “Chapter 20: Java API or XML Registries” explains how to set up a registry and create

clients that access the registry.

For additional inormation about JAX-WS and web services, seeJava Specication Request(JSR) 224 (http://jcp.org/aboutJava/communityprocess/pfd/jsr224/index.html ) andJSR109(http://jcp.org/en/jsr/detail?id=109 ).

For inormation about web services security, see “Conguring Message Security or WebServices” on page 98.

For inormation about web services administration, monitoring, logging, and registries, seeChapter 16, “Managing Web Services,” in Sun GlassFish Communications Server 2.0

 Administration Guide.

The Fast Inoset standard species a binary ormat based on the XML Inormation Set. Thisormat is an ecient alternative to XML. For inormation about using Fast Inoset, see theollowing links:

113

■ Java Web Services Developer Pack 1.6 Release Notes (http://java.sun.com/

webservices/docs/1.6/ReleaseNotes.html )■ Fast Inoset in Java Web Services Developer Pack, Version 1.6 (http://java.sun.com/

webservices/docs/1.6/jaxrpc/fastinfoset/manual.html )■ Fast Inoset Project (http://fi.dev.java.net)

Creating Portable Web Service Artiacts

For a tutorial that shows how to use the wsimport and wsgen commands see “Part Two: Web

Creating PortableWeb Service Artiacts

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 114/326

For a tutorial that shows how to use the wsimport and wsgen commands, see Part Two: WebServices” in the Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/

index.html). For reerence inormation on these commands, see the Sun GlassFish

Communications Server 2.0 Reerence Manual .

Deploying a Web Service

You deploy a web service endpoint to the Communications Server just as you would any servlet,stateless session bean (SLSB), or application. Ater you deploy the web service, the next step is to

publish it. For more inormation about publishing a web service, see “Web Services Registry” onpage 115.

You can use the autodeployment eature to deploy a simple JSR181(http://jcp.org/en/jsr/

detail?id=181) annotated le. You can compile and deploy in one step, as in the ollowingexample:

javac -cp javaee.jar -d domain-dir /autodeploy MyWSDemo.java

Note – For complex services with dependent classes, user specied WSDL les, or otheradvanced eatures, autodeployment o an annotated le is not sucient.

The Sun-specic deployment descriptor les sun-web.xml and sun-ejb-jar.xml provideoptional web service enhancements in their webservice-endpoint and

webservice-description elements, including a debugging-enabled subelement that enablesthe creation o a test page. The test page eature is enabled by deault and described in“The WebService URI, WSDL File, and Test Page” on page 116.

For more inormation about deployment, autodeployment, and deployment descriptors, seethe Sun GlassFish Communications Server 2.0 Application Deployment Guide. For moreinormation about the asadmin deploy command, see the Sun GlassFish CommunicationsServer 2.0 Reerence Manual .

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009114

Web Services RegistryYou deploy a registry to the Communications Server just as you would any connector module,except that i you are using the Admin Console, you must select a Registry Type value. Aterdeployment, you can congure a registry in one o the ollowing ways:

■ In the Admin Console, open the Web Services component, and select the Registry tab. Fordetails, click the Help button in the Admin Console.

■ To congure a registry using the command line, use the ollowing commands.

■ Set the registry type to com.sun.appserv.registry.ebxml orcom sun appserv registry uddi Use a backslash beore each period as an escape

WebServicesRegistry

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 115/326

com.sun.appserv.registry.uddi . Use a backslash beore each period as an escapecharacter. For example:

asadmin create-resource-adapter-config --user adminuser

--property com\.sun\.appserv\.registry\.ebxml=true MyReg

■ Set any properties needed by the registry. For an ebXML registry, set theLifeCycleManagerURL and QueryManagerURL properties. In the ollowing example, thesystem property REG_URL issettohttp\\:\\/\\/siroe.com\\:6789\\/soar\\/registry\\/soap .

asadmin create-connector-connection-pool --user adminuser --raname MyReg--connectiondefinition javax.xml.registry.ConnectionFactory --property

LifeCycleManagerURL=${REG_URL}:QueryManagerURL=${REG_URL} MyRegCP

■ Set a JNDI name or the registry resource. For example:

asadmin create-connector-resource --user adminuser --poolname MyRegCP jndi-MyReg

For details on these commands, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Ater you deploy a web service, you can publish it to a registry in one o the ollowing ways:

■ In the Admin Console, open the Web Services component, select the web service in thelisting on the General tab, and select the Publish tab. For details, click the Help button in theAdmin Console.

■ Use the asadmin publish-to-registry command. For example:

asadmin publish-to-registry --user adminuser --registryjndinames jndi-MyReg --webservicename my-ws#simple

For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

The Sun Java Enterprise System (Java ES) includes a Sun-specic ebXML registry. For moreinormation about the Java ES registry and registries in general, see “Chapter 20: Java API orXML Registries” in the Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/

doc/index.html).

Chapter 6 • Developing Web Services 115

A connector module that accesses UDDI registries is provided with the CommunicationsServer in the as-install /lib/install/applications/jaxr-ra directory.

You can also use the JWSDP registry available at http://java.sun.com/webservices/jwsdp/

index.jsp or the SOA registry available at http://www.sun.com/products/soa/index.jsp .

The Web Service URI, WSDL File, and Test PageClients can run a deployed web service by accessing its service endpoint address URI, which hasthe ollowing ormat:

TheWeb ServiceURI,WSDLFile, andTestPage

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 116/326

the ollowing ormat:

http://host : port /context-root /servlet-mapping-url-pattern

The context-root is dened in the application.xml or web.xml le, and can be overridden inthe sun-application.xml or sun-web.xml le. The servlet-mapping-url-patternis dened inthe web.xml le.

In the ollowing example, the context-root is my-ws and the servlet-mapping-url-pattern is/simple:

http://localhost:8080/my-ws/simple

You can view the WSDL le o the deployed service in a browser by adding ?WSDL tothe end o the URI. For example:

http://localhost:8080/my-ws/simple?WSDL

For debugging, you can run a test page or the deployed service in a browser by adding?Tester

to the end o the URL. For example:

http://localhost:8080/my-ws/simple?Tester

You can also test a service using the Admin Console. Open the Web Services component, selectthe web service in the listing on the General tab, and select Test. For details, click the Helpbutton in the Admin Console.

Note – The test page works only or WS-I compliant web services. This means that the testerservlet does not work or services with WSDL les that use RPC/encoded binding.

Generation o the test page is enabled by deault. You can disable the test page or a web serviceby setting the value o the debugging-enabled element in the sun-web.xml andsun-ejb-jar.xml deployment descriptor to false. For more inormation, see the SunGlassFish Communications Server 2.0 Application Deployment Guide.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009116

 JBI RuntimeThe Java Business Integration runtime (JBI runtime) provides a distributed inrastructure usedor enterprise integration. It consists o a set o binding components and service engines, whichintegrate various types o inormation technology assets. The binding components and service

engines are interconnected with a normalized message router. Binding components and serviceengines adapt inormation technology assets to a standard services model, based on XMLmessage exchange using standardized message exchange patterns. The JBI runtime providesservices or transorming and routing messages, as well as the ability to centrally administer thedistributed system.

JBI Runtime

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 117/326

This JBI runtime incorporates the JSR208(http://jcp.org/en/jsr/detail?id=208)specication or JBI and other open standards. The JBI runtime allows you to integrate web

services and enterprise applications as loosely coupled composite applications within aService-Oriented Architecture (SOA).

The distribution o the JBI runtime includes a Java EE service engine, an HTTP SOAP bindingcomponent, a WSDL shared library, and Ant tasks described in“JBI Tasks” on page 68. Forinormation about JBI administration in the Communications Server, see theSun GlassFishCommunications Server 2.0 Administration Guide.

Additional components, tools, and documentation are available or download. Reer toProjectOpen ESB (https://open-esb.dev.java.net/) or more inormation on the additionalcomponents, tools, and documentation that are available.

The Java EE Service Engine acts as a bridge between the Java EE and JBI runtime environmentsor web service providers and web service consumers. The Java EE Service Engine providesbetter perormance than a SOAP over HTTP binding component due to in-processcommunication between components and additional protocols provided by JBI bindingcomponents such as JMS, SMTP, and File.

The JSR 208 specication allows transactions to be propagated to other components using amessage exchange property specied in the JTA_TRANSACTION_PROPERTY_NAME eld. The JavaEE Service Engine uses this property to set and get a transaction object rom the JBI messageexchange. It then uses the transaction object to take part in a transaction. This means a Java EEapplication or module can take part in a transaction started by a JBI application. Conversely, aJBI application can take part in a transaction started by a Java EE application or module.

Similarly, the JSR 208 specication allows a security subject to be propagated as a messageexchange property named javax.jbi.security.subject. Thus a security subject can bepropagated rom a Java EE application or module to a JBI application or the reverse.

To deploy a Java EE application or module as a JBI service unit, use the Admin Console or theasadmin deploy-jbi-service-assembly command. For more inormation about the asadmin

deploy-jbi-service-assembly command, see the Sun GlassFish Communications Server 2.0Reerence Manual .

Chapter 6 • Developing Web Services 117

Using the jbi.xml File

Section 6.3.1 o the JSR 208 specication describes the jbi.xml le. This is a deploymentdescriptor, located in theMETA-INF directory. To deploy a Java EE application or module as aJBI service unit, you need only speciy a small subset o elements in the jbi.xml le. Here is anexample provider:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<jbi version="1.0" xmlns="http://java.sun.com/xml/ns/jbi" xmlns:ns0="http://ejbws.jbi.misc/">

<services binding-component="false">

<provides endpoint-name="MiscPort" interface-name="ns0:Misc" service-name="ns0:MiscService"/>

JBI Runtime

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 118/326

</services>

</jbi>

Here is an example consumer:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<jbi version="1.0" xmlns="http://java.sun.com/xml/ns/jbi" xmlns:ns0="http://message.hello.jbi/">

<services binding-component="false">

<consumes endpoint-name="MsgPort" interface-name="ns0:Msg" service-name="ns0:MsgService"/>

</services>

</jbi>

The Java EE Service Engine enables the endpoints described in theprovides section o thejbi.xml le in the JBI runtime. Similarly, the Java EE Service Engine routes invocations o theendpoints described in theconsumes section rom the Java EE web service consumer to the JBIruntime.

Using Application Server DescriptorsTo determine whether a web service endpoint is enabled in the JBI runtime environment, youcanseta jbi-enabled attribute in the Communications Server. This attribute is set to false

(disabled) by deault. To enable an endpoint or JBI, set the attribute to true using the asadmin

set command. For example, i an endpoint is bundled as a WAR le named my-ws.war with anendpoint named simple, use the ollowing command:

asadmin set --user adminuser server.applications.web-module.my-ws.web-service-endpoint.simple.jbi-enabled=true

Determining whether requests rom a web service consumer are routed through the Java EEService Engine is unnecessary and deprecated, but supported or backward compatibility. Youcanseta stub-property named jbi-enabled in the consumer's sun-web.xml orsun-ejb-jar.xml le. This property is set to true (enabled) by deault. Here is an example o the sun-web.xml le:

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009118

<sun-web-app>

<service-ref>

<service-ref-name>sun-web.serviceref/calculator</service-ref-name>

<port-info>

<wsdl-port>

<namespaceURI>http://example.web.service/Calculator</namespaceURI><localpart>CalculatorPort</localpart>

</wsdl-port>

<service-endpoint-interface>service.web.example.calculator.Calculator</service-endpoint-interface>

<stub-property name="jbi-enabled" value="true"/>

</port-info>

</service-ref>

Using theWoodstoxParser

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 119/326

/service ref

</sun-web-app>

For more inormation about the sun-web.xml and sun-ejb-jar.xml deployment descriptorles, see the Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Using theWoodstox Parser

The deault XML parser in the Communications Server is the Sun GlassFish XML Parser(SJSXP). Using the Woodstox parser, which is bundled with the Communications Server, may improve perormance. Woodstox and SJSXP both provide implementations o the StAX API.To enable the Woodstox parser, set the ollowing system properties or the deaultserver-config conguration in the domain.xml le, then restart the server:

<config name=server-config>

...

<system-property name="javax.xml.stream.XMLEventFactory"value="com.ctc.wstx.stax.WstxEventFactory"/>

<system-property name="javax.xml.stream.XMLInputFactory"

value="com.ctc.wstx.stax.WstxInputFactory"/>

<system-property name="javax.xml.stream.XMLOutputFactory"

value="com.ctc.wstx.stax.WstxOutputFactory"/>

</config>

In addition, set these properties or any other congurations reerenced by server instances orclusters on which you want to use the Woodstox parser. For more inormation about thedomain.xml le and system properties, see the Sun GlassFish Communications Server 2.0

 Administration Reerence.

Chapter 6 • Developing Web Services 119

Note – I you are using a stand-alone client, you must set these same properties or the client onthe java command line as ollows:

-Djavax.xml.stream.XMLInputFactory=com.ctc.wstx.stax.WstxInputFactory

-Djavax.xml.stream.XMLOutputFactory=com.ctc.wstx.stax.WstxOutputFactory

-Djavax.xml.stream.XMLEventFactory=com.ctc.wstx.stax.WstxEventFactory

Setting these properties is not necessary i you are using an application client, which isrecommended and supported.

Using theWoodstoxParser

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 120/326

For more inormation about the Woodstox parser, see http://woodstox.codehaus.org/ . Formore inormation about the StAX API, see Chapter 17: Streaming API or XML in the Java EE 5Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/index.html ).

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009120

Using the Java Persistence API

7C H A P T E R 7

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 121/326

Sun GlassFish Communications Server support or the Java Persistence API includes allrequired eatures described in the Java Persistence Specication. Although ocially part o theEnterprise JavaBeans Specication v3.0, also known as JSR 220 (http://jcp.org/en/jsr/

detail?id=220), the Java Persistence API can also be used with non-EJB components outsidethe EJB container.

The Java Persistence API provides an object/relational mapping acility to Java developers or

managing relational data in Java applications. For basic inormation about the Java PersistenceAPI, see “Part Four: Persistence” in the Java EE 5 Tutorial (http://java.sun.com/javaee/5/

docs/tutorial/doc/index.html).

This chapter contains Communications Server specic inormation on using the JavaPersistence API in the ollowing topics:

■ “Speciying the Database” on page 122

■ “Additional Database Properties” on page 124■ “Conguring the Cache” on page 124■ “Setting the Logging Level” on page 124■ “Using Lazy Loading” on page 125■ “Primary Key Generation Deaults” on page 125■ “Automatic Schema Generation” on page 126■ “Query Hints” on page 131■ “Changing the Persistence Provider” on page 132■ “Restrictions and Optimizations” on page 133

Note – The deault persistence provider in the Communications Server is based on Oracle'sTopLink Essentials Java Persistence API implementation. All conguration options in TopLink Essentials are available to applications that use the Communications Server's deault persistenceprovider.

121

Speciying the DatabaseThe Communications Server uses the bundled Java DB (Derby) database by deault. I thetransaction-type element is omitted or specied as JTA and both the jta-data-source andnon-jta-data-source elements are omitted in the persistence.xml le,JavaDBisusedasa

JTA data source. I transaction-type is specied as RESOURCE_LOCAL and bothjta-data-source and non-jta-data-source are omitted, Java DB is used as a non-JTA datasource.

To use a non-deault database, either speciy a value or the jta-data-source element, or setthe transaction-type element to RESOURCE_LOCAL and speciy a value or thenon-jta-data-source element.

Speciying the Database

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 122/326

j

I you are using the deault persistence provider, the provider attempts to automatically detectthe database based on the connection metadata. You can speciy the optionaltoplink.platform.class.name property to guarantee that the database is correct. Forexample:

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence">

<persistence-unit name ="em1">

<jta-data-source>jdbc/MyDB2DB</jta-data-source>

<properties>

<property name="toplink.platform.class.name"value="oracle.toplink.essentials.platform.database.DB2Platform "/>

</properties>

</persistence-unit>

</persistence>

The ollowing toplink.platform.class.name property values are allowed. Supported

platorms have been tested with the Communications Server and are ound to be Java EEcompatible.

//Supported platforms

oracle.toplink.essentials.platform.database.DerbyPlatform

oracle.toplink.essentials.platform.database.oracle.OraclePlatform

oracle.toplink.essentials.platform.database.SQLServerPlatform

oracle.toplink.essentials.platform.database.DB2Platform

oracle.toplink.essentials.platform.database.SybasePlatform

oracle.toplink.essentials.platform.database.CloudscapePlatformoracle.toplink.essentials.platform.database.MySQL4Platform

oracle.toplink.essentials.platform.database.PointBasePlatform

oracle.toplink.essentials.platform.database.PostgreSQLPlatform

//Others available

oracle.toplink.essentials.platform.database.InformixPlatform

oracle.toplink.essentials.platform.database.TimesTenPlatform

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009122

oracle.toplink.essentials.platform.database.AttunityPlatform

oracle.toplink.essentials.platform.database.HSQLPlatform

oracle.toplink.essentials.platform.database.SQLAnyWherePlatform

oracle.toplink.essentials.platform.database.DBasePlatform

oracle.toplink.essentials.platform.database.DB2MainframePlatform

oracle.toplink.essentials.platform.database.AccessPlatform

To use the Java Persistence API outside the EJB container (in Java SE mode), do not speciy thejta-data-source or non-jta-data-source elements i the DataSource is not available.Instead, speciy the provider element and any additional properties required by the JDBCdriver or the database. For example:

<?xml version="1 0" encoding="UTF 8"?>

Speciying the Database

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 123/326

<?xml version= 1.0 encoding= UTF-8 ?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence">

<persistence-unit name ="em2">

<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>

<transaction-type>RESOURCE_LOCAL<transaction-type>

<non-jta-data-source>jdbc/MyDB2DB</non-jta-data-source>

<properties>

<property name="toplink.platform.class.name"

value="oracle.toplink.essentials.platform.database.DB2Platform "/>

<!-- JDBC connection properties -->

<property name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>

<property name="toplink.jdbc.url"

value="jdbc:derby://localhost:1527/testdb;retrieveMessagesFromServerOnGetMessage=true;create=true; "/>

<property name="toplink.jdbc.user" value="APP"/>

<property name="toplink.jdbc.password" value="APP"/>

</properties>

</persistence-unit>

</persistence>

For more inormation about toplink properties, see “Additional Database Properties” onpage 124.

For a list o the JDBC drivers currently supported by the Communications Server, see the SunGlassFish Communications Server 2.0 Release Notes. For congurations o supported and otherdrivers, see “Congurations or Specic JDBC Drivers” in Sun GlassFish CommunicationsServer 2.0 Administration Guide.

To change the persistence provider, see“Changing the Persistence Provider” on page 132.

Chapter 7 • Using the Java Persistence API 123

Additional Database PropertiesI you are using the deault persistence provider, you can speciy in the persistence.xml lethe database properties listed at Persistence Unit Extensions in TopLink JPA ExtensionsReerence (http://www.oracle.com/

technology/products/ias/toplink/jpa/essentials/toplink-jpa-extensions.html ).

For schema generation properties, see “Generation Options” on page 128. For query hints, see“Query Hints” on page 131.

Confguring the Cache

AdditionalDatabase Properties

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 124/326

I you are using the deault persistence provider, you can congure whether caching occurs, thetype o caching, the size o the cache, and whether client sessions share the cache. Cachingproperties or the deault persistence provider are described in detail atExtensions or Caching in TopLink JPA Extensions Reerence (http://www.oracle.com/

technology/products/ias/toplink/jpa/essentials/toplink-jpa-extensions.html ).

Setting the Logging Level

One o the deault persistence provider's database properties that you can set in thepersistence.xml leis toplink.logging.level. For example, setting the logging level toFINE or higher logs all SQL statements. For details about this property, see Extensions or Logging inTopLink JPA Extensions Reerence (http://www.oracle.com/

technology/products/ias/toplink/jpa/essentials/toplink-jpa-extensions.html ).

You can also set the TopLink Essentials logging level globally in the Application Server in any o the ollowing ways:

■ Seta module-log-levels property using the asadmin command. For example:

asadmin set --user adminuser "server.log-service.module-log-levels.property.oracle\.toplink\.essentials "=FINE

■ Set a JVM option using the asadmin command. For example:

asadmin create-jvm-options --user adminuser -Dtoplink.logging.level=FINE

■ Seta module-log-levels property using the Admin Console. In the developer prole, select

the Application Server component and the Logging tab. In the cluster prole, select theLogger Settings component under the relevant conguration. Select the Log Levels tab.Then scroll down to Additional Module Log Level Properties, select Add Property, typeoracle.toplink.essentials in the Name eld, and type the desired logging level in theValue eld.

Setting the logging level to OFF disables TopLink Essentials logging. A logging level set in thepersistence.xml le takes precedence over the global logging level.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009124

You can set the logging level or Java Persistence in general using the Admin Console. In thedeveloper prole, select the Application Server component and the Logging tab. In the clusterprole, select the Logger Settings component under the relevant conguration. Select the LogLevels tab. Then set the logging level or Persistence. Setting the logging level to OFF disablesJava Persistence logging.

Using Lazy LoadingThe deault persistence provider treats only OneToOne, ManyToOne, OneToMany, and ManyToMany

mappings specially when they are annotated as LAZY. OneToMany and ManyToMany mappings areloaded lazily by deault in compliance with the Java Persistence Specication. Other mappings

Primary Key GenerationDeaults

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 125/326

loaded lazily by deault in compliance with the Java Persistence Specication. Other mappingsare always loaded eagerly. For OneToOne and ManyToOne mappings, value holder indirection isused. For OneToMany and ManyToMany mappings, transparent indirection is used.

For basic inormation about lazy loading, seeLazy Loading in TopLink JPA ExtensionsReerence (http://www.oracle.com/

technology/products/ias/toplink/jpa/essentials/toplink-jpa-extensions.html ). Fordetails about indirection, see Indirection in Mapping Concepts (http://www.oracle.com/

technology/products/ias/toplink/doc/10131/main/_html/mapun002.htm ).

Primary Key Generation DeaultsIn the descriptions o the @GeneratedValue, @SequenceGenerator,and @TableGenerator

annotations in the Java Persistence Specication, certain deaults are noted as specic to thepersistence provider. The deault persistence provider's primary key generation deaults arelisted here.

@GeneratedValue deaults are as ollows:

■ Using strategy=AUTO (or no strategy) creates a @TableGenerator named SEQ_GEN withdeault settings. Speciying a generator has no efect.

■ Using strategy=TABLE without speciying a generator creates a @TableGenerator namedSEQ_GEN_TABLE with deault settings. Speciying a generator but no @TableGenerator

creates and names a @TableGenerator with deault settings.

Using strategy=IDENTITY or strategy=SEQUENCE produces the same results, which aredatabase-specic.

■ For Oracle databases, not speciying a generator creates a @SequenceGenerator namedSEQ_GEN_SEQUENCE with deault settings. Speciying a generator but no@SequenceGenerator creates and names a @SequenceGenerator with deault settings.

■ For PostgreSQL databases, a SERIAL column named entity-table_ pk-column_SEQ iscreated.

Chapter 7 • Using the Java Persistence API 125

■ For MySQL databases, an AUTO_INCREMENT column is created.

■ For other supported databases, an IDENTITY column is created.

The @SequenceGenerator annotation has one deault specic to the deault provider. Thedeault sequenceName is the specied name.

@TableGenerator deaults are as ollows:

■ The deault table is SEQUENCE.

■ The deault pkColumnName is SEQ_NAME.

■ The deault valueColumnName is SEQ_COUNT.

■ The deault pkColumnValue is the specied name, or the deault name ino name is specied.

Automatic Schema Generation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 126/326

p p , p

Automatic Schema GenerationThe automatic schema generation eature o the Communications Server denes databasetables based on the elds or properties in entities and the relationships between the elds orproperties. This insulates developers rom many o the database related aspects o development,allowing them to ocus on entity development. The resulting schema is usable as-is or can begiven to a database administrator or tuning with respect to perormance, security, and so on.

This section covers the ollowing topics:■ “Annotations” on page 126■ “Supported Data Types” on page 127■ “Generation Options” on page 128

Note – Automatic schema generation is supported on an all-or-none basis: it expects that notables exist in the database beore it is executed. It is not intended to be used as a tool to generate

extra tables or constraints.

Deployment won't ail i all tables are not created, and undeployment won't ail i not all tablesare dropped. Instead, an error is written to the server log. This is done to allow you toinvestigate the problem and x it manually. You should not rely on the partially createddatabase schema to be correct or running the application.

AnnotationsThe ollowing annotations are used in automatic schema generation: @AssociationOverride,@AssociationOverrides, @AttributeOverride, @AttributeOverrides, @Column,@DiscriminatorColumn, @DiscriminatorValue, @Embedded, @EmbeddedId, @GeneratedValue,@Id, @IdClass, @JoinColumn, @JoinColumns, @JoinTable, @Lob, @ManyToMany, @ManyToOne,@OneToMany, @OneToOne, @PrimaryKeyJoinColumn, @PrimaryKeyJoinColumns,

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009126

@SecondaryTable, @SecondaryTables, @SequenceGenerator, @Table, @TableGenerator,@UniqueConstraint,and @Version. For inormation about these annotations, see the JavaPersistence Specication.

For @Column annotations, the insertable and updatable elements are not used in automatic

schema generation.

For @OneToMany and @ManyToOne annotations, no ForeignKeyConstraint is created in theresulting DDL les.

Supported Data Types

Automatic Schema Generation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 127/326

Supported Data Types

The ollowing table shows mappings o Java types to SQL types when the deault persistenceprovider and automatic schema generation are used.

TABLE 7–1 Java Type to SQLType Mappings

JavaTypeJavaDB, Derby,CloudScape Oracle DB2 Sybase MS-SQL Server MySQL Server

boolean, java.lang.Boolean SMALLINT NUMBER(1) SMALLINT BIT BIT TINYINT(1)

int, java.lang.Integer INTEGER NUMBER(10) INTEGER INTEGER INTEGER INTEGER

long, java.lang.Long BIGINT NUMBER(19) INTEGER NUMERIC(19) NUMERIC(19) BIGINT

float, java.lang.Float FLOAT NUMBER(19,4) FLOAT FLOAT(16) FLOAT(16) FLOAT

double, java.lang.Double FLOAT NUMBER(19,4) FLOAT FLOAT(32) FLOAT(32) DOUBLE

short, java.lang.Short SMALLINT NUMBER(5) SMALLINT SMALLINT SMALLINT SMALLINT

byte, java.lang.Byte SMALLINT NUMBER(3) SMALLINT SMALLINT SMALLINT SMALLINT

java.lang.Number DECIMAL NUMBER(38) DECIMAL(15) N UMERIC(38) N UMERIC(28) D ECIMAL(38)

java.math.BigInteger BIGINT NUMBER(38) BIGINT NUMERIC(38) NUMERIC(28) BIGINT

java.ma th.Big Decimal DE CIMAL NUMB ER(38) D ECIMAL (15) NUME RIC(38 ) NUMERIC (28) DEC IMAL(38 )

java.lang.String VARCHAR(255) VARCHAR(255) VARCHAR(255) VARCHAR(255) VARCHAR(255) VARCHAR(255)

char, java.lang.Character CHAR(1) CHAR(1) CHAR(1) CHAR(1) CHAR(1) CHAR(1)

byte[], java.lang.Byte[],java.sql.Blob

BLOB(64000) LONG RAW BLOB(64000) IMAGE IMAGE BLOB(64000)

char[],java.lang.Character[],java.sql.Clob

CLOB(64000) LONG CLOB(64000) TEXT TEXT TEXT(64000)

Chapter 7 • Using the Java Persistence API 127

TABLE 7–1 Java Type to SQLType Mappings (Continued)

JavaTypeJavaDB, Derby,CloudScape Oracle DB2 Sybase MS-SQL Server MySQL Server

java.sql.Date DATE DATE DATE DATETIME DATETIME DATE

java.sql.Time TIME DATE TIME DATETIME DATETIME TIME

java.sql.Timestamp TIMESTAMP DATE TIMESTAMP DATETIME DATETIME DATETIME

Generation Options

Schema generation properties or asadmin command line options can control automatic schema

Automatic Schema Generation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 128/326

Schema generation properties or asadmin command line options can control automatic schema

generation by the ollowing:■ Creating tables during deployment■ Dropping tables during undeployment■ Dropping and creating tables during redeployment■ Generating the DDL les

Note – Beore using these options, make sure you have a properly congured database. See

“Speciying the Database” on page 122.

The ollowing optional schema generation properties control the automatic creation o database tables at deployment. You can speciy them in the persistence.xml le.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009128

TABLE 7–2 Schema Generation Properties

Property Deault Description

toplink.ddl-generation none Species whether tables and DDL les are created during deployment,and whether tables are droppedrst i they already exist. Allowed

 values are create-tables, drop-and-create-tables,and none.I create-tables is specied, database tables are created or entitiesthat need them.

I drop-and-create-tables is specied, and i tables wereautomatically created when this application was last deployed, tablesrom the earlierdeployment are dropped and resh onesare created. I tableswere not automatically created when this application was lastdeployed no attempt is made to drop any tables I tables with the

Automatic Schema Generation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 129/326

deployed, no attempt is made to drop any tables. I tables with the

same names as those that would have beenautomatically created areound, the deployment proceeds, but a warning is thrown to indicatethat tables could not be created.

I none is specied, no tables are created or dropped.

The asadmin generation options listed in Table 7–3 and Table 7–4override the value o this property.

I you are using persistence outside the EJB container and would liketo create the DDL les without creating tables, additionally dene aJava system property INTERACT_WITH_DB and setits value to false.

toplink.create-ddl-jdbc-file-name createDDL.jdbc Species the name o the JDBC le that contains the DDL statementsrequired to create the required objects (tables, sequences, andconstraints) in the database.

toplink.drop-ddl-jdbc-file-name dropDDL.jdbc Species the name o the JDBC le that contains the DDL statementsrequired to drop the required objects (tables, sequences, andconstraints) rom the database.

toplink.application-location . or the currentworking directory 

Species the location where the DDL les are written.

For persistence within the EJB container, i this property is not set,DDL les are written to one o the ollowing locations, or applicationsand modules, respectively:

domain-dir /generated/ejb/j2ee-apps/app-name

domain-dir /generated/ejb/j2ee-modules/mod-name

Chapter 7 • Using the Java Persistence API 129

TABLE 7–2 SchemaGeneration Properties (Continued)

Property Deault Description

toplink.ddl-generation.

output-mode

both Species the DDL generation target i you are in Java SE mode, outsidethe EJB container. Values are as ollows:■ both – Generates SQL les and executes them on the database. I 

toplink.ddl-generation issetto create-tables, thentoplink.create-ddl-jdbc-file-name is written to

toplink.application-location and executed on the database. I 

toplink.ddl-generation issetto drop-and-create-tables,

then both toplink.create-ddl-jdbc-file-name and

toplink.drop-ddl-jdbc-file-name are written to

toplink.application-location and both SQL les are executed

on the database

Automatic Schema Generation

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 130/326

on the database.

■ database – Executes SQL on the database only (does not generate

SQL les). I toplink.ddl-generation issetto create-tables,

then toplink.create-ddl-jdbc-file-name is executed on the

database. It is not written to toplink.application-location . I 

toplink.ddl-generation issetto drop-and-create-tables,

then both toplink.create-ddl-jdbc-file-name and

toplink.drop-ddl-jdbc-file-name are executed on the

database. Neither is written totoplink.application-location

.■ sql-script – Generates SQL les only (does not execute them on

the database). I toplink.ddl-generation issetto

create-tables, then toplink.create-ddl-jdbc-file-name is

written to toplink.application-location. It isnot executedon

the database. I toplink.ddl-generation issetto

drop-and-create-tables, then both

toplink.create-ddl-jdbc-file-name and

toplink.drop-ddl-jdbc-file-name are written totoplink.application-location. Neither is executed on the

database.

The ollowing options o the asadmin deploy or asadmin deploydir command control theautomatic creation o database tables at deployment.

TABLE 7–3 The asadmin deploy and asadmin deploydir Generation Options

Option Deault Description

--createtables none I  true, causes database tables to be created or entities that need them. I false,does not create tables.I not specied, the value o the toplink.ddl-generation

property in persistence.xml is used.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009130

TABLE 7–3 The asadmin deploy and asadmin deploydir Generation Options (Continued)

Option Deault Description

--dropandcreatetables none I  true, and i tables were automatically created when this application was lastdeployed, tables rom the earlierdeployment are dropped and resh onesarecreated.

I true, and i tables were not automatically created when this application was lastdeployed, no attempt is made to drop any tables. I tables with the same names asthose that would have beenautomatically created are ound, the deploymentproceeds, but a warning is thrown to indicate that tables could not be created.

I false,the toplink.ddl-generation property setting in persistence.xml isoverridden.

Query Hints

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 131/326

The ollowing options o the asadmin undeploy command control the automatic removal o database tables at undeployment.

TABLE 7–4 The asadmin undeploy Generation Options

Option Deault Description

--droptables none I  true, causes database tables that were automatically created when the entities were lastdeployed to be droppedwhen the entities are undeployed. I false, does not drop tables.

I not specied, tables are droppedonlyi the toplink.ddl-generation property setting inpersistence.xml is drop-and-create-tables.

For more inormation about the asadmin deploy, asadmin deploydir, and asadmin undeploy

commands, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

When asadmin deployment options and persistence.xml options are both specied, the

asadmin deployment options take precedence.

The asant tasks sun-appserv-deploy and sun-appserv-undeploy are equivalent to asadmin

deploy and asadmin undeploy, respectively. These asant tasks also override thepersistence.xml options. For details, see Chapter 3, “The asant Utility.”

Query HintsQuery hints are additional, implementation-specic conguration settings. You can use hintsin your queries in the ollowing ormat:

setHint("hint-name", hint-value)

For example:

Chapter 7 • Using the Java Persistence API 131

Customer customer = (Customer)entityMgr.

createNamedQuery("findCustomerBySSN").

setParameter("SSN", "123-12-1234").

setHint("toplink.refresh", true).

getSingleResult();

For more inormation about the query hints available with the deault provider, seeQuery Hints

in TopLink JPA Extensions Reerence (http://www.oracle.com/

technology/products/ias/toplink/jpa/essentials/toplink-jpa-extensions.html ).

Changing the Persistence Provider

Changing the Persistence Provider

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 132/326

Note – The previous sections in this chapter apply only to the deault persistence provider. I youchange the provider or a module or application, the provider-specic database properties,query hints, and schema generation eatures described in this chapter do not apply.

The verifier utility always uses the deault provider to veriy persistence settings. Forinormation about the verifier utility, see “The verier Utility” in Sun GlassFish

Communications Server 2.0 Application Deployment Guide.

You can change the persistence provider or an application in the manner described in the JavaPersistence API Specication.

First, install the provider. Copy the provider JAR les to the domain-dir /lib directory, andrestart the Communications Server. For more inormation about the domain-dir /lib directory,

see “Using the Common Class Loader” on page 40. The new persistence provider is now available to all modules and applications deployed on servers that share the same conguration.However, the deault provider remains the same.

In your persistence unit, speciy the provider and any properties the provider requires in thepersistence.xml le. For example:

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence">

<persistence-unit name ="em3">

<provider>com.company22.persistence.PersistenceProviderImpl</provider>

<properties>

<property name="company22.database.name" value="MyDB"/>

</properties>

</persistence-unit>

</persistence>

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009132

Restrictions and OptimizationsThis section discusses restrictions and perormance optimizations that afect using the JavaPersistence API.

■ “Extended Persistence Context Failover” on page 133■ “Using @OrderBy with a Shared Session Cache” on page 133■ “Using BLOB or CLOB Types with the Inet Oraxo JDBC Driver” on page 134■ “Database Case Sensitivity” on page 134■ “Sybase Finder Limitation” on page 135■ “MySQL Database Restrictions” on page 135

Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 133/326

Extended Persistence Context FailoverA reerence to an extended persistence context in a stateul session bean or an HttpSession

may not ail over successully.

The Java Persistence API specication is not clear how the container and persistence providershould work together to passivate a stateul session bean with an extended persistence contextin a stand-alone server instance. This also prevents successul serialization and storage o areerence to an extended persistence context in an HttpSession.

Even in a single-instance environment, i a stateul session bean is passivated, its extendedpersistence context could be lost when the stateul session bean is activated. In thisenvironment, it is sae to store an extended persistence context in a stateul session bean only i you can saely disable stateul session bean passivation altogether. This is possible, buttrade-ofs in memory utilization must be careully examined beore choosing this option.

In a single-instance environment, it is sae to store a reerence to an extended persistence

context in an HttpSession.

Using @OrderBy with a Shared Session Cache

Setting @OrderBy on a ManyToMany or OneToMany relationship eld in which a List representsthe Many side doesn't work i the session cache is shared. Use one o the ollowingworkarounds:

■ Have the application maintain the order so the List is cached properly.

■ Reresh the session cache using EntityManager.refresh() i you don't want to maintainthe order during creation or modication o theList.

■ Disable session cache sharing in persistence.xml as ollows:

<property name="toplink.cache.shared.default" value="false"/>

Chapter 7 • Using the Java Persistence API 133

Using BLOB or CLOBTypes with the Inet Oraxo JDBCDriver

To use BLOB or CLOB data types larger than 4 KB or persistence using the Inet Oraxo JDBCDriver or Oracle Databases, you must set the database's streamstolob property value to true.

Database Case Sensitivity

Mapping reerences to column or table names must be in accordance with the expected columnor table name case, and ensuring this is the programmer's responsibility. I column or tablenames are not explicitly specied or a eld or entity, the Communications Server uses uppercase column names by deault so any mapping reerences to the column or table names must be

Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 134/326

case column names by deault, so any mapping reerences to the column or table names must bein upper case. I column or table names are explicitly specied, the case o all mappingreerences to the column or table names must be in accordance with the case used in thespecied names.

The ollowing are examples o how case sensitivity afects mapping elements that reer tocolumns or tables. Programmers must keep case sensitivity in mind when writing thesemappings.

Unique Constraints

I column names are not explicitly specied on a eld, unique constraints and oreign key mappings must be specied using uppercase reerences. For example:

@Table(name="Department", uniqueConstraints={ @UniqueConstraint ( columnNames= { "DEPTNAME" } ) } )

The other way to handle this is by speciying explicit column names or each eld with the

required case. For example:

@Table(name="Department", uniqueConstraints={ @UniqueConstraint ( columnNames= { "deptName" } ) } )

public class Department{ @Column(name="deptName") private String deptName; }

Otherwise, the ALTER TABLE statement generated by the Communications Server uses theincorrect case, and the creation o the unique constraint ails.

Foreign Key MappingUse @OneToMany(mappedBy="COMPANY") or speciy an explicit column name or the Company

eld on the Many side o the relationship.

SQL Result Set Mapping

Use the ollowing elements:

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009134

<sql-result-set-mapping name="SRSMName" >

<entity-result entity-class="entities.someEntity" />

<column-result name="UPPERCASECOLUMNNAME" />

</sql-result-set-mapping>

Or speciy an explicit column name or the upperCaseColumnName eld.

Named Native Queries and JDBC Queries

Column or table names specied in SQL queries must be in accordance with the expected case.For example, MySQL requires column names in the SELECT clause o JDBC queries to beuppercase, while PostgreSQL and Sybase require table names to be uppercase in all JDBCqueries.

Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 135/326

PostgreSQL Case Sensitivity

PostgreSQL stores column and table names in lower case. JDBC queries on PostgreSQL retrievecolumn or table names in lowercase unless the names are quoted. For example:

use aliases Select m.ID AS \"ID\" from Department m

Use the backslash as an escape character in the class le, but not in the persistence.xml le.

Sybase Finder Limitation

I a nder method with an input greater than 255 characters is executed and the primary key column is mapped to a VARCHAR column, Sybase attempts to convert type VARCHAR to typeTEXT and generates the ollowing error:

com.sybase.jdbc2.jdbc.SybSQLException: Implicit conversion from datatype

’TEXT’ to ’VARCHAR’ is not allowed. Use the CONVERT function to run this

query.

To avoid this error, make sure the nder method input is less than 255 characters.

MySQL Database Restrictions

The ollowing restrictions apply when you use a MySQL database with the CommunicationsServer or persistence.

■ MySQL treats int1 and int2 as reserved words. I you want to dene int1 and int2 as eldsin your table, use ‘int1‘ and ‘int2‘ eld names in your SQL le.

■ When VARCHAR elds get truncated, a warning is displayed instead o an error. To get anerror message, start the MySQL database in strict SQL mode.

Chapter 7 • Using the Java Persistence API 135

■ The order o elds in a oreign key index must match the order in the explicitly createdindex on the primary table.

■ The CREATE TABLE syntax in the SQL le must end with the ollowing line.

) Engine=InnoDB;

InnoDB provides MySQL with a transaction-sae (ACID compliant) storage engine havingcommit, rollback, and crash recovery capabilities.

■ Fora FLOAT type eld, the correct precision must be dened. By deault, MySQL uses ourbytes to store a FLOAT type that does not have an explicit precision denition. For example,this causes a number such as 12345.67890123 to be rounded of to 12345.7 during anINSERT. To prevent this, speciy FLOAT(10,2) in the DDL le, which orces the database touse an eight-byte double-precision column. For more inormation, see

Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 136/326

http://dev.mysql.com/doc/mysql/en/numeric-types.html .■ To use || as the string concatenation symbol, start the MySQL server with the

--sql-mode="PIPES_AS_CONCAT" option. For more inormation, seehttp://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html andhttp://dev.mysql.com/doc/mysql/en/ansi-mode.html .

■ MySQL always starts a new connection when autoCommit==true is set. This ensures thateach SQL statement orms a single transaction on its own. I you try to rollback or commit

an SQL statement, you get an error message.

javax.transaction.SystemException: java.sql.SQLException:

Can’t call rollback when autocommit=true

javax.transaction.SystemException: java.sql.SQLException:

Error open transaction is not closed

To resolve this issue, add relaxAutoCommit=true to the JDBC URL. For more inormation,

see http://forums.mysql.com/read.php?39,31326,31404 .■ MySQL does not allow a DELETE on a row that contains a reerence to itsel. Here is an

example that illustrates the issue.

create table EMPLOYEE (

empId int NOT NULL,

salary float(25,2) NULL,

mgrId int NULL,

PRIMARY KEY (empId),FOREIGN KEY (mgrId) REFERENCES EMPLOYEE (empId)

) ENGINE=InnoDB;

insert into Employee values (1, 1234.34, 1);

delete from Employee where empId = 1;

This example ails with the ollowing error message.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009136

ERROR 1217 (23000): Cannot delete or update a parent row:

a foreign key constraint fails

To resolve this issue, change the table creation script to the ollowing:

create table EMPLOYEE (

empId int NOT NULL,

salary float(25,2) NULL,

mgrId int NULL,

PRIMARY KEY (empId),

FOREIGN KEY (mgrId) REFERENCES EMPLOYEE (empId)

ON DELETE SET NULL

) ENGINE=InnoDB;

insert into Employee values (1, 1234.34, 1);

Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 137/326

p y

delete from Employee where empId = 1;

This can be done only i the oreign key eld is allowed to be null. For more inormation, seehttp://bugs.mysql.com/bug.php?id=12449 and http://dev.mysql.com/doc/mysql/

en/innodb-foreign-key-constraints.html .

Chapter 7 • Using the Java Persistence API 137

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 138/326

138

Developing Web and SIP Applications

8C H A P T E R 8

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 139/326

This chapter describes how web and SIP applications are supported in the Sun GlassFishCommunications Server and includes the ollowing sections:

■ “Using Servlets” on page 139■ “Using JavaServer Pages” on page 146■ “Creating and Managing Sessions” on page 151■ “Advanced Web Application Features” on page 159

For general inormation about web applications, see “Part One: The Web Tier” in the Java EE 5Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/index.html ).

For general inormation about SIP applications, see Java Specication Request (JSR) 289(http://www.jcp.org/en/jsr/detail?id=289 ).

A module with both web application and SIP application eatures is a converged web/SIPmodule.

You can optionally use a sun-web.xml or sun-sip.xml le, or both, to speciy extra deploymentsettings. I you use both, the sun-web.xml le congures the web container and thesun-sip.xml le congures the SIP container. The sun-sip.xml leisasubsetothesun-web.xml le. For more inormation, see the Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Using ServletsCommunications Server supports the Java Servlet Specication version 2.5.

Note – Servlet API version 2.5 is ully backward compatible with versions 2.3 and 2.4, so allexisting servlets should work without modication or recompilation.

139

To develop servlets, use Sun Microsystems’ Java Servlet API. For inormation about using theJava Servlet API, see the documentation provided by Sun Microsystems athttp://java.sun.com/products/servlet/index.html .

The Communications Server provides the wscompile and wsdeploy tools to help you

implement a web service endpoint as a servlet. For more inormation about these tools, see theSun GlassFish Communications Server 2.0 Reerence Manual .

This section describes how to create efective servlets to control application interactionsrunning on an Communications Server, including standard-based servlets. In addition, thissection describes the Communications Server eatures to use to augment the standards.

This section contains the ollowing topics:

■ “Invoking a Servlet With a URL” on page 140

Using Servlets

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 140/326

Invoking a Servlet With a URL on page 140■ “Servlet Output” on page 141■ “Caching Servlet Results” on page 141■ “About the Servlet Engine” on page 145

Invoking a Servlet With a URL

You can call a servlet deployed to the Communications Server by using a URL in a browser orembedded as a link in an HTML or JSP le. The ormat o a servlet invocation URL is as ollows:

http://server : port /context-root /servlet-mapping ?name=value

The ollowing table describes each URL section.

TABLE 8–1 URLFields or Servlets Within an Application

URL element Description

server : port  The IP address (or host name) and optional port number.

To access the deault web or converged web/SIP module or a virtual server, speciy only this URL section. You do not need to speciy the context-root or servlet-name

unless you also wish to speciy name-value parameters.

context-root  For an application, the context root is dened in the context-root element o theapplication.xml, sun-application.xml, or sun-web.xml le. For an individually deployed web or converged web/SIP module, the context root is specied duringdeployment.

For both applications and individually deployed web or converged web/SIP modules,the deault context root is the name o the WAR or SAR le minus the .war or .sar

sux.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009140

TABLE 8–1 URLFields or Servlets Within an Application (Continued)

URL element Description

servlet-mapping  The servlet-mapping as congured in the web.xml or sip.xml le.

?name=value... Optional request parameters.

In this example, localhost is the host name, MortPages is the context root, and calcMortgage

is the servlet mapping:

http://localhost:8080/MortPages/calcMortgage?rate=8.0&per=360&bal=180000

When invoking a servlet rom within a JSP le, you can use a relative path. For example:

<jsp:forward page="TestServlet"/>

Using Servlets

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 141/326

jsp:forward page TestServlet /

<jsp:include page="TestServlet"/>

Servlet Output

ServletContext.log messages are sent to the server log.

By deault, the System.out and System.err output o servlets are sent to the server log, andduring startup, server log messages are echoed to the System.err output. Also by deault, thereis no Windows-only console or the System.err output.

You can change these deaults using the Admin Console. In the developer prole, select theCommunications Server component and the Logging tab. In the cluster prole, select theLogger Settings component under the relevant conguration. Then check or uncheck Write to

System Log. I this box is checked, System.out output is sent to the server log. I it is unchecked,System.out output is sent to the system deault location only.

For more inormation, click the Help button in the Admin Console rom the Logging page.

Caching Servlet Results

The Communications Server can cache the results o invoking a servlet, a JSP, or any URLpattern to make subsequent invocations o the same servlet, JSP, or URL pattern aster. TheCommunications Server caches the request results or a specic amount o time. In this way, i another data call occurs, the Communications Server can return the cached data instead o perorming the operation again. For example, i your servlet returns a stock quote that updatesevery 5 minutes, you set the cache to expire ater 300 seconds.

Chapter 8 • Developing Web and SIP Applications 141

Note – Caching does not apply to SIP servlets.

Whether to cache results and how to cache them depends on the data involved. For example, itmakes no sense to cache the results o a quiz submission, because the input to the servlet isdiferent each time. However, it makes sense to cache a high level report showing demographicdata taken rom quiz results that is updated once an hour.

To dene how an Communications Server web application handles response caching, you editspecic elds in the sun-web.xml le.

Note – A servlet that uses caching is not portable.

Using Servlets

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 142/326

For Javadoc tool pages relevant to caching servlet results, go to http://

glassfish.dev.java.net/nonav/javaee5/api/index.html and click on thecom.sun.appserv.web.cache package.

For inormation about JSP caching, see “JSP Caching” on page 147.

The rest o this section covers the ollowing topics:

■ “Caching Features” on page 142■ “Deault Cache Conguration” on page 143■ “Caching Example” on page 143■ “The CacheKeyGenerator Interace” on page 144

Caching Features

The Communications Server has the ollowing web application response caching capabilities:

■ Caching is congurable based on the servlet name or the URI.

■ When caching is based on the URI, this includes user specied parameters in the query string. For example, a response rom /garden/catalog?category=roses is diferent rom aresponse rom /garden/catalog?category=lilies . These responses are stored underdiferent keys in the cache.

■ Cache size, entry timeout, and other caching behaviors are congurable.

Entry timeout is measured rom the time an entry is created or rereshed. To override thistimeout or an individual cache mapping, speciy the cache-mapping subelement timeout.

■ To determine caching criteria programmatically, write a class that implements thecom.sun.appserv.web.cache.CacheHelper interace. For example, i only a servlet knowswhen a back end data source was last modied, you can write a helper class to retrieve thelast modied timestamp rom the data source and decide whether to cache the responsebased on that timestamp.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009142

■ To determine cache key generation programmatically, write a class that implements thecom.sun.appserv.web.cache.CacheKeyGenerator interace. See “TheCacheKeyGenerator Interace” on page 144.

■ All non-ASCII request parameter values specied in cache key elements must be URLencoded. The caching subsystem attempts to match the raw parameter values in the request

query string.■ Since newly updated classes impact what gets cached, the web container clears the cache

during dynamic deployment or reloading o classes.

■ The ollowing HttpServletRequest request attributes are exposed.

■ com.sun.appserv.web.cachedServletName , the cached servlet target■ com.sun.appserv.web.cachedURLPattern , the URL pattern being cached

■ Results produced by resources that are the target o a RequestDispatcher.include() orRequestDispatcher.forward() call are cached i caching has been enabled or those

Using Servlets

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 143/326

gresources. For details, see “cache-mapping” in Sun GlassFish Communications Server 2.0 Application Deployment Guide and “dispatcher” in Sun GlassFish CommunicationsServer 2.0 Application Deployment Guide. These are elements in the sun-web.xml le.

Deault Cache Confguration

I you enable caching but do not provide any special conguration or a servlet or JSP, the

deault cache conguration is as ollows:■ The deault cache timeout is 30 seconds.

■ Only the HTTP GET method is eligible or caching.

■ HTTP requests with cookies or sessions automatically disable caching.

■ No special consideration is given to Pragma:, Cache-control:, or Vary: headers.

■ The deault key consists o the Servlet Path (minus pathInfo and the query string).

■ A “least recently used” list is maintained to evict cache entries i the maximum cache size isexceeded.

■ Key generation concatenates the servlet path with key eld values, i any are specied.

■ Results produced by resources that are the target o a RequestDispatcher.include() orRequestDispatcher.forward() call are never cached.

Caching Example

Here is an example cache element in the sun-web.xml le:

<cache max-capacity="8192" timeout="60">

<cache-helper name="myHelper" class-name="MyCacheHelper"/>

<cache-mapping>

<servlet-name>myservlet</servlet-name>

<timeout name="timefield">120</timeout>

Chapter 8 • Developing Web and SIP Applications 143

<http-method>GET</http-method>

<http-method>POST</http-method>

</cache-mapping>

<cache-mapping>

<url-pattern> /catalog/* </url-pattern>

<!-- cache the best selling category; cache the responses to

-- this resource only when the given parameters exist. Cache

-- only when the catalog parameter has ’lilies’ or ’roses’

-- but no other catalog varieties:

-- /orchard/catalog?best&category=’lilies’

-- /orchard/catalog?best&category=’roses’

-- but not the result of

-- /orchard/catalog?best&category=’wild’

-->

<constraint-field name=’best’ scope=’request.parameter’/><constraint-field name=’category’ scope=’request parameter’>

Using Servlets

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 144/326

<constraint-field name= category scope= request.parameter >

<value> roses </value>

<value> lilies </value>

</constraint-field>

<!-- Specify that a particular field is of given range but the

-- field doesn’t need to be present in all the requests -->

<constraint-field name=’SKUnum’ scope=’request.parameter’>

<value match-expr=’in-range’> 1000 - 2000 </value>

</constraint-field>

<!-- cache when the category matches with any value other than

-- a specific value -->

<constraint-field name="category" scope="request.parameter>

<value match-expr="equals" cache-on-match-failure="true">

bogus

</value>

</constraint-field>

</cache-mapping><cache-mapping>

<servlet-name> InfoServlet </servlet-name>

<cache-helper-ref>myHelper</cache-helper-ref>

</cache-mapping>

</cache>

For more inormation about the sun-web.xml caching settings, see “cache” in Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

The CacheKeyGenerator Interace

The built-in deault CacheHelper implementation allows web applications to customize the key generation. An application component (in a servlet or JSP) can set up a customCacheKeyGenerator implementation as an attribute in the ServletContext.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009144

The name o the context attribute is congurable as the value o thecacheKeyGeneratorAttrName property in the default-helper element o the sun-web.xml

deployment descriptor. For more inormation, see “deault-helper” in Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

About the Servlet Engine

Servlets exist in and are managed by the servlet engine in the Communications Server. Theservlet engine is an internal object that handles all servlet meta unctions. These unctionsinclude instantiation, initialization, destruction, access rom other components, andconguration management. This section covers the ollowing topics:

“Instantiating and Removing Servlets” on page 145■ “Request Handling” on page 145

Using Servlets

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 145/326

Request Handling on page 145

Instantiating and Removing Servlets

Ater the servlet engine instantiates the servlet, the servlet engine calls the servlet’s init()

method to perorm any necessary initialization. You can override this method to perorm aninitialization unction or the servlet’s lie, such as initializing a counter.

When a servlet is removed rom service, the servlet engine calls the destroy() method in theservlet so that the servlet can perorm any nal tasks and deallocate resources. You can overridethis method to write log messages or clean up any lingering connections that won’t be caught ingarbage collection.

Request Handling

When a request is made, the Communications Server hands the incoming data to the servletengine. The servlet engine processes the request’s input data, such as orm data, cookies, sessioninormation, and URL name-value pairs, into an HttpServletRequest or SipServletRequest

request object type.

The servlet engine also creates an HttpServletResponse or SipServletResponse responseobject type. The engine then passes both as parameters to the servlet’s service() method.

In an HTTP servlet, the deault service() method routes requests to another method based onthe HTTP transer method: POST, GET, DELETE, HEAD, OPTIONS, PUT, or TRACE. For example,HTTP POST requests are sent to the doPost() method, HTTP GET requests are sent to thedoGet() method, and so on. This enables the servlet to process request data diferently,depending on which transer method is used. Since the routing takes place in the servicemethod, you generally do not override service() in an HTTP servlet. Instead, overridedoGet(), doPost(), and so on, depending on the request type you expect.

Chapter 8 • Developing Web and SIP Applications 145

To perorm the tasks to answer a request, override the service() method or generic servlets,and the doGet() or doPost() methods or HTTP servlets. Very oten, this means accessing EJBcomponents to perorm business transactions, then collating the inormation in the requestobject or in a JDBC ResultSet object.

The service() method o javax.servlet.sip.SipServlet takes both a SipServletRequest

anda SipServletResponse argument, but or every invocation o this method, only oneargument is valid (diferent rom null), depending on whether the incoming SIP message is arequest or a response. I the incoming SIP message is a request, only the SipServletRequest

argument is valid, and the SipServletResponse argument is null. I the incoming SIP messageis a response, only the SipServletResponse argument is valid, and the SipServletRequest

argument is null.

The deault implementation o the service() method o javax.servlet.sip.SipServlet

dispatches SIP requests to the appropriate doXXX() method (based on the SIP request method),and SIP responses to the appropriate doXXXResponse() method (based on the SIP response

Using JavaServer Pages

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 146/326

and SIP responses to the appropriate doXXXResponse() method (based on the SIP responsestatus code). The doXXX() methods take a single argument o type SipServletRequest, whilethe doXXXResponse() methods take a single argument o type SipServletResponse. Forexample, a SIP invite request is dispatched to the doInvite() method, and a SIP response witha status code in the range between 200 and 300 is dispatched to the doSuccessResponse()

method.

In the same way that web developers typically override the various doXXX() methods o HttpServlet, and do not modiy the deault implementation o its service() method (whichcontains the dispatch logic to the appropriate doXXX() method), SIP developers typically override only the doXXX() and doXXXResponse() methods o SipServlet.

Using JavaServer Pages

The Communications Server supports the ollowing JSP eatures:■ JavaServer Pages (JSP) Specication version 2.1■ Precompilation o JSP les, which is especially useul or production servers■ JSP tag libraries and standard portable tags

For inormation about creating JSP les, see Sun Microsystem’s JavaServer Pages web site athttp://java.sun.com/products/jsp/index.html .

For inormation about Java Beans, see Sun Microsystem’s JavaBeans web page athttp://java.sun.com/beans/index.html .

This section describes how to use JavaServer Pages (JSP les) as page templates in anCommunications Server web application. This section contains the ollowing topics:

■ “JSP Tag Libraries and Standard Portable Tags” on page 147■ “JSP Caching” on page 147

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009146

■ “Options or Compiling JSP Files” on page 151

 JSP Tag Libraries and Standard Portable Tags

Communications Server supports tag libraries and standard portable tags. For moreinormation, see the JavaServer Pages Standard Tag Library (JSTL) page athttp://java.sun.com/products/jsp/jstl/index.jsp .

Web applications don’t need to bundle copies o thejsf-impl.jar or appserv-jstl.jar JSPtag libraries (in as-install /lib) to use JavaServerTM Faces technology or JSTL, respectively. Thesetag libraries are automatically available to all web applications.

However, the as-install /lib/appserv-tags.jar tag library or JSP caching is not automatically available to web applications. See “JSP Caching” on page 147, next.

Using JavaServer Pages

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 147/326

 JSP Caching

JSP caching lets you cache tag invocation results within the Java engine. Each can be cachedusing diferent cache criteria. For example, suppose you have invocations to view stock quotes,

weather inormation, and so on. The stock quote result can be cached or 10 minutes, theweather report result or 30 minutes, and so on. JSP caching is described in the ollowing topics:

■ “The appserv-tags.jar File” on page 147■ “Caching Scope” on page 148■ “The cache Tag” on page 149■ “The flush Tag” on page 150

For more inormation about response caching as it pertains to servlets, see “Caching Servlet

Results” on page 141.

The appserv-tags.jar File

JSP caching is implemented by a tag library packaged into theas-install /lib/appserv-tags.jar le, which you can copy into the WEB-INF/lib directory o your web application. The appserv-tags.tld tag library descriptor le is in the META-INF

directory o this JAR le.

Note – Web applications that use this tag library without bundling it are not portable.

To allow all web applications to share this tag library, change the ollowing elements in thedomain.xml le. Change this:

Chapter 8 • Developing Web and SIP Applications 147

<jvm-options>

-Dcom.sun.enterprise.taglibs=appserv-jstl.jar,jsf-impl.jar

</jvm-options>

to this:

<jvm-options>-Dcom.sun.enterprise.taglibs=appserv-jstl.jar,jsf-impl.jar,appserv-tags.jar

</jvm-options>

and this:

<jvm-options>

-Dcom.sun.enterprise.taglisteners=jsf-impl.jar

</jvm-options>

to this:

Using JavaServer Pages

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 148/326

<jvm-options>

-Dcom.sun.enterprise.taglisteners=jsf-impl.jar,appserv-tags.jar

</jvm-options>

For more inormation about the domain.xml le, see the Sun GlassFish CommunicationsServer 2.0 Administration Reerence.

Reer to these tags in JSP les as ollows:

<%@ taglib prefix=" prefx " uri="Sun ONE Application Server Tags" %>

Subsequently, the cache tags are available as < prefx :cache> and < prefx :flush>. For example,i your prefx is mypfx, the cache tags are available as <mypfx:cache> and <mypfx:flush>.

Caching ScopeJSP caching is available in three diferent scopes: request, session,and application.Thedeault is application.Touseacachein request scope, a web application must speciy thecom.sun.appserv.web.taglibs.cache.CacheRequestListener inits web.xml deploymentdescriptor, as ollows:

<listener>

<listener-class>

com.sun.appserv.web.taglibs.cache.CacheRequestListener

</listener-class>

</listener>

Likewise, or a web application to utilize a cache in session scope, it must speciy thecom.sun.appserv.web.taglibs.cache.CacheSessionListener in its web.xml deploymentdescriptor, as ollows:

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009148

<listener>

<listener-class>

com.sun.appserv.web.taglibs.cache.CacheSessionListener

</listener-class>

</listener>

To utilize a cache in application scope, a web application need not speciy any listener. Thecom.sun.appserv.web.taglibs.cache.CacheContextListener is already specied in theappserv-tags.tld le.

The cache Tag

The cache tag caches the body between the beginning and ending tags according to theattributes specied. The rst time the tag is encountered, the body content is executed and

cached. Each subsequent time it is run, the cached content is checked to see i it needs to berereshed and i so, it is executed again, and the cached data is rereshed. Otherwise, the cached

Using JavaServer Pages

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 149/326

rereshed and i so, it is executed again, and the cached data is rereshed. Otherwise, the cacheddata is served.

Attributes o cache

The ollowing table describes attributes or the cache tag.

TABLE 8–2 The cache Attributes

Attribute Deault Description

key ServletPath_Sux  (optional) The name used by the container to access the cached entry. Thecache key is suxed to the servlet path to generate a key to access thecached entry. I no key is specied, a number is generated according to theposition o the tag in the page.

timeo ut 60s (optional) The time in seconds ater which the body o the tag is executedand the cache is rereshed. By deault, this value is interpreted in seconds.To speciy a diferent unit o time, add a sux to the timeout value asollows: s or seconds, m or minutes, h or hours, d or days. Forexample,2h species two hours.

nocache false (optional) I set to true, the body content is executed and served as i therewere no cache tag. This ofers a way to programmatically decide whetherthe cached response is sent or whether the body has to be executed, though

the response is not cached.refresh false (optional) I set to true, the body content is executed and the response is

cached again. This lets you programmaticallyreresh the cacheimmediately regardless o the timeout setting.

scope applic ation (optional) The scope o the cache. Can be request, session, orapplication.See “Caching Scope” on page 148.

Chapter 8 • Developing Web and SIP Applications 149

Example o cache

The ollowing example represents a cached JSP le:

<%@ taglib prefix="mypfx" uri="Sun ONE Application Server Tags" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<mypfx:cache key="${sessionScope.loginId}"nocache="${param.nocache}"

refresh="${param.refresh}"

timeout="10m">

<c:choose>

<c:when test="${param.page == ’frontPage’}">

<%-- get headlines from database --%>

</c:when>

<c:otherwise>...

Using JavaServer Pages

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 150/326

</c:otherwise>

</c:choose>

</mypfx:cache>

<mypfx:cache timeout="1h">

<h2> Local News </h2>

<%-- get the headline news and cache them --%>

</mypfx:cache>

The flush Tag

Forces the cache to be ushed. I a key is specied, only the entry with that key is ushed. I nokey is specied, the entire cache is ushed.

Attributes o flush

The ollowing table describes attributes or the flush tag.

TABLE 8–3 The flush Attributes

Attribute Deault Description

key ServletPath_Sux  (optional) The name used by the container to access the cached entry. The

cache key is suxed to the servlet path to generate a key to access thecached entry. I no key is specied, a number is generated according to theposition o the tag in the page.

s cope ap plicati on (optional) The scope o the cache. Can be request, session, orapplication.See “Caching Scope” on page 148.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009150

Examples o flush

To ush the entry with key="foobar":

<mypfx:flush key="foobar"/>

To ush the entire cache:

<c:if test="${empty sessionScope.clearCache}">

<mypfx:flush />

</c:if>

Options or Compiling JSP Files

Communications Server provides the ollowing ways o compiling JSP 2.1 compliant sourceles into servlets:

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 151/326

les into servlets:

■ JSP les are automatically compiled at runtime.

■ The asadmin deploy command has a precompilejsp option. For details, see the SunGlassFish Communications Server 2.0 Reerence Manual .

■ The sun-appserv-jspc Ant task allows you to precompile JSP les; see “The

sun-appserv-jspc Task” on page 58.■ The jspc command line tool allows you to precompile JSP les at the command line. For

details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Creating and Managing SessionsThis chapter describes how to create and manage HTTP or SIP sessions that allows users and

transaction inormation to persist between interactions.

This chapter contains the ollowing sections:

■ “Conguring Sessions” on page 151■ “Session Managers” on page 154

Confguring SessionsThis section covers the ollowing topics:

■ “HTTP Sessions, Cookies, and URL Rewriting” on page 152■ “Coordinating Session Access” on page 152■ “SIP Session Limitation” on page 152■ “Distributed Sessions and Persistence” on page 153

Chapter 8 • Developing Web and SIP Applications 151

HTTP Sessions, Cookies, and URL Rewriting

To congure whether and how HTTP sessions use cookies and URL rewriting, edit thesession-properties and cookie-properties elements in the sun-web.xml le or anindividual web application. For more about the properties you can congure, see“session-properties” in Sun GlassFish Communications Server 2.0 Application Deployment 

Guide and “cookie-properties” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide.

For inormation about conguring deault session properties or the entire web container, seeChapter 8, “SIP, Web, and EJB Containers,” in Sun GlassFish Communications Server 2.0

 Administration Guide and the Sun GlassFish Communications Server 2.0 High Availability 

 Administration Guide.

Coordinating Session Access

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 152/326

g

Make sure that multiple threads don’t simultaneously modiy the same session object inconicting ways.

This is especially likely to occur in SIP applications where multiple SIP sessions share a SIPapplication session, and in converged applications where requests or the same session occur

through HTTP and SIP protocols. It is likely to occur in pure web applications that use HTMLrames where multiple servlets are executing simultaneously on behal o the same client. Agood solution is to ensure that one o the servlets modies the session and the others haveread-only access.

SIP Session Limitation

The ollowing JSR 289 API methods are not ully supported in a clustered environment:

javax.servlet.sip.SipSessionsUtil.getApplicationSessionById(String applicationSessionId)

javax.servlet.sip.SipSessionsUtil.getApplicationSessionByKey(String applicationSessionKey,

boolean create)

I the session is not located in the server instance where the method is executed, these methodsreturn a null result.

I a SIP application session contains application data that must be accessed rom anywhere inthe cluster, the application should store that data in a database, using the SIP application ID asthe key. This makes the data easily accessible rom JMS handlers, EJB components, or similarentities whose distribution in the cluster is not correlated with the distribution o SIPapplication sessions.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009152

Distributed Sessions and Persistence

Note – Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see“Usage Proles” in

Sun GlassFish Communications Server 2.0 Administration Guide.

A distributed HTTP or SIP session can run in multiple Communications Server instances,provided the ollowing criteria are met:

■ Each server instance has the same distributable web, SIP, or converged web/SIP applicationdeployed to it. The web-app element o the web.xml or sip.xmldeployment descriptor lemust have the distributable subelement specied. For a converged web/SIP application to

be treated as distributable, both itsweb.xml and sip.xml deployment descriptor les musthave the distributable subelement specied.

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 153/326

■ The web, SIP, or converged web/SIP application uses high-availability session persistence. I a non-distributable web, SIP, or converged web/SIP application is congured to usehigh-availability session persistence, a warning is written to the server log, and the sessionpersistence type reverts to memory.See “The replicated Persistence Type” on page 157.

■ I a converged web/SIP application uses high-availability session persistence or its SIP

sessions, but not its HTTP sessions, or the reverse, a warning is logged, and the persistencetype o both the application's SIP and HTTP sessions reverts to memory.

■ All objects bound into a distributed session must be o the types listed inTable 8–4.

■ The web, SIP, or converged web/SIP application must be deployed using thedeploy ordeploydir command with the --availabilityenabled option set to true.Seethe SunGlassFish Communications Server 2.0 Reerence Manual .

Note – Contrary to the Servlet 2.5 specication, Communications Server does not throw anIllegalArgumentException i an object type not supported or ailover is bound into adistributed session.

Keep the distributed session size as small as possible. Session size has a direct impact on overallsystem throughput.

In the event o an instance or hardware ailure, another server instance can take over adistributed session, with the ollowing limitations:

■ I a distributable web, SIP, or converged web/SIP application reerences a Java EEcomponent or resource, the reerence might be lost. See Table 8–4 or a list o the types o reerences that HTTPSession or SipApplicationSessionailover supports.

■ Reerences to open les or network connections are lost.

Chapter 8 • Developing Web and SIP Applications 153

■ Session replication occurs asynchronously, so a small number o sessions may be lost onailure because their state has not propagated to the other instances in the cluster.

For inormation about how to work around these limitations, see the Sun GlassFishCommunications Server 2.0 Deployment Planning Guide.

In the ollowing table, No indicates that ailover or the object type might not work in all casesand that no ailover support is provided. However, ailover might work in some cases or thatobject type. For example, ailover might work because the class implementing that type isserializable.

For more inormation about the InitialContext,see “Accessing the Naming Context” onpage 277. For more inormation about transaction recovery, see Chapter 16, “Using theTransaction Service.” For more inormation about Administered Objects, see“CreatingPhysical Destinations” on page 289.

TABLE 8–4 Object Types Supported or Java EE Web or SIPApplication Session State Failover

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 154/326

Java Object Type Failover Support

Colocated or distributed stateless session, stateulsession, or entity bean reerence

Yes

JNDI context Yes, InitialContext and java:comp/env

UserTransaction Yes, but i the instance that ails is never restarted, any  prepared global transactions are lost and might not becorrectly rolled back or committed.

JDBC DataSource No

Java Message Service (JMS) ConnectionFactory,Destination

No

JavaMail Session No

Connection Factory No

Administered Object No

Web service reerence No

Serializable Java types Yes

Extended persistence context No

Session ManagersA session manager automatically creates new session objects whenever a new session starts. Insome circumstances, clients do not join the session, or example, i the session manager usescookies and the client does not accept cookies.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009154

Communications Server ofers these session management options, determined by thesession-manager element’s persistence-type attribute in the sun-web.xml orsun-sip.xmlle:

■ “The memory Persistence Type” on page 155, the deault

■ “The file Persistence Type” on page 156, which uses a le to store session data, supported

only or pure web applications■ “The replicated Persistence Type” on page 157, which uses other servers in the cluster or

session persistence

Note – I the session manager conguration contains an error, the error is written to the serverlog and the deault (memory) conguration is used.

For more inormation, see “session-manager” in Sun GlassFish Communications Server 2.0Application Deployment Guide

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 155/326

 Application Deployment Guide.

The memory Persistence Type

This persistence type is not designed or a production environment that requires sessionpersistence. It provides no session persistence. However, or web applications only, you can

congure it so that the session state in memory is written to the le system prior to servershutdown.

To speciy the memory persistence type or the entire web container, use theconfigure-ha-persistence command. For details, see theSun GlassFish CommunicationsServer 2.0 Reerence Manual .

To speciy the memory persistence type or a specic web or SIP application, edit thesun-web.xml

orsun-sip.xml

le as in the ollowing example. Thepersistence-type

property is optional, but must be set to memory i included. This overrides the web container availability settings or the web application.

<sun-web-app>

...

<session-config>

<session-manager persistence-type="memory" />

<manager-properties>

<property name="sessionFilename" value="sessionstate" />

</manager-properties>

</session-manager>

...

</session-config>

...

</sun-web-app>

Chapter 8 • Developing Web and SIP Applications 155

The only manager property that the memory persistence type supports is sessionFilename, whichis listed under “manager-properties” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide. This property does not apply to SIP applications.

For more inormation about the sun-web.xml or sun-sip.xml le, see Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

The file Persistence Type

This persistence type provides session persistence to the local le system, and allows a singleserver domain to recover the session state ater a ailure and restart. The session state ispersisted in the background, and the rate at which this occurs is congurable. The store alsoprovides passivation and activation o the session state to help control the amount o memory used. This option is not supported in a production environment. However, it is useul or adevelopment system with a single server instance. This persistence type does not apply to SIPapplications.

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 156/326

Note – Make sure the delete option is set in the server.policy le, or expired le-basedsessions might not be deleted properly. For more inormation about server.policy, see “Theserver.policy File” on page 95.

To speciy the file persistence type or the entire web container, use theconfigure-ha-persistence command. For details, see theSun GlassFish CommunicationsServer 2.0 Reerence Manual .

To speciy the file persistence type or a specic web application, edit the sun-web.xml le asin the ollowing example. Note that persistence-type must be set to file. This overrides theweb container availability settings or the web application.

<sun-web-app>

...<session-config>

<session-manager persistence-type="file">

<store-properties>

<property name="directory" value="sessiondir" />

</store-properties>

</session-manager>

...

</session-config>

...

</sun-web-app>

The file persistence type supports all the manager properties listed under“manager-properties” in Sun GlassFish Communications Server 2.0 Application Deployment Guide except sessionFilename, and supports the directory store property listed under“store-properties” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009156

For more inormation about the sun-web.xml le, see Sun GlassFish Communications Server 2.0 Application Deployment Guide.

The replicated Persistence Type

The replicated persistence type uses other servers in the cluster or session persistence.

Clustered server instances replicate session state in a predictive manner so that the state is savedwhere it is most likely to be needed. Each backup instance stores the replicated data in memory.This allows sessions to be distributed. For details, see“Distributed Sessions and Persistence” onpage 153. In addition, you can congure the requency and scope o session persistence. Theother servers are also used as the passivation and activation store. Use this option in aproduction environment that requires session persistence.

Note – Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see“Usage Proles” inS Gl Fi h C i i S 2 0 Ad i i i G id

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 157/326

Sun GlassFish Communications Server 2.0 Administration Guide.

To use the replicated persistence type, you must rst enable availability. Select the Availability Service component under the relevant conguration in the Admin Console. Check theAvailability Service box. To enable availability or the web container, select the Web Container

Availability tab, then check the Availability Service box. To enable availability or the SIPcontainer, select the SIP Container Availability tab, then check the Availability Service box. Allinstances in a Communications Server cluster should have the same availability settings toensure consistent behavior. For details, see the Sun GlassFish Communications Server 2.0 High Availability Administration Guide.

To change settings such as persistence requency and persistence scope or the entire webcontainer, use the Persistence Frequency and Persistence Scope drop-down lists on the Web

Container Availability tab in the Admin Console, or use the asadmin set command. Forexample:

asadmin set

server-config.availability-service.web-container-availability.persistence-frequency=time-based

For more inormation, see the description o the asadmin set command in the Sun GlassFishCommunications Server 2.0 Reerence Manual .

To speciy the replicated persistence type or a specic web application, edit the sun-web.xmlle as in the ollowing example. Note that persistence-type must be set to replicated. Thisoverrides the web container availability settings or the web application.

<sun-web-app>

...

<session-config>

Chapter 8 • Developing Web and SIP Applications 157

<session-manager persistence-type="replicated">

<manager-properties>

<property name="persistenceFrequency" value="web-method" />

</manager-properties>

<store-properties>

<property name="persistenceScope" value="session" />

</store-properties></session-manager>

...

</session-config>

...

</sun-web-app>

To speciy the replicated persistence type or a specic SIP application, edit the sun-sip.xml

le as in the ollowing example. Note that persistence-type must be set to replicated and

that persistenceFrequency and persistenceScope are not used.

<sun-sip-app>

Creating and Managing Sessions

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 158/326

p pp

...

<session-config>

<session-manager persistence-type="replicated"/>

...

</session-config>

...</sun-sip-app>

For a converged web/SIP application, you must edit both thesun-web.xml le and thesun-sip.xml le. A converged web/SIP application has two session managers. The HTTPsession manager is congured by sun-web.xml. The SIP session manager is congured by sun-sip.xml.

For web container session persistence only, the replicated persistence type supports all the

manager properties listed under “manager-properties” in Sun GlassFish CommunicationsServer 2.0 Application Deployment Guide except sessionFilename, and supports thepersistenceScope store property listed under “store-properties” in Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

For more inormation about the sun-web.xml or sun-sip.xml le, see Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009158

Advanced Web Application Features

This section includes summaries o the ollowing topics:

■ “Internationalization Issues” on page 159■ “Virtual Servers” on page 160■ “Deault Web Modules” on page 161■ “Class Loader Delegation” on page 162■ “Using the default-web.xml File” on page 162■ “Conguring Logging and Monitoring in the Web Container” on page 163■ “Conguring Idempotent URL Requests” on page 163■ “Header Management” on page 164■ “Conguring Valves and Catalina Listeners” on page 164■

“Alternate Document Roots” on page 165■ “Redirecting URLs” on page 167■ “Enabling Comet Support” on page 167■ “U i t t l Fil ” 167

AdvancedWeb ApplicationFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 159/326

■ Using a context.xml File on page 167■ “Enabling WebDav” on page 168■ “Using mod_jk” on page 169■ “Advanced JVM Options or SIP Requests” on page 171

Internationalization Issues

This section covers internationalization as it applies to the ollowing:

■ “The Server's Deault Locale” on page 159■ “Servlet Character Encoding” on page 159

The Server's Deault Locale

To set the deault locale o the entire Communications Server, which determines the locale o the Admin Console, the logs, and so on, use the Admin Console. In the developer prole, selectthe Communications Server component, the Advanced tab, and the Domain Attributes tab. Inthe cluster prole, select the domain component. Then type a value in the Locale eld. Fordetails, click the Help button in the Admin Console.

Servlet Character Encoding

This section explains how the Communications Server determines the character encoding orthe servlet request and the servlet response. For encodings you can use, seehttp://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html .

Chapter 8 • Developing Web and SIP Applications 159

Servlet Request

When processing a servlet request, the server uses the ollowing order o precedence, rst tolast, to determine the request character encoding:

■ The getCharacterEncoding() method

■ A hidden eld in the orm, specied by the form-hint-field attribute o theparameter-encoding element in the sun-web.xml le

■ The default-charset attribute o the parameter-encoding element in the sun-web.xml

le

■ The deault, which is ISO-8859-1

For details about the parameter-encoding element, see “parameter-encoding” in Sun GlassFish

Communications Server 2.0 Application Deployment Guide.

Servlet Response

AdvancedWeb Application Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 160/326

Servlet Response

When processing a servlet response, the server uses the ollowing order o precedence, rst tolast, to determine the response character encoding:

■ The setCharacterEncoding() or setContentType() method■ The setLocale() method■ The deault, which is ISO-8859-1

Virtual Servers

A virtual server, also called a virtual host, is a virtual web server that serves content targeted or

a specic URL. Multiple virtual servers can serve content using the same or diferent hostnames, port numbers, or IP addresses. The HTTP service directs incoming web requests todiferent virtual servers based on the URL.

When you rst install the Communications Server, a deault virtual server is created. You canalso assign a deault virtual server to each new HTTP listener you create.

Web applications and Java EE applications containing web components (web modules) can be

assigned to virtual servers during deployment. A web module can be assigned to more than one virtual server, and a virtual server can have more than one web module assigned to it.

For more inormation about virtual servers, see “virtual-server” in Sun GlassFish

Communications Server 2.0 Administration Reerence.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009160

▼ To Assign a Deault Virtual Server

In the Admin Console, openthe HTTP Service component under the relevant confguration.

Open the HTTP Listenerscomponent under the HTTP Service component.

Selector create a new HTTP listener.

Select romthe DeaultVirtual Server drop-down list.

For more inormation, see “Deault Web Modules” on page 161.

For details, click the Help button in the Admin Console rom the HTTP Listeners page.

▼ To AssignVirtual Servers

1

2

3

4

SeeAlso

AdvancedWeb ApplicationFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 161/326

Deploy theapplication or web moduleand assign thedesired virtual servers to it.

For more inormation, see Sun GlassFish Communications Server 2.0 Application Deployment 

Guide.

In the Admin Console, openthe HTTP Service component under the relevant confguration.

Open theVirtual Servers component under the HTTP Service component.

Selectthe virtual server to which you want to assign a deault web module.

Select the application or web modulerom the Deault Web Moduledrop-down list.

For more inormation, see “Deault Web Modules” on page 161.

For details, click the Help button in the Admin Console rom the Virtual Servers page.

Deault Web Modules

A deault web module can be assigned to the deault virtual server and to each new virtualserver. For details, see “Virtual Servers” on page 160. To access the deault web module or a

 virtual server, point the browser to the URL or the virtual server, but do not supply a contextroot. For example:

http://myvserver:3184/

1

2

3

4

5

SeeAlso

Chapter 8 • Developing Web and SIP Applications 161

A virtual server with no deault web module assigned serves HTML or JavaServer PagesTM

(JSPTM) content rom its document root, which is usually domain-dir /docroot. To access thisHTML or JSP content, point your browser to the URL or the virtual server, do not supply acontext root, but speciy the target le.

For example:

http://myvserver:3184/hellothere.jsp

Class Loader Delegation

The Servlet specication recommends that the Web class loader look in the local class loaderbeore delegating to its parent. To make the Web class loader ollow the delegation model in the

Servlet specication, set delegate="false" in the class-loader element o the sun-web.xml orsun-sip.xml le. It’s sae to do this only or a web or SIP module that does not interact with any other modules.

AdvancedWeb Application Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 162/326

The deault value is delegate="true", which causes the Web class loader to delegate in the samemanner as the other class loaders. Use delegate="true" or a web application that accesses EJBcomponents or that acts as a web service client or endpoint. For details about sun-web.xmlorsun-sip.xml ,see Sun GlassFish Communications Server 2.0 Application Deployment Guide.

For general inormation about class loaders, see Chapter 2, “Class Loaders.”

Using the default-web.xml File

You can use the default-web.xml le to dene eatures such as lters and security constraintsthat apply to all web applications.

For example, you can disable directory listings or added security. In your domain'sdefault-web.xml le, search or the denition o the servlet whose servlet-name is equal todefault, and set the value o the init-param named listings to false. Then redeploy yourweb application i it has already been deployed.

<init-param>

<param-name>listings</param-name>

<param-value>false</param-value></init-param>

The mime-mapping elements in default-web.xml are global and inherited by all webapplications. You can override these mappings or dene your own using mime-mapping

elements in your web application's web.xml le. For more inormation about mime-mapping

elements, see the Servlet specication.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009162

You can use the Admin Console to edit the default-web.xml le. For details, click the Helpbutton in the Admin Console. As an alternative, you can edit the le directly using the ollowingsteps.

▼ To Use the default-web.xml File

Place theJAR fle or theflter, security constraint, or other eaturein thedomain-dir /lib

directory.

Edit thedomain-dir /config/default-web.xml fle toreerto the JAR fle.

Restart the server.

Confguring Logging and Monitoring in the WebContainer

1

2

3

AdvancedWeb ApplicationFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 163/326

For inormation about conguring logging and monitoring in the web container using theAdmin Console, click the Help button in the Admin Console. In the developer prole, Loggingand Monitor tabs are accessible rom the Application Server page. In the Cluster prole, selectLogger Settings under the relevant conguration, or select the Stand-Alone Instances

component, select the instance rom the table, and select the Monitor tab.

Confguring Idempotent URL RequestsAn idempotent request is one that does not cause any change or inconsistency in an applicationwhen retried. To enhance the availability o your applications deployed on an CommunicationsServer cluster, congure the load balancer to retry ailed idempotent HTTP requests on all theCommunications Server instances in a cluster. This option can be used or read-only requests,or example, to retry a search request.

This section describes the ollowing topics:

■ “Speciying an Idempotent URL” on page 163■ “Characteristics o an Idempotent URL” on page 164

Speciying an Idempotent URL

To congure idempotent URL response, speciy the URLs that can be saely retried inidempotent-url-pattern elements in the sun-web.xml le. For example:

<idempotent-url-pattern url-pattern="sun_java/*" no-of-retries="10"/>

For details, see “idempotent-url-pattern” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Chapter 8 • Developing Web and SIP Applications 163

I none o the server instances can successully serve the request, an error page is returned.

Characteristics o an Idempotent URL

Since all requests or a given session are sent to the same application server instance, and i thatCommunications Server instance is unreachable, the load balancer returns an error message.

Normally, the request is not retried on another Communications Server instance. However, i the URL pattern matches that specied in the sun-web.xml le, the request is implicitly retriedon another Communications Server instance in the cluster.

In HTTP, some methods (such as GET) are idempotent, while other methods (such as POST)are not. In efect, retrying an idempotent URL should not cause values to change on the serveror in the database. The only diference should be a change in the response received by the user.

Examples o idempotent requests include search engine queries and database queries. The

underlying principle is that the retry does not cause an update or modication o data.

A search engine, or example, sends HTTP requests with the same URL pattern to the loadbalancer. Speciying the URL pattern o the search request to the load balancer ensures that

AdvancedWeb Application Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 164/326

HTTP requests with the specied URL pattern are implicitly retried on anotherCommunications Server instance.

For example, i the request URL sent to the Communications Server is o the type/search/something .html, then the URL pattern can be specied as /search/*.

Examples o non-idempotent requests include banking transactions and online shopping. I you retry such requests, money might be transerred twice rom your account.

Header ManagementIn all Editions o the Communications Server, the Enumeration rom request.getHeaders()

contains multiple elements (one element per request header) instead o a single, aggregated value.

The header names used in HttpServletResponse.add XXX Header() andHttpServletResponse.set XXX Header() are returned as they were created.

Confguring Valves and Catalina Listeners

You can congure custom valves and Catalina listeners or web modules or virtual servers by dening properties. In the domain.xml le, valve and listener properties look like this:

<web-module ...>

<property name="valve_1" value="org.glassfish.extension.Valve"/>

<property name="listener_1" value="org.glassfish.extension.MyLifecycleListener"/>

</web-module>

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009164

You can dene these properties in one o the ollowing ways, then restart the server:

■ You can dene properties using the asadmin set command. For example:

asadmin set domain1.applications.web-module.MyWebMod.property.valve_1="org.glassfish.extension.Valve"

asadmin set config1.http-service.virtual-server.MyVS.property.valve_1="org.glassfish.extension.Valve"

■ You can dene virtual server properties using the Admin Console. Select the HTTP Servicecomponent under the relevant conguration, select Virtual Servers, and select the desired

 virtual server. Select Add Property, enter the property name and value, check the enable box,and select Save. For details, click the Help button in the Admin Console.

Alternate Document Roots

An alternate document root (docroot) allows a web application to serve requests or certainresources rom outside its own docroot, based on whether those requests match one (or more)o the URI patterns o the web application's alternate docroots.

AdvancedWeb ApplicationFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 165/326

To speciy an alternate docroot or a web application or a virtual server, use thealternatedocroot_n property, where n is a positive integer that allows specication o morethan one. This property can be a subelement o a sun-web-app element in the sun-web.xml leor a virtual-server element in the domain.xml le. For more inormation about these

elements, see “sun-web-app” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide and “virtual-server” in Sun GlassFish Communications Server 2.0 Administration Reerence.

A virtual server's alternate docroots are considered only i a request does not map to any o theweb modules deployed on that virtual server. A web module's alternate docroots are consideredonly once a request has been mapped to that web module.

I a request matches an alternate docroot's URI pattern, it is mapped to the alternate docroot by appending the request URI (minus the web application's context root) to the alternate docroot'sphysical location (directory). I a request matches multiple URI patterns, the alternate docrootis determined according to the ollowing precedence order:

■ Exact match■ Longest path match■ Extension match

For example, the ollowing properties speciy three docroots. The URI pattern o the rstalternate docroot uses an exact match, whereas the URI patterns o the second and thirdalternate docroots use extension and longest path prex matches, respectively.

<property name="alternatedocroot_1" value="from=/my.jpg dir=/srv/images/jpg"/>

<property name="alternatedocroot_2" value="from=*.jpg dir=/srv/images/jpg"/>

<property name="alternatedocroot_3" value="from=/jpg/* dir=/src/images"/>

Chapter 8 • Developing Web and SIP Applications 165

The value o each alternate docroot has two components: The rst component, from, speciesthe alternate docroot's URI pattern, and the second component, dir, species the alternatedocroot's physical location (directory).

Suppose the above examples belong to a web application deployed athttp://company22.com/myapp . The rst alternate docroot maps any requests with this URL:

https://reader012.{domain}/reader012/html5/0821/5b7b0dd098b12/5b7b0e2a6c8b8.jpg

To this resource:

/svr/images/jpg/my.jpg

The second alternate docroot maps any requests with a *.jpg sux, such as:

http://company22.com/myapp/*.jpg

To this physical location:

AdvancedWeb Application Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 166/326

/svr/images/jpg

The third alternate docroot maps any requests whose URI starts with /myapp/jpg/, such as:

https://reader012.{domain}/reader012/html5/0821/5b7b0dd098b12/5b7b0e2b272cf./*

To the same directory as the second alternate docroot.

For example, the second alternate docroot maps this request:

https://reader012.{domain}/reader012/html5/0821/5b7b0dd098b12/5b7b0e2b53de9.jpg

To:

/srv/images/jpg/abc/def/my.jpg

The third alternate docroot maps:

https://reader012.{domain}/reader012/html5/0821/5b7b0dd098b12/5b7b0e2b272cf./abc/resource

To:

/srv/images/jpg/abc/resource

I a request does not match any o the target web application's alternate docroots, or i the targetweb application does not speciy any alternate docroots, the request is served rom the webapplication's standard docroot, as usual.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009166

Redirecting URLs

You can speciy that a request or an old URL is treated as a request or a new URL. This is calledredirecting a URL.

To speciy a redirected URL or a virtual server, use the redirect_n property, where n is a

positive integer that allows specication o more than one. This property is a subelement o avirtual-server element in the domain.xml le. For more inormation about this element, see“virtual-server” in Sun GlassFish Communications Server 2.0 Administration Reerence. Each o these redirect_n properties is inherited by all web applications deployed on the virtual server.

The value o each redirect_n property has two components, which may be specied in any order:

The rst component, from, species the prex o the requested URI to match.

The second component, url-prefix, species the new URL prex to return to the client. Therom prex is simply replaced by this URL prex.

AdvancedWeb ApplicationFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 167/326

For example:

<property name="redirect_1" value="from=/dummy url-prefix=http://etude"/>

Enabling Comet Support

To enable Comet support or an HTTP listener and all its associated web applications, set thecometSupport property to true. For more inormation, see “http-listener” in Sun GlassFishCommunications Server 2.0 Administration Reerence.

I your servlet or JSP page uses Comet technology, make sure it is initialized when theCommunications Server starts up by adding the load-on-startup element to your web.xml

le. For example:

<servlet>

<servlet-name>CheckIn</servlet-name>

<servlet-class>CheckInServlet</servlet-class>

<load-on-startup>0</load-on-startup>

</servlet>

Using a context.xml File

Use the contextXmlDefault property to speciy the location, relative to domain-dir ,othecontext.xml le or a virtual server. For more inormation about virtual servers, see “VirtualServers” on page 160. For more inormation about the context.xml le, see The ContextContainer (http://tomcat.apache.org/tomcat-5.5-doc/config/context.html ).

Chapter 8 • Developing Web and SIP Applications 167

Enabling WebDav

To enable WebDav in the Communications Server, you edit the web.xml and sun-web.xml lesas ollows.

First, enable the WebDav servlet in your web.xml le:

<servlet>

<servlet-name>webdav</servlet-name>

<servlet-class>org.apache.catalina.servlets.WebdavServlet</servlet-class>

<init-param>

<param-name>debug</param-name>

<param-value>0</param-value>

</init-param>

<init-param>

<param-name>listings</param-name>

<param-value>true</param-value>

</init-param>

<init-param>

d l /

AdvancedWeb Application Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 168/326

<param-name>readonly</param-name>

<param-value>false</param-value>

</init-param>

</servlet>

Then dene the servlet mapping associated with your WebDav servlet in your web.xml le:

<servlet-mapping>

<servlet-name>webdav</servlet-name>

<url-pattern>/webdav/*</url-pattern>

</servlet-mapping>

To protect the WebDav servlet so other users can't modiy it, add a security constraint in your

web.xml le:

<security-constraint>

<web-resource-collection>

<web-resource-name>Login Resources</web-resource-name>

<url-pattern>/webdav/*</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>Admin</role-name>

</auth-constraint><user-data-constraint>

<transport-guarantee>NONE</transport-guarantee>

</user-data-constraint>

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>default</realm-name>

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009168

</login-config>

<security-role>

<role-name>Admin</role-name>

</security-role>

</security-constraint>

Then dene a security role mapping in your sun-web.xml le:

<security-role-mapping>

<role-name>Admin</role-name>

<group-name>Admin</group-name>

</security-role-mapping>

I you are using the file realm, create a user and password. For example:

asadmin create-file-user --user admin --host localhost --port 4848 --terse=true--groups Admin --authrealmname default admin

You can now use any WebDav client by connecting to the WebDav servlet URL, which has thisormat:

AdvancedWeb ApplicationFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 169/326

http://host : port /context-root /webdav/ fle

For example:

http://localhost:80/glassfish-webdav/webdav/index.html

You can add the WebDav servlet to your default-web.xml le to enable it or all applications,but you can't set up a security role mapping to protect it.

Using mod_jk 

To set up mod_jk, ollow these steps:

1. Obtain the ollowing sotware:

■ Apache 2.0.x ■ Apache Tomcat Connectors (http://www.apache.org/dist/tomcat/

tomcat-connectors/jk/binaries/)■ Apache Tomcat 5.5.16, needed or just one JAR le (http://archive.apache.org/

dist/tomcat/tomcat-5/v5.5.16/bin/apache-tomcat-5.5.16.tar.gz )■ Apache Commons Logging 1.0.4 (http://archive.apache.org/

dist/jakarta/commons/logging/binaries/commons-logging-1.0.4.tar.gz )■ Apache Commons Modeler 1.1 (http://archive.apache.org/

dist/jakarta/commons/modeler/binaries/modeler-1.1.tar.gz )

2. Install mod_jk as described at http://tomcat.apache.org/connectors-doc/

webserver_howto/apache.html .

Chapter 8 • Developing Web and SIP Applications 169

3. Copy the ollowing Tomcat and Jakarta Commons les to as-install /lib:

■ tomcat-ajp.jar

■ commons-logging.jar

■ commons-modeler.jar

4. Create and congure the ollowing les:

■ /etc/httpd/conf/httpd.conf

■ /etc/httpd/conf/worker.properties ordomain-dir /config/glassfish-jk.properties (to use non-deault values o attributesdescribed at http://tomcat.apache.org/tomcat-5.5-doc/config/ajp.html )

Examples o these les are shown ater these steps. I you use both worker.properties andglassfish-jk.properties les, the le reerenced by httpd.conf, or reerenced by httpd.conf rst, takes precedence.

5. Start httpd.

6. Enable mod_jk using the ollowing command:

asadmin create-jvm-options -Dcom sun enterprise web connector enableJK=8009

AdvancedWeb Application Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 170/326

asadmin create jvm options Dcom.sun.enterprise.web.connector.enableJK=8009

7. I you are using the glassfish-jk.properties le and not reerencing it in httpd.conf,point to it using the ollowing command:

asadmin create-jvm-options-Dcom.sun.enterprise.web.connector.enableJK.propertyFile= domain-dir /config/glassfish-jk.properties

8. Restart the Communications Server.

Here is an example httpd.conf le:

LoadModule jk_module /usr/lib/httpd/modules/mod_jk.so

JkWorkersFile /etc/httpd/conf/worker.properties

# Where to put jk logsJkLogFile /var/log/httpd/mod_jk.log

# Set the jk log level [debug/error/info]

JkLogLevel debug

# Select the log format

JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "# JkOptions indicate to send SSL KEY SIZE,

JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories

# JkRequestLogFormat set the request format

JkRequestLogFormat "%w %V %T"# Send all jsp requests to GlassFish

JkMount /*.jsp worker1

# Send all glassfish-test requests to GlassFish

JkMount /glassfish-test/* worker1

Here is an example worker.properties or glassfish-jk.properties le:

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009170

# Define 1 real worker using ajp13

worker.list=worker1

# Set properties for worker1 (ajp13)

worker.worker1.type=ajp13

worker.worker1.host=localhost.localdomain

worker.worker1.port=8009

worker.worker1.lbfactor=50

worker.worker1.cachesize=10

worker.worker1.cache_timeout=600

worker.worker1.socket_keepalive=1

worker.worker1.socket_timeout=300

Advanced JVM Options or SIP Requests

You can change the DNS cache size and the number o SIP timer queues, which may improvethe perormance o SIP request processing.

The DNS cache ensures that consecutive lookup requests o a certain TEL URI initiated by anapplication do not trigger more than one e ternal DNS/ENUM request To congure the DNS

AdvancedWeb ApplicationFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 171/326

application do not trigger more than one external DNS/ENUM request. To congure the DNScache, set the maximum number o cache entries using the asadmin create-jvm-options

command. For example:

asadmin create-jvm-options --user adminuser -Ddns.cache.size=10000

The deault value is 50000.Avalueo -1 is interpreted as setting no limit on the number o entries.

The number o SIP timer queues is congurable. When the SIP request load is high, addingmore SIP timer queues may improve perormance. To set the number o SIP timer queues, usethe asadmin create-jvm-options command. For example:

asadmin create-jvm-options --user adminuser -Dorg.jvnet.glassfish.comms.sip.timer.queues=5

The deault value is 1. Allowed values are integers between 1 and 10 inclusive.

Chapter 8 • Developing Web and SIP Applications 171

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 172/326

172

Using Enterprise JavaBeansTechnology

This chapter describes how Enterprise JavaBeansTM (EJBTM) technology is supported in the SunGlassFish Communications Server. This chapter addresses the ollowing topics:

■ “Summary o EJB 3.0 Changes” on page 173■ “Value Added Features” on page 174

9C H A P T E R 9

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 173/326

■ “EJB Timer Service” on page 178■ “Using Session Beans” on page 179■ “Using Read-Only Beans” on page 186■

“Using Message-Driven Beans” on page 189■ “Handling Transactions With Enterprise Beans” on page 192

For general inormation about enterprise beans, see “Part Three: Enterprise Beans” in the JavaEE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/index.html ).

Summary o EJB 3.0 Changes

The Communications Server supports and is compliant with the Sun Microsystems EnterpriseJavaBeans (EJB) architecture as dened by the Enterprise JavaBeans Specication, v3.0, alsoknown as JSR 220 (http://jcp.org/en/jsr/detail?id=220).

Note – The Communications Server is backward compatible with 1.1, 2.0, and 2.1 enterprisebeans. However, to take advantage o version 3.0 eatures, you should develop new beans as 3.0enterprise beans.

The main changes in the Enterprise JavaBeans Specication, v3.0 that impact enterprise beansin the Communications Server environment are as ollows:

■ Denition o the Java language metadata annotations that can be used to annotate EJBapplications. These metadata annotations are targeted at simpliying the developer's task, atreducing the number o program classes and interaces the developer is required to

173

implement, at encapsulation o environmental dependencies and JNDI access, and ateliminating the need or the developer to provide an EJB deployment descriptor.

■ Elimination o the requirement or home or EJB component interaces or session beans.The required business interace or a session bean can be a plain Java interace rather than anEJBObject, EJBLocalObject, or java.rmi.Remote interace.

Elimination o all required interaces or persistent entities. Specication o Java languagemetadata annotations and XML deployment descriptor elements or the object/relationalmapping o persistent entities. For details about Java Persistence in the CommunicationsServer, see Chapter 7, “Using the Java Persistence API.”

Container-managed persistence (CMP) is still supported or EJB 2.1 beans, or backwardcompatibility. For details, see Chapter 10, “Using Container-Managed Persistence.”

Value Added FeaturesThe Communications Server provides a number o value additions that relate to EJBdevelopment. These capabilities are discussed in the ollowing sections. Reerences to morein-depth material are included.

Value Added Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 174/326

■ “Read-Only Beans” on page 174■ “The pass-by-reference Element” on page 175■ “Pooling and Caching” on page 175■ “Bean-Level Container-Managed Transaction Timeouts” on page 176■ “Priority Based Scheduling o Remote Bean Invocations” on page 177■ “Immediate Flushing” on page 177

Read-Only Beans

Another eature that the Communications Server provides is the read-only bean,anEJB2.1entity bean that is never modied by an EJB client. Read-only beans avoid database updatescompletely.

Note – Read-only beans are specic to the Communications Server and are not part o theEnterprise JavaBeans Specication, v2.1. Use o this eature or an EJB 2.1 bean results in anon-portable application.

To make an EJB 3.0 entity read-only, use @Column annotations to mark its columnsinsertable=false and updatable=false.

A read-only bean can be used to cache a database entry that is requently accessed but rarely updated (externally by other beans). When the data that is cached by a read-only bean isupdated by another bean, the read-only bean can be notied to reresh its cached data.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009174

The Communications Server provides a number o ways by which a read-only bean’s state canbe rereshed. By setting the refresh-period-in-seconds element in the sun-ejb-jar.xml leand the trans-attribute element (or @TransactionAttribute annotation) in theejb-jar.xml le, it is easy to congure a read-only bean that is one o the ollowing:

■ Always rereshed■ Periodically rereshed■ Never rereshed■ Programmatically rereshed

Read-only beans are best suited or situations where the underlying data never changes, orchanges inrequently. For urther inormation and usage guidelines, see“Using Read-Only Beans” on page 186.

The pass-by-reference ElementThe pass-by-reference element in the sun-ejb-jar.xml le allows you to speciy theparameter passing semantics or colocated remote EJB invocations. This is an opportunity toimprove perormance. However, use o this eature results in non-portable applications. See

Value Added Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 175/326

p p p pp“pass-by-reerence” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Pooling and Caching

The EJB container o the Communications Server pools anonymous instances (message-drivenbeans, stateless session beans, and entity beans) to reduce the overhead o creating anddestroying objects. The EJB container maintains the ree pool or each bean that is deployed.Bean instances in the ree pool have no identity (that is, no primary key associated) and are usedto serve method calls. The ree beans are also used to serve all methods or stateless session

beans.

Bean instances in the ree pool transition rom a Pooled state to a Cached state ater ejbCreate

and the business methods run. The size and behavior o each pool is controlled usingpool-related properties in the EJB container or the sun-ejb-jar.xml le.

In addition, the Communications Server supports a number o tunable parameters that cancontrol the number o “stateul” instances (stateul session beans and entity beans) cached as

well as the duration they are cached. Multiple bean instances that reer to the same database row in a table can be cached. The EJB container maintains a cache or each bean that is deployed.

To achieve scalability, the container selectively evicts some bean instances rom the cache,usually when cache overows. These evicted bean instances return to the ree bean pool. Thesize and behavior o each cache can be controlled using the cache-related properties in the EJBcontainer or the sun-ejb-jar.xml le.

Chapter 9 • Using Enterprise JavaBeans Technology 175

Pooling and caching parameters or the sun-ejb-jar.xml le are described in “bean-cache” inSun GlassFish Communications Server 2.0 Application Deployment Guide.

Pooling Parameters

One o the most important parameters o Communications Server pooling is

steady-pool-size. When steady-pool-size is set to greater than 0, the container not only pre-populates the bean pool with the specied number o beans, but also attempts to ensure thatthis number o beans is always available in the ree pool. This ensures that there are enoughbeans in the ready to serve state to process user requests.

This parameter does not necessarily guarantee that no more than steady-pool-size instancesexist at a given time. It only governs the number o instances that are pooled over a long periodo time. For example, suppose an idle stateless session container has a ully-populated pool witha steady-pool-size o 10. I 20 concurrent requests arrive or the EJB component, thecontainer creates 10 additional instances to satisy the burst o requests. The advantage o this isthat it prevents the container rom blocking any o the incoming requests. However, i theactivity dies down to 10 or ewer concurrent requests, the additional 10 instances are discarded.

Another parameter, pool-idle-timeout-in-seconds , allows the administrator to speciy the

Value Added Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 176/326

amount o time a bean instance can be idle in the pool. When pool-idle-timeout-in-seconds

is set to greater than 0, the container removes or destroys any bean instance that is idle or thisspecied duration.

Caching Parameters

Communications Server provides a way that completely avoids caching o entity beans, usingcommit option C. Commit option C is particularly useul i beans are accessed in large numberbut very rarely reused. For additional inormation, reer to “Commit Options” on page 193.

The Communications Server caches can be either bounded or unbounded. Bounded caches

have limits on the number o beans that they can hold beyond which beans are passivated. Forstateul session beans, there are three ways (LRU, NRU and FIFO) o picking victim beans whencache overow occurs. Caches can also passivate beans that are idle (not accessed or a speciedduration).

Bean-Level Container-Managed Transaction Timeouts

The deault transaction timeout or the domain is specied using the Transaction Timeoutsetting o the Transaction Service. A transaction started by the container must commit (orrollback) within this time, regardless o whether the transaction is suspended (and resumed), orthe transaction is marked or rollback.

To override this timeout or an individual bean, use the optional cmt-timeout-in-seconds

element in sun-ejb-jar.xml. The deault value, 0, species that the deault Transaction Service

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009176

timeout is used. The value o cmt-timeout-in-seconds is used or all methods in the bean thatstart a new container-managed transaction. This value is not used i the bean joins a clienttransaction.

Priority Based Scheduling o Remote Bean Invocations

You can create multiple thread pools, each having its own work queues. An optional element inthe sun-ejb-jar.xml le, use-thread-pool-id, species the thread pool that processes therequests or the bean. The bean must have a remote interace, or use-thread-pool-id isignored. You can create diferent thread pools and speciy the appropriate thread pool ID or abean that requires a quick response time. I there is no such thread pool congured or i theelement is absent, the deault thread pool is used.

Immediate Flushing

Normally, all entity bean updates within a transaction are batched and executed at the end o the transaction. The only exception is the database ush that precedes execution o a nder or

Value Added Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 177/326

y p pselect query.

Since a transaction oten spans many method calls, you might want to nd out i the updates

made by a method succeeded or ailed immediately ater method execution. To orce a ush atthe end o a method’s execution, use the flush-at-end-of-method element in thesun-ejb-jar.xml le. Only non-nder methods in an entity bean can be ush-enabled. (For anEJB 2.1 bean, these methods must be in the Local, Local Home, Remote, or Remote Homeinterace.) See “ush-at-end-o-method” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Upon completion o the method, the EJB container updates the database. Any exception

thrown by the underlying data store is wrapped as ollows:■ I the method that triggered the ush is a create method, the exception is wrapped with

CreateException.

■ I the method that triggered the ush is a remove method, the exception is wrapped withRemoveException.

■ For all other methods, the exception is wrapped with EJBException.

All normal end-o-transaction database synchronization steps occur regardless o whether thedatabase has been ushed during the transaction.

Chapter 9 • Using Enterprise JavaBeans Technology 177

EJB Timer ServiceThe EJB Timer Service uses a database to store persistent inormation about EJB timers. In thedeveloper prole, the EJB Timer Service in Communications Server is precongured to use anembedded version o the Java DB database. The EJB Timer Service conguration can storepersistent timer inormation in any database supported by the Communications Server or

persistence.

For a list o the JDBC drivers currently supported by the Communications Server, see the SunGlassFish Communications Server 2.0 Release Notes. For congurations o supported and otherdrivers, see “Congurations or Specic JDBC Drivers” in Sun GlassFish CommunicationsServer 2.0 Administration Guide.

To change the database used by the EJB Timer Service, set the EJB Timer Service’s Timer

DataSource setting to a valid JDBC resource. You must also create the timer database table.DDL les are located in as-install /lib/install/databases. Ideally, each cluster should haveits own timer table.

Using the EJB Timer Service is equivalent to interacting with a single JDBC resource manager.I an EJB component or application accesses a database either directly through JDBC or

EJBTimer Service

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 178/326

J p pp y g Jindirectly (or example, through an entity bean’s persistence mechanism), and also interactswith the EJB Timer Service, its data source must be congured with an XA JDBC driver.

You can change the ollowing EJB Timer Service settings. You must restart the server or thechanges to take efect.

■ Minimum Delivery Interval - Species the minimum time in milliseconds beore anexpiration or a particular timer can occur. This guards against extremely small timerincrements that can overload the server. The deault is 7000.

■ Maximum Redeliveries - Species the maximum number o times the EJB timer serviceattempts to redeliver a timer expiration due or exception or rollback. The deault is 1.

■ Redelivery Interval - Species how long in milliseconds the EJB timer service waits ater aailed ejbTimeout delivery beore attempting a redelivery. The deault is 5000.

■ Timer DataSource - Species the database used by the EJB Timer Service. In the developerprole, the deault is jdbc/__TimerPool.

For inormation about conguring EJB Timer Service settings, see Chapter 8, “SIP, Web, andEJB Containers,” in Sun GlassFish Communications Server 2.0 Administration Guide. For

inormation about the asadmin list-timers and asadmin migrate-timers commands, seethe Sun GlassFish Communications Server 2.0 Reerence Manual .

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009178

Using Session BeansThis section provides guidelines or creating session beans in the Communications Serverenvironment. This section addresses the ollowing topics:

■ “About the Session Bean Containers” on page 179■

“Stateul Session Bean Failover” on page 180■ “Session Bean Restrictions and Optimizations” on page 185

Extensive inormation on session beans is contained in Chapters 3 and 4 o the EnterpriseJavaBeans Specication, v3.0, EJB Core Contracts and Requirements.

About the Session Bean Containers

Like an entity bean, a session bean can access a database through Java Database Connectivity (JDBC) calls. A session bean can also provide transaction settings. These transaction settingsand JDBC calls are reerenced by the session bean’s container, allowing it to participate intransactions managed by the container.

Using Session Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 179/326

A container managing stateless session beans has a diferent charter rom a container managingstateul session beans. This section addresses the ollowing topics:

■ “Stateless Container” on page 179■ “Stateul Container” on page 180

Stateless Container

The stateless container manages stateless session beans, which, by denition, do not carry client-specic states. All session beans (o a particular type) are considered equal.

A stateless session bean container uses a bean pool to service requests. The CommunicationsServer specic deployment descriptor le, sun-ejb-jar.xml, contains the properties thatdene the pool:

■ steady-pool-size

■ resize-quantity

■ max-pool-size

■ pool-idle-timeout-in-seconds

For more inormation about sun-ejb-jar.xml,see “The sun-ejb-jar.xml File” in Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

The Communications Server provides the wscompile and wsdeploy tools to help youimplement a web service endpoint as a stateless session bean. For more inormation about thesetools, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Chapter 9 • Using Enterprise JavaBeans Technology 179

Stateul Container

The stateul container manages the stateul session beans, which, by denition, carry theclient-specic state. There is a one-to-one relationship between the client and the stateulsession beans. At creation, each stateul session bean (SFSB) is given a unique session ID that isused to access the session bean so that an instance o a stateul session bean is accessed by asingle client only.

Stateul session beans are managed using cache. The size and behavior o stateul session beanscache are controlled by speciying the ollowing sun-ejb-jar.xml parameters:

■ max-cache-size

■ resize-quantity

■ cache-idle-timeout-in-seconds

■ removal-timeout-in-seconds

■ victim-selection-policy

The max-cache-size element species the maximum number o session beans that are held incache. I the cache overows (when the number o beans exceeds max-cache-size), thecontainer then passivates some beans or writes out the serialized state o the bean into a le. Thedirectory in which the le is created is obtained rom the EJB container using the congurationAPI

Using Session Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 180/326

APIs.

For more inormation about sun-ejb-jar.xml,see “The sun-ejb-jar.xml File” in Sun GlassFish

Communications Server 2.0 Application Deployment Guide.

The passivated beans are stored on the le system. The Session Store Location setting in the EJBcontainer allows the administrator to speciy the directory where passivated beans are stored.By deault, passivated stateul session beans are stored in application-specic subdirectoriescreated underdomain-dir /session-store.

Note – Make sure the delete option is set in the server.policy le, or expired le-basedsessions might not be deleted properly. For more inormation about server.policy, see “Theserver.policy File” on page 95.

The Session Store Location setting also determines where the session state is persisted i it is nothighly available; see “Choosing a Persistence Store” on page 182.

Stateul Session Bean FailoverAn SFSB’s state can be saved in a persistent store in case a server instance ails. The state o anSFSB is saved to the persistent store at predened points in its lie cycle. This is calledcheckpointing . I SFSB checkpointing is enabled, checkpointing generally occurs ater any transaction involving the SFSB is completed, even i the transaction rolls back.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009180

However, i an SFSB participates in a bean-managed transaction, the transaction might becommitted in the middle o the execution o a bean method. Since the bean’s state might beundergoing transition as a result o the method invocation, this is not an appropriate instant tocheckpoint the bean’s state. In this case, the EJB container checkpoints the bean’s state at the endo the corresponding method, provided the bean is not in the scope o another transaction whenthat method ends. I a bean-managed transaction spans across multiple methods,

checkpointing is delayed until there is no active transaction at the end o a subsequent method.

The state o an SFSB is not necessarily transactional and might be signicantly modied as aresult o non-transactional business methods. I this is the case or an SFSB, you can speciy a listo checkpointed methods. I SFSB checkpointing is enabled, checkpointing occurs ater any checkpointed methods are completed.

Note –Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domains

that are created with the cluster prole. For inormation about proles, see“Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

Th ll i bl li h h SFSB il All bj b d

Using Session Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 181/326

The ollowing table lists the types o reerences that SFSB ailover supports. All objects boundinto an SFSB must be one o the supported types. In the table, No indicates that ailover or theobject type might not work in all cases and that no ailover support is provided. However,ailover might work in some cases or that object type. For example, ailover might work because the class implementing that type is serializable.

TABLE 9–1 Object Types Supported or Java EE Stateul Session Bean State Failover

Java Object Type Failover Support

Colocated or distributed stateless session, stateulsession, or entity bean reerence

Yes

JNDI context Yes, InitialContext and java:comp/env

UserTransaction Yes, but i the instance that ails is never restarted, any  prepared global transactions are lost and might not becorrectly rolled back or committed.

JDBC DataSource No

Java Message Service (JMS) ConnectionFactory,

Destination

No

JavaMail Session No

Connection Factory No

Administered Object No

Chapter 9 • Using Enterprise JavaBeans Technology 181

TABLE 9–1 Object Types Supported or Java EE Stateul Session Bean State Failover (Continued)

Java Object Type Failover Support

Web service reerence No

Serializable Java types Yes

Extended persistence context No

For more inormation about the InitialContext, see “Accessing the Naming Context” onpage 277. For more inormation about transaction recovery, see Chapter 16, “Using theTransaction Service.” For more inormation about Administered Objects, see“CreatingPhysical Destinations” on page 289.

Note – Idempotent URLs are supported along the HTTP path, but not the RMI-IIOP path. For

more inormation, see “Conguring Idempotent URL Requests” on page 163.

I a server instance to which an RMI-IIOP client request is sent crashes during the requestprocessing (beore the response is prepared and sent back to the client), an error is sent to theclient. The client must retry the request explicitly. When the client retries the request, therequest is sent to another server instance in the cluster, which retrieves session state

Using Session Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 182/326

qinormation or this client.

HTTP and SIP sessions can also be saved in a persistent store in case a server instance ails. Inaddition, i a distributable web or SIP application reerences an SFSB, and the web or SIPapplication’s session ails over, the EJB reerence is also ailed over. For more inormation, see“Distributed Sessions and Persistence” on page 153.

I an SFSB that uses session persistence is undeployed while the Communications Serverinstance is stopped, the session data in the persistence store might not be cleared. To preventthis, undeploy the SFSB while the Communications Server instance is running.

Congure SFSB ailover by:

■ “Choosing a Persistence Store” on page 182■ “Enabling Checkpointing” on page 183■ “Speciying Methods to Be Checkpointed” on page 184 (optional)

Choosing a Persistence Store

The ollowing types o persistent storage are supported or passivation and checkpointing o theSFSB state:

■ The local le system - Allows a single server instance to recover the SFSB state ater a ailureand restart. This store also provides passivation and activation o the state to help controlthe amount o memory used. This option is not supported in a production environment thatrequires SFSB state persistence. This is the deault storage mechanism.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009182

■ Other servers - Uses other server instances in the cluster or session persistence. Clusteredserver instances replicate session state in a ring topology. Each backup instance stores thereplicated data in memory.

Choose the persistence store in one o the ollowing ways:

■ To use the local le system, rst disable availability. Select the Availability Service

component under the relevant conguration in the Admin Console. Uncheck theAvailability Service box. Then select the EJB Container component and edit the SessionStore Location value. The deault is domain-dir /session-store.

■ To use other servers, select the Availability Service component under the relevantconguration in the Admin Console. Check the Availability Service box. To enableavailability or the EJB container, select the EJB Container Availability tab, then check theAvailability Service box. All instances in an Communications Server cluster should have thesame availability settings to ensure consistent behavior.

For more inormation, see the Sun GlassFish Communications Server 2.0 High Availability  Administration Guide.

Enabling Checkpointing

Th ll i i d ib h bl SFSB h k i i

Using Session Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 183/326

The ollowing sections describe how to enable SFSB checkpointing:

■ “Server Instance and EJB Container Levels” on page 183■ “Application and EJB Module Levels” on page 183■ “SFSB Level” on page 183

Server Instance and EJB Container Levels

To enable SFSB checkpointing at the server instance or EJB container level, see “Choosing aPersistence Store” on page 182.

Application and EJB Module Levels

To enable SFSB checkpointing at the application or EJB module level during deployment, usethe asadmin deploy or asadmin deploydir command with the --availabilityenabled

option set to true. For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

SFSB Level

To enable SFSB checkpointing at the SFSB level, set availability-enabled="true" in the ejb

element o the SFSB’s sun-ejb-jar.xml le as ollows:

<sun-ejb-jar>

...

<enterprise-beans>

Chapter 9 • Using Enterprise JavaBeans Technology 183

...

<ejb availability-enabled="true">

<ejb-name>MySFSB</ejb-name>

</ejb>

...

</enterprise-beans>

</sun-ejb-jar>

Speciying Methods to Be Checkpointed

I SFSB checkpointing is enabled, checkpointing generally occurs ater any transactioninvolving the SFSB is completed, even i the transaction rolls back.

To speciy additional optional checkpointing o SFSBs at the end o non-transactional businessmethods that cause important modications to the bean’s state, use the

checkpoint-at-end-of-method element within the ejb element in sun-ejb-jar.xml.

For example:

<sun-ejb-jar>

...

<enterprise-beans>

Using Session Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 184/326

<enterprise beans>

...

<ejb availability-enabled="true">

<ejb-name>ShoppingCartEJB</ejb-name>

<checkpoint-at-end-of-method>

<method>

<method-name>addToCart</method-name>

</method>

</checkpoint-at-end-of-method>

</ejb>

...

</enterprise-beans>

</sun-ejb-jar>

For details, see “checkpoint-at-end-o-method” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

The non-transactional methods in the checkpoint-at-end-of-method element can be theollowing:

■ create() methods dened in the home or business interace o the SFSB, i you want tocheckpoint the initial state o the SFSB immediately ater creation

■ For SFSBs using container managed transactions only, methods in the remote interace o the bean marked with the transaction attribute TX_NOT_SUPPORTED or TX_NEVER 

■ For SFSBs using bean managed transactions only, methods in which a bean managedtransaction is neither started nor committed

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009184

Any other methods mentioned in this list are ignored. At the end o invocation o each o thesemethods, the EJB container saves the state o the SFSB to persistent store.

Note – I an SFSB does not participate in any transaction, and i none o its methods are explicitly specied in the checkpoint-at-end-of-method element, the bean’s state is not checkpointed atall even i availability-enabled="true" or this bean.

For better perormance, speciy a small subset o methods. The methods chosen shouldaccomplish a signicant amount o work in the context o the Java EE application or shouldresult in some important modication to the bean’s state.

Session Bean Restrictions and Optimizations

This section discusses restrictions on developing session beans and provides some optimizationguidelines:

■ “Optimizing Session Bean Perormance” on page 185■ “Restricting Transactions” on page 185

Using Session Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 185/326

Optimizing Session Bean Perormance

For stateul session beans, colocating the stateul beans with their clients so that the client andbean are executing in the same process address space improves perormance.

RestrictingTransactions

The ollowing restrictions on transactions are enorced by the container and must be observedas session beans are developed:

■ A session bean can participate in, at most, a single transaction at a time.

■ I a session bean is participating in a transaction, a client cannot invoke a method on thebean such that the trans-attribute element (or @TransactionAttribute annotation) inthe ejb-jar.xml le would cause the container to execute the method in a diferent orunspecied transaction context or an exception is thrown.

■ I a session bean instance is participating in a transaction, a client cannot invoke the remove

method on the session object’s home or business interace object, or an exception is thrown.

Chapter 9 • Using Enterprise JavaBeans Technology 185

Using Read-Only BeansA read-only bean is an EJB 2.1 entity bean that is never modied by an EJB client. The data that aread-only bean represents can be updated externally by other enterprise beans, or by othermeans, such as direct database updates.

Note – Read-only beans are specic to the Communications Server and are not part o theEnterprise JavaBeans Specication, v2.1. Use o this eature or an EJB 2.1 bean results in anon-portable application.

To make an EJB 3.0 entity bean read-only, use @Column annotations to mark its columnsinsertable=false and updatable=false.

Read-only beans are best suited or situations where the underlying data never changes, orchanges inrequently. The ollowing topics are addressed in this section:

■ “Read-Only Bean Characteristics and Lie Cycle” on page 186■ “Read-Only Bean Good Practices” on page 187■ “Rereshing Read-Only Beans” on page 187■ “Deploying Read-Only Beans” on page 189

Using Read-Only Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 186/326

p y g y p g

Read-Only Bean Characteristics and Lie CycleRead-only beans are best suited or situations where the underlying data never changes, orchanges inrequently. For example, a read-only bean can be used to represent a stock quote or aparticular company, which is updated externally. In such a case, using a regular entity beanmight incur the burden o calling ejbStore, which can be avoided by using a read-only bean.

Read-only beans have the ollowing characteristics:

■ Only entity beans can be read-only beans.

■ Either bean-managed persistence (BMP) or container-managed persistence (CMP) isallowed. I CMP is used, do not create the database schema during deployment. Instead,work with your database administrator to populate the data into the tables. SeeChapter 10,“Using Container-Managed Persistence.”

■ Only container-managed transactions are allowed; read-only beans cannot start their owntransactions.

■ Read-only beans don’t update any bean state.

■ ejbStore is never called by the container.

■ ejbLoad is called only when a transactional method is called or when the bean is initially created (in the cache), or at regular intervals controlled by the bean’srefresh-period-in-seconds element in the sun-ejb-jar.xml le.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009186

■ The home interace can have any number o nd methods. The return type o the ndmethods must be the primary key or the same bean type (or a collection o primary keys).

■ I the data that the bean represents can change, then refresh-period-in-seconds must beset to reresh the beans at regular intervals. ejbLoad is called at this regular interval.

A read-only bean comes into existence using the appropriate nd methods.

Read-only beans are cached and have the same cache properties as entity beans. When aread-only bean is selected as a victim to make room in the cache, ejbPassivate is called and thebean is returned to the ree pool. When in the ree pool, the bean has no identity and is usedonly to serve any nder requests.

Read-only beans are bound to the naming service like regular read-write entity beans, andclients can look up read-only beans the same way read-write entity beans are looked up.

Read-Only Bean Good Practices

For best results, ollow these guidelines when developing read-only beans:

■ Avoid having any create or remove methods in the home interace.

U th lid EJB 2 1 t ti tt ib t th ib l t

Using Read-Only Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 187/326

■ Use any o the valid EJB 2.1 transaction attributes or the trans-attribute element.

The reason or having TX_SUPPORTED is to allow reading uncommitted data in the sametransaction. Also, the transaction attributes can be used to orce ejbLoad.

Rereshing Read-Only Beans

There are several ways o rereshing read-only beans as addressed in the ollowing sections:

■ “Invoking a Transactional Method” on page 187■

“Rereshing Periodically” on page 187■ “Rereshing Programmatically” on page 188

Invoking a Transactional Method

Invoking any transactional method invokes ejbLoad.

Rereshing Periodically

Use the refresh-period-in-seconds element in the sun-ejb-jar.xml le to reresh aread-only bean periodically.

■ I the value specied in refresh-period-in-seconds is zero or not specied, which is thedeault, the bean is never rereshed (unless a transactional method is accessed).

■ I the value is greater than zero, the bean is rereshed at the rate specied.

Chapter 9 • Using Enterprise JavaBeans Technology 187

Note – This is the only way to reresh the bean state i the data can be modied external to theCommunications Server.

By deault, a single timer is used or all instances o a read-only bean. When that timer res, allbean instances are marked as expired and are rereshed rom the database the next time they are

used.

Use the -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true ag to reresheach bean instance independently upon access i its reresh period has expired. The deault isfalse. Note that each instance still has the same reresh period. This additional level o granularity can improve the perormance o read-only beans that do not need to be rereshed atthe same time.

To set this ag, use the asadmin create-jvm-options command. For example:

asadmin create-jvm-options --user adminuser -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true

Rereshing Programmatically

Typically, beans that update any data that is cached by read-only beans need to notiy theread-only beans to reresh their state. Use ReadOnlyBeanNotifier to orce the reresh o

Using Read-Only Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 188/326

read only beans to reresh their state. Use ReadOnlyBeanNotifier to orce the reresh o read-only beans.

To do this, invoke the ollowing methods on the ReadOnlyBeanNotifier bean:

public interface ReadOnlyBeanNotifier extends java.rmi.Remote {

refresh(Object PrimaryKey) throws RemoteException;

}

The implementation o the ReadOnlyBeanNotifier interace is provided by the container. Thebean looks up ReadOnlyBeanNotifier using a ragment o code such as the ollowing example:

com.sun.appserv.ejb.ReadOnlyBeanHelper helper =

new com.sun.appserv.ejb.ReadOnlyBeanHelper();

com.sun.appserv.ejb.ReadOnlyBeanNotifier notifier =

helper.getReadOnlyBeanNotifier("java:comp/env/ejb/ReadOnlyCustomer");

notifier.refresh(PrimaryKey);

For a local read-only bean notier, the lookup has this modication:

helper.getReadOnlyBeanLocalNotifier("java:comp/env/ejb/LocalReadOnlyCustomer");

Beans that update any data that is cached by read-only beans need to call the refresh methods.The next (non-transactional) call to the read-only bean invokes ejbLoad.

For Javadoc tool pages relevant to read-only beans, go to http://glassfish.dev.java.net/

nonav/javaee5/api/index.html and click on the com.sun.appserv.ejb package.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009188

Deploying Read-Only BeansRead-only beans are deployed in the same manner as other entity beans. However, in the entry or the bean in the sun-ejb-jar.xml le, the is-read-only-bean element must be set to true.That is:

<is-read-only-bean>true</is-read-only-bean>

Also, the refresh-period-in-seconds element in the sun-ejb-jar.xml le can be set to some value that species the rate at which the bean is rereshed. I this element is missing, no rereshoccurs.

All requests in the same transaction context are routed to the same read-only bean instance. Setthe allow-concurrent-access element to either true (to allow concurrent accesses) or false

(to serialize concurrent access to the same read-only bean). The deault is false.

For urther inormation on these elements, reer to “The sun-ejb-jar.xml File” in Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

Using Message-Driven BeansThis section describes message driven beans and explains the requirements or creating them in

Using Message-Driven Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 189/326

This section describes message-driven beans and explains the requirements or creating them inthe Communications Server environment. This section contains the ollowing topics:

■ “Message-Driven Bean Conguration” on page 189■ “Message-Driven Bean Restrictions and Optimizations” on page 191

Message-Driven Bean ConfgurationThis section addresses the ollowing conguration topics:

“Connection Factory and Destination” on page 189■ “Message-Driven Bean Pool” on page 190■ “Domain-Level Settings” on page 190

For inormation about setting up load balancing or message-driven beans, see“Load-BalancedMessage Inow” on page 292.

Connection Factory and Destination

A message-driven bean is a client to a Connector inbound resource adapter. Themessage-driven bean container uses the JMS service integrated into the CommunicationsServer or message-driven beans that are JMS clients. JMS clients use JMS Connection Factory-and Destination-administered objects. A JMS Connection Factory administered object is aresource manager Connection Factory object that is used to create connections to the JMSprovider.

Chapter 9 • Using Enterprise JavaBeans Technology 189

The mdb-connection-factory element in the sun-ejb-jar.xml le or a message-driven beanspecies the connection actory that creates the container connection to the JMS provider.

The jndi-name element o the ejb element in the sun-ejb-jar.xml le species the JNDIname o the administered object or the JMS Queue or Topic destination that is associated withthe message-driven bean.

Message-Driven Bean Pool

The container manages a pool o message-driven beans or the concurrent processing o astream o messages. The sun-ejb-jar.xml le contains the elements that dene the pool (thatis, the bean-pool element):

■ steady-pool-size

■ resize-quantity■ max-pool-size

■ pool-idle-timeout-in-seconds

For more inormation about sun-ejb-jar.xml,see “The sun-ejb-jar.xml File” in Sun GlassFish

Communications Server 2.0 Application Deployment Guide.

Using Message-Driven Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 190/326

Domain-Level SettingsYou can control the ollowing domain-level message-driven bean settings in the EJB container:

■ Initial and Minimum Pool Size - Species the initial and minimum number o beansmaintained in the pool. The deault is 0.

■ Maximum Pool Size - Species the maximum number o beans that can be created to satisy client requests. The deault is 32.

■ Pool Resize Quantity - Species the number o beans to be created i a request arrives whenthe pool is empty (subject to the Initial and Minimum Pool Size), or the number o beans toremove i idle or more than the Idle Timeout. The deault is 8.

■ Idle Timeout - Species the maximum time in seconds that a bean can remain idle in thepool. Ater this amount o time, the bean is destroyed. The deault is 600 (10 minutes). A

 value o 0 means a bean can remain idle indenitely.

For inormation on monitoring message-driven beans, click the Help button in the AdminConsole. In the developer prole, the Monitor tab is accessible rom the Application Serverpage. In the Cluster prole, select the Stand-Alone Instances component, select the instancerom the table, and select the Monitor tab.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009190

Note – Running monitoring when it is not needed might impact perormance, so you mightchoose to turn monitoring of when it is not in use. For details, see Chapter 20, “MonitoringComponents and Services,” in Sun GlassFish Communications Server 2.0 Administration Guide.

Message-Driven Bean Restrictions and OptimizationsThis section discusses the ollowing restrictions and perormance optimizations that pertain todeveloping message-driven beans:

■ “Pool Tuning and Monitoring” on page 191■ “The onMessage Runtime Exception” on page 191

Pool Tuning and Monitoring

The message-driven bean pool is also a pool o threads, with each message-driven bean instancein the pool associating with a server session, and each server session associating with a thread.Thereore, a large pool size also means a high number o threads, which impacts perormanceand server resources.

Using Message-Driven Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 191/326

When conguring message-driven bean pool properties, make sure to consider actors such as

message arrival rate and pattern, onMessage method processing time, overall server resources(threads, memory, and so on), and any concurrency requirements and limitations rom otherresources that the message-driven bean accesses.

When tuning perormance and resource usage, make sure to consider potential JMS providerproperties or the connection actory used by the container (the mdb-connection-factory

element in the sun-ejb-jar.xml le). For example, you can tune the Sun GlassFish MessageQueue ow control related properties or connection actory in situations where the message

incoming rate is much higher thanmax-pool-size

can handle.Reer to Chapter 20, “Monitoring Components and Services,” in Sun GlassFish CommunicationsServer 2.0 Administration Guide or inormation on how to get message-driven bean poolstatistics.

The onMessage Runtime Exception

Message-driven beans, like other well-behaved MessageListeners, should not, in general, throw runtime exceptions. I a message-driven bean’s onMessage method encounters a system-levelexception or error that does not allow the method to successully complete, the EnterpriseJavaBeans Specication, v3.0 provides the ollowing guidelines:

■ I the bean method encounters a runtime exception or error, it should simply propagate theerror rom the bean method to the container.

Chapter 9 • Using Enterprise JavaBeans Technology 191

■ I the bean method perorms an operation that results in a checked exception that the beanmethod cannot recover, the bean method should throw thejavax.ejb.EJBException thatwraps the original exception.

■ Any other unexpected error conditions should be reported using javax.ejb.EJBException

(javax.ejb.EJBException is a subclass o java.lang.RuntimeException).

Under container-managed transaction demarcation, upon receiving a runtime exception roma message-driven bean’s onMessage method, the container rolls back the container-startedtransaction and the message is redelivered. This is because the message delivery itsel is part o the container-started transaction. By deault, the Communications Server container closes thecontainer’s connection to the JMS provider when the rst runtime exception is received rom amessage-driven bean instance’s onMessage method. This avoids potential message redelivery looping and protects server resources i the message-driven bean’s onMessage methodcontinues misbehaving. To change this deault container behavior, use thecmt-max-runtime-exceptions property o the mdb-container element in the domain.xml le.

The cmt-max-runtime-exceptions property species the maximum number o runtimeexceptions allowed rom a message-driven bean’s onMessage method beore the container startsto close the container’s connection to the message source. By deault this value is 1; -1 disablesthis container protection.

HandlingTransactions With EnterpriseBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 192/326

A message-driven bean’s onMessage method can use the javax.jms.Message

getJMSRedelivered method to check whether a received message is a redelivered message.

Note – The cmt-max-runtime-exceptions property might be deprecated in the uture.

Handling Transactions With Enterprise BeansThis section describes the transaction support built into the Enterprise JavaBeans programmingmodel or the Communications Server.

As a developer, you can write an application that updates data in multiple databases distributedacross multiple sites. The site might use EJB servers rom diferent vendors. This sectionprovides overview inormation on the ollowing topics:

■ “Flat Transactions” on page 193■ “Global and Local Transactions” on page 193■ “Commit Options” on page 193■ “Administration and Monitoring” on page 194

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009192

Flat Transactions

The Enterprise JavaBeans Specication, v3.0 requires support or at (as opposed to nested)transactions. In a at transaction, each transaction is decoupled rom and independent o othertransactions in the system. Another transaction cannot start in the same thread until thecurrent transaction ends.

Flat transactions are the most prevalent model and are supported by most commercial databasesystems. Although nested transactions ofer a ner granularity o control over transactions, they are supported by ar ewer commercial database systems.

Global and LocalTransactions

Understanding the distinction between global and local transactions is crucial in understandingthe Communications Server support or transactions. See “Transaction Scope” on page 270.

Both local and global transactions are demarcated using thejavax.transaction.UserTransaction interace, which the client must use. Local transactionsbypass the transaction manager and are aster. For more inormation, see “The TransactionManager, the Transaction Synchronization Registry, and UserTransaction”onpage272.

HandlingTransactionsWithEnterprise Beans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 193/326

Commit Options

The EJB protocol is designed to give the container the exibility to select the disposition o theinstance state at the time a transaction is committed. This allows the container to best managecaching an entity object’s state and associating an entity object identity with the EJB instances.

There are three commit-time options:

OptionA – The container caches a ready instance between transactions. The containerensures that the instance has exclusive access to the state o the object in persistent storage.

In this case, the container does not have to synchronize the instance’s state rom thepersistent storage at the beginning o the next transaction.

Note – Commit option A is not supported or this Communications Server release.

■ OptionB – The container caches a ready instance between transactions, but the containerdoes not ensure that the instance has exclusive access to the state o the object in persistentstorage. This is the deault.

In this case, the container must synchronize the instance’s state by invoking ejbLoad rompersistent storage at the beginning o the next transaction.

Chapter 9 • Using Enterprise JavaBeans Technology 193

■ OptionC – The container does not cache a ready instance between transactions, but insteadreturns the instance to the pool o available instances ater a transaction has completed.

The lie cycle or every business method invocation under commit option C looks like this.

ejbActivate → ejbLoad → business method → ejbStore → ejbPassivate

I there is more than one transactional client concurrently accessing the same entity, the rstclient gets the ready instance and subsequent concurrent clients get new instances rom thepool.

The Communications Server deployment descriptor has an element, commit-option, thatspecies the commit option to be used. Based on the specied commit option, the appropriatehandler is instantiated.

Administration and Monitoring

An administrator can control a number o domain-level Transaction Service settings. Fordetails, see “Conguring the Transaction Service” on page 272.

The Transaction Timeout setting can be overridden by a bean. See“Bean-LevelContainer-Managed Transaction Timeouts” on page 176.

HandlingTransactions With EnterpriseBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 194/326

g p g

In addition, the administrator can monitor transactions using statistics rom the transactionmanager that provide inormation on such activities as the number o transactions completed,rolled back, or recovered since server startup, and transactions presently being processed.

For inormation on administering and monitoring transactions, select the Transaction Servicecomponent under the relevant conguration in the Admin Console and click the Help button.Also see Chapter 12, “Transactions,” in Sun GlassFish Communications Server 2.0 Administration Guide.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009194

Using Container-Managed Persistence

This chapter contains inormation on how EJB 2.1 container-managed persistence (CMP)works in the Sun GlassFish Communications Server in the ollowing topics:

■ “Communications Server Support or CMP” on page 195■ “CMP Mapping” on page 196■ “Automatic Schema Generation or CMP” on page 200■ “Schema Capture” on page 206■ “Conguring the CMP Resource” on page 207

“P R l d F ” 207

10C H A P T E R 1 0

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 195/326

■ “Perormance-Related Features” on page 207■ “Conguring Queries or 1.1 Finders” on page 210■ “CMP Restrictions and Optimizations” on page 214

Communications Server Support or CMPCommunications Server support or EJB 2.1 CMP beans includes:

■ Full support or the J2EE v1.4 specication’s CMP model. Extensive inormation on CMP iscontained in chapters 10, 11, and 14 o the Enterprise JavaBeans Specication, v2.1. Thisincludes the ollowing:

■ Support or commit options B and C or transactions. See “Commit Options” onpage 193.

■ The primary key class must be a subclass o java.lang.Object. This ensures portability,and is noted because some vendors allow primitive types (such as int)tobeusedastheprimary key class.

■ The Communications Server CMP implementation, which provides the ollowing:

■ An Object/Relational (O/R) mapping tool that creates XML deployment descriptors orEJB JAR les that contain beans that use CMP.

■ Support or compound (multi-column) primary keys.

■ Support or sophisticated custom nder methods.

195

■ Standards-based query language (EJB QL).

■ CMP runtime support. See “Conguring the CMP Resource” on page 207.

■ Communications Server perormance-related eatures, including the ollowing:

■ Version column consistency checking■ Relationship preetching■

Read-Only BeansFor details, see “Perormance-Related Features” on page 207.

CMP MappingImplementation or entity beans that use CMP is mostly a matter o mapping CMP elds and

CMR elds (relationships) to the database. This section addresses the ollowing topics:■ “Mapping Capabilities” on page 196■ “The Mapping Deployment Descriptor File” on page 196■ “Mapping Considerations” on page 197

Mapping Capabilities

CMP Mapping

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 196/326

pp g p

 Mapping reers to the ability to tie an object-based model to a relational model o data, usually the schema o a relational database. The CMP implementation provides the ability to tie a set o interrelated beans containing data and associated behaviors to the schema. This objectrepresentation o the database becomes part o the Java application. You can also customize thismapping to optimize these beans or the particular needs o an application. The result is a singledata model through which both persistent database inormation and regular transient programdata are accessed.

The mapping capabilities provided by the Communications Server include:

■ Mapping a CMP bean to one or more tables■ Mapping CMP elds to one or more columns■ Mapping CMP elds to diferent column types■ Mapping tables with compound primary keys■ Mapping tables with unknown primary keys■ Mapping CMP relationships to oreign keys■

Mapping tables with overlapping primary and oreign keys

The Mapping Deployment Descriptor File

Each module with CMP beans must have the ollowing les:

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009196

■ ejb-jar.xml – The J2EE standard le or assembling enterprise beans. For a detaileddescription, see the Enterprise JavaBeans Specication, v2.1.

■ sun-ejb-jar.xml – The Communications Server standard le or assembling enterprisebeans. For a detailed description, see“The sun-ejb-jar.xml File” in Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

■ sun-cmp-mappings.xml –The mapping deployment descriptor fle, which describes the

mapping o CMP beans to tables in a database. For a detailed description, see “Thesun-cmp-mappings.xml File” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide.

The sun-cmp-mappings.xml le can be automatically generated and does not have to exist priorto deployment. For details, see“Generation Options or CMP” on page 203.

The sun-cmp-mappings.xml le maps CMP elds and CMR elds (relationships) to thedatabase. A primary table must be selected or each CMP bean, and optionally, multiplesecondary tables. CMP elds are mapped to columns in either the primary or secondary table(s). CMR elds are mapped to pairs o column lists (normally, column lists are the lists o columns associated with primary and oreign keys).

Note – Table names in databases can be case-sensitive. Make sure that the table names in thesun-cmp-mappings.xml le match the names in the database.

CMP Mapping

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 197/326

Relationships should always be mapped to the primary key eld(s) o the related table.

The sun-cmp-mappings.xml le conorms to the sun-cmp-mapping_1_2.dtd leandispackaged with the user-dened bean classes in the EJB JAR le under the META-INF directory.

The Communications Server creates the mappings in the sun-cmp-mappings.xml leautomatically during deployment i the le is not present.

To map the elds and relationships o your entity beans manually, edit thesun-cmp-mappings.xml deployment descriptor. Only do this i you are procient in editingXML.

The mapping inormation is developed in conjunction with the database schema (.dbschema)le, which can be automatically captured when you deploy the bean (see “Automatic DatabaseSchema Capture” on page 206). You can manually generate the schema using thecapture-schema utility (“Using the capture-schema Utility” on page 206).

Mapping ConsiderationsThis section addresses the ollowing topics:

■ “Join Tables and Relationships” on page 198■ “Automatic Primary Key Generation” on page 198

Chapter 10 • Using Container-Managed Persistence 197

■ “Fixed Length CHAR Primary Keys” on page 198■ “Managed Fields” on page 198■ “BLOB Support” on page 199■ “CLOB Support” on page 200

The data types used in automatic schema generation are also suggested or manual mapping.These data types are described in “Supported Data Types or CMP” on page 201.

 Join Tables and Relationships

Use o join tables in the database schema is supported or all types o relationships, not justmany-to-many relationships. For general inormation about relationships, see section 10.3.7 o the Enterprise JavaBeans Specication, v2.1.

Automatic Primary Key Generation

The Communications Server supports automatic primary key generation or EJB 1.1, 2.0, and2.1 CMP beans. To speciy automatic primary key generation, give the prim-key-class

element in the ejb-jar-xml le the value java.lang.Object. CMP beans with automatically generated primary keys can participate in relationships with other CMP beans. TheCommunications Server does not support database-generated primary key values.

I the database schema is created during deployment, the Communications Server creates theschema with the primary key column then generates unique values or the primary key column

CMP Mapping

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 198/326

schema with the primary key column, then generates unique values or the primary key column

at runtime.

I the database schema is not created during deployment, the primary key column in themapped table must be o type NUMERIC with a precision o 19 or more, and must not be mappedto any CMP eld. The Communications Server generates unique values or the primary key column at runtime.

Fixed Length CHAR Primary Keys

I an existing database table has a primary key column in which the values vary in length, but thetype is CHAR instead o VARCHAR, the Communications Server automatically trims any extraspaces when retrieving primary key values. It is not a good practice to use a xed length CHAR

column as a primary key. Use this eature with schemas that cannot be changed, such as aschema inherited rom a legacy application.

Managed Fields

A managed eld is a CMP or CMR eld that is mapped to the same database column as anotherCMP or CMR eld. CMP elds mapped to the same column and CMR elds mapped to exactly the same column lists always have the same value in memory. For CMR elds that share only asubset o their mapped columns, changes to the columns afect the relationship elds inmemory diferently. Basically, the Communications Server always tries to keep the state o theobjects in memory synchronized with the database.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009198

A managed eld can have any fetched-with subelement. I the fetched-with subelement is<default/>,the -DAllowManagedFieldsInDefaultFetchGroup ag must be set to true.See“Deault Fetch Group Flags” on page 210 and “etched-with” in Sun GlassFish Communications

Server 2.0 Application Deployment Guide.

BLOB SupportBinary Large Object (BLOB) is a data type used to store values that do not correspond to othertypes such as numbers, strings, or dates. Java elds whose types implementjava.io.Serializable or are represented as byte[] can be stored as BLOBs.

IaCMPeldisdenedas Serializable, it is serialized into a byte[] beore being stored inthe database. Similarly, the value etched rom the database is deserialized. However, i a CMPeld is dened as byte[], it is stored directly instead o being serialized and deserialized when

stored and etched, respectively.

To enable BLOB support in the Communications Server environment, dene a CMP eld o type byte[] or a user-dened type that implements the java.io.Serializable interace. I you map the CMP bean to an existing database schema, map the eld to a column o type BLOB.

To use BLOB or CLOB data types larger than 4 KB or CMP using the Inet Oraxo JDBC Driveror Oracle Databases you must set the streamstolob property value to true

CMP Mapping

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 199/326

or Oracle Databases, you must set the streamstolob property value to true.

For a list o the JDBC drivers currently supported by the Communications Server, see the Sun

GlassFish Communications Server 2.0 Release Notes. For congurations o supported and otherdrivers, see “Congurations or Specic JDBC Drivers” in Sun GlassFish Communications

Server 2.0 Administration Guide.

For automatic mapping, you might need to change the deault BLOB column length or thegenerated schema using the schema-generator-properties element in sun-ejb-jar.xml.See

your database vendor documentation to determine whether you need to speciy the length. Forexample:

<schema-generator-properties>

<property>

<name>Employee.voiceGreeting.jdbc-type</name>

<value>BLOB</value>

</property>

<property>

<name>Employee.voiceGreeting.jdbc-maximum-length</name>

<value>10240</value>

</property>

...

</schema-generator-properties>

Chapter 10 • Using Container-Managed Persistence 199

CLOB Support

Character Large Object (CLOB) is a data type used to store and retrieve very long text elds.CLOBs translate into long strings.

To enable CLOB support in the Communications Server environment, dene a CMP eld o type java.lang.String. I you map the CMP bean to an existing database schema, map the

eld to a column o type CLOB.

To use BLOB or CLOB data types larger than 4 KB or CMP using the Inet Oraxo JDBC Driveror Oracle Databases, you must set the streamstolob property value to true.

For a list o the JDBC drivers currently supported by the Communications Server, see the SunGlassFish Communications Server 2.0 Release Notes. For congurations o supported and otherdrivers, see “Congurations or Specic JDBC Drivers” in Sun GlassFish CommunicationsServer 2.0 Administration Guide.

For automatic mapping, you might need to change the deault CLOB column length or thegenerated schema using the schema-generator-properties element in sun-ejb-jar.xml.Seeyour database vendor documentation to determine whether you need to speciy the length. Forexample:

<schema-generator-properties>

<property>

Automatic Schema Generationor CMP

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 200/326

<name>Employee.resume.jdbc-type</name><value>CLOB</value>

</property>

<property>

<name>Employee.resume.jdbc-maximum-length</name>

<value>10240</value>

</property>

...

</schema-generator-properties>

Automatic Schema Generation or CMPThe automatic schema generation eature provided in the Communications Server denesdatabase tables based on the elds in entity beans and the relationships between the elds. Thisinsulates developers rom many o the database related aspects o development, allowing them

to ocus on entity bean development. The resulting schema is usable as-is or can be given to adatabase administrator or tuning with respect to perormance, security, and so on.

This section addresses the ollowing topics:

■ “Supported Data Types or CMP” on page 201■ “Generation Options or CMP” on page 203

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009200

Note – Automatic schema generation is supported on an all-or-none basis: it expects that notables exist in the database beore it is executed. It is not intended to be used as a tool to generateextra tables or constraints.

Deployment won't ail i all tables are not created, and undeployment won't ail i not all tablesare dropped. This is done to allow you to investigate the problem and x it manually. Youshould not rely on the partially created database schema to be correct or running theapplication.

Supported Data Types or CMP

CMP supports a set o JDBC data types that are used in mapping Java data elds to SQL types.

Supported JDBC data types are as ollows: BIGINT, BIT, BLOB, CHAR, CLOB, DATE,DECIMAL, DOUBLE, FLOAT, INTEGER, NUMERIC, REAL, SMALLINT, TIME,TIMESTAMP, TINYINT, VARCHAR.

The ollowing table contains the mappings o Java types to JDBC types when automaticmapping is used.

TABLE 10–1 Java Type to JDBC Type Mappings orCMP

Automatic Schema Generation or CMP

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 201/326

J yp J yp pp g

Java Type JDBC Type Nullability

boolean BIT No

java.lang.Boolean BIT Yes

byte TINYINT No

java.lang.Byte TINYINT Yes

double DOUBLE No

java.lang.Double DOUBLE Yes

float REAL No

java.lang.Float REAL Yes

int INTEGER No

java.lang.Integer INTEGER Yes

long BIGINT No

java.lang.Long BIGINT Yes

short SMALLINT No

Chapter 10 • Using Container-Managed Persistence 201

TABLE 10–1 Java Type to JDBC Type Mappings or CMP (Continued)

Java Type JDBC Type Nullability

java.lang.Short SMALLINT Yes

java.math.BigDecimal DECIMAL Yes

java.math.BigInteger DECIMAL Yes

char CHAR No

java.lang.Character CHAR Yes

java.lang.String VARCHAR or CLOB Yes

Serializable BLOB Yes

byte[] BLOB Yes

java.util.Date DATE (Oracle only)TIMESTAMP (all other databases)

Yes

java.sql.Date DATE Yes

java.sql.Time TIME Yes

java.sql.Timestamp TIMESTAMP Yes

Automatic Schema Generationor CMP

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 202/326

Note – Java types assigned to CMP elds must be restricted to Java primitive types, JavaSerializable types, java.util.Date, java.sql.Date, java.sql.Time, orjava.sql.Timestamp. An entity bean local interace type (or a collection o such) can be thetype o a CMR eld.

The ollowing table contains the mappings o JDBC types to database vendor-specic typeswhen automatic mapping is used. For a list o the JDBC drivers currently supported by theCommunications Server, see the Sun GlassFish Communications Server 2.0 Release Notes. Forcongurations o supported and other drivers, see“Congurations or Specic JDBC Drivers”in Sun GlassFish Communications Server 2.0 Administration Guide.

TABLE 10–2 Mappings o JDBCTypes to Database Vendor Specic Types or CMP

JDBCType

JavaDB, Derby,

CloudScape Oracle DB2 Sybase ASE 12.5 MS-SQL Server

BIT SMALLINT SMALLINT SMALLINT TINYINT BIT

TINYINT SMALLINT SMALLINT SMALLINT TINYINT TINYINT

SMALLINT SMALLINT SMALLINT SMALLINT SMALLINT SMALLINT

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009202

TABLE 10–2 Mappings o JDBC Types to Database Vendor Specic Types or CMP (Continued)

JDBCTypeJavaDB, Derby,CloudScape Oracle DB2 Sybase ASE 12.5 MS-SQL Server

INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER

BIGINT BIGINT NUMBER BIGINT NUMERIC NUMERIC

REAL REAL REAL FLOAT FLOAT REAL

DOUBLE DOUBLE PRECISION DOUBLE PRECISION DOUBLE DOUBLE PRECISION FLOAT

DECIMAL(p,s) DECIMAL(p,s) NUMBER(p,s) DECIMAL(p,s) DECIMAL(p,s) DECIMAL(p,s)

VARCHAR VARCHAR VARCHAR2 VARCHAR VARCHAR VARCHAR

DATE DATE DATE DATE DATETIME DATETIME

TIME TIME DATE TIME DATETIME DATETIME

TIMESTAMP TIMESTAMP TIMESTAMP(9) TIMESTAMP DATETIME DATETIME

BLOB BLOB BLOB BLOB IMAGE IMAGE

CLOB CLOB CLOB CLOB TEXT NTEXT

Generation Options or CMP

Automatic Schema Generation or CMP

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 203/326

p

Deployment descriptor elements or asadmin command line options can control automaticschema generation by the ollowing:

■ Creating tables during deployment■ Dropping tables during undeployment■ Dropping and creating tables during redeployment■ Speciying the database vendor■

Speciying that table names are unique■ Speciying type mappings or individual CMP elds

Note – Beore using these options, make sure you have a properly congured CMP resource. See“Conguring the CMP Resource” on page 207.

For a read-only bean, do not create the database schema during deployment. Instead, work withyour database administrator to populate the data into the tables. See“Using Read-Only Beans”on page 186.

Automatic schema generation is not supported or beans with version column consistency checking. Instead, work with your database administrator to create the schema and add therequired triggers. See “Version Column Consistency Checking” on page 208.

Chapter 10 • Using Container-Managed Persistence 203

The ollowing optional data subelements o the cmp-resource element in the sun-ejb-jar.xml

le control the automatic creation o database tables at deployment. For more inormationabout the cmp-resource element, see “cmp-resource” in Sun GlassFish Communications

Server 2.0 Application Deployment Guide and “Conguring the CMP Resource” on page 207.

TABLE 10–3 The sun-ejb-jar.xml Generation Elements

Element Deault Description

create-tables-at-deploy false I true, causes database tables to be created or beans that are automatically mapped by the EJB container. I false, does not create tables.

drop-tables-at-undeploy false I true, causes database tables that were automatically created when the bean(s)were lastdeployed to be droppedwhen the bean(s) are undeployed. I false, doesnot drop tables.

database-vendor-name none Species the name o the database vendor orwhich tables are created. Allowed

 values are javadb, db2, mssql, oracle, postgresql, pointbase, derby (also orCloudScape), and sybase, case-insensitive.

I no value is specied, a connection is made to the resource specied by thejndi-name subelement o the cmp-resource element in the sun-ejb-jar.xml le,and the database vendor name is read. I the connection cannot be established, ori the value is not recognized, SQL-92 compliance is presumed.

schema-generator-properties none Species eld-specic column attributes in property subelements. Each property name is o the ollowing ormat:

Automatic Schema Generationor CMP

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 204/326

g

bean-name. feld-name.attribute

For example:

Employee.firstName.jdbc-type

Also allows you to setthe use-unique-table-names property. I true, thisproperty species that generated table names are unique within each applicationserver domain. The deault is false.

Forurther inormation and an example, see “schema-generator-properties” inSun GlassFish Communications Server 2.0 Application Deployment Guide.

The ollowing options o the asadmin deploy or asadmin deploydir command control theautomatic creation o database tables at deployment.

TABLE 10–4 The asadmin deploy and asadmin deploydir Generation Options or CMP

Option Deault Description

--createtables none I  true, causes database tables to be created or beans that need them. I false, doesnot create tables. I not specied, the value o the create-tables-at-deploy

attribute in sun-ejb-jar.xml is used.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009204

TABLE 10–4 The asadmin deploy and asadmin deploydir Generation Options or CMP (Continued)

Option Deault Description

--dropandcreatetables none I  true, and i tables were automatically created when this application was lastdeployed, tables rom the earlierdeployment are dropped and resh onesarecreated.

I true, and i tables were not automatically created when this application was last

deployed, no attempt is made to drop any tables. I tables with the same names asthose that would have beenautomatically created are ound, the deploymentproceeds, but a warning indicates that tables could not be created.

I false, settings o create-tables-at-deploy or drop-tables-at-undeploy inthe sun-ejb-jar.xml le are overridden.

--uniquetablenames none I  true, species that table names are unique within each application server domain.I not specied, the value o the use-unique-table-names property insun-ejb-jar.xml is used.

--dbvendorname none Species the name o the database vendor or whichtables are created. Allowed values are javadb, db2, mssql, oracle, postgresql, pointbase, derby (also orCloudScape), and sybase, case-insensitive.

I not specied, the value o the database-vendor-name attribute insun-ejb-jar.xml is used.

I no value is specied, a connection is made to the resource specied by thejndi-name subelement o the cmp-resource element in the sun-ejb-jar.xml le,

Automatic Schema Generation or CMP

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 205/326

and the database vendor name is read. I the connection cannot be established, or i the value is not recognized, SQL-92 compliance is presumed.

I one or more o the beans in the module are manually mapped and you use any o the asadmin

deploy or asadmin deploydir options, the deployment is not harmed in any way, but theoptions have no efect, and a warning is written to the server log.

The ollowing options o the asadmin undeploy command control the automatic removal o database tables at undeployment.

TABLE 10–5 The asadmin undeploy Generation Options or CMP

Option Deault Description

--droptables none I  true, causes database tables that were automatically created when the bean(s) were lastdeployed to be droppedwhen the bean(s) are undeployed. I false, does notdrop tables.

I not specied, the value o the drop-tables-at-undeploy attribute in sun-ejb-jar.xml isused.

For more inormation about the asadmin deploy, asadmin deploydir, and asadmin undeploy

commands, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Chapter 10 • Using Container-Managed Persistence 205

When command line and sun-ejb-jar.xml options are both specied, the asadmin optionstake precedence.

The asant tasks sun-appserv-deploy and sun-appserv-undeploy are equivalent to asadmin

deploy and asadmin undeploy, respectively. These asant tasks also override thesun-ejb-jar.xml options. For details, see Chapter 3, “The asant Utility.”

Schema CaptureThis section addresses the ollowing topics:

■ “Automatic Database Schema Capture” on page 206■ “Using the capture-schema Utility” on page 206

Automatic Database Schema Capture

You can congure a CMP bean in Communications Server to automatically capture thedatabase metadata and save it in a .dbschema le during deployment. I thesun-cmp-mappings.xml le contains an empty <schema/> entry, the cmp-resource entry in thesun-ejb-jar.xml le is used to get a connection to the database, and automatic generation o the schema is perormed.

Schema Capture

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 206/326

Note – Beore capturing the database schema automatically, make sure you have a properly congured CMP resource. See “Conguring the CMP Resource” on page 207.

Using the capture-schema Utility

You can use the capture-schema command to manually generate the database metadata(.dbschema) le. For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

The capture-schema utility does not modiy the schema in any way. Its only purpose is toprovide the persistence engine with inormation about the structure o the database (theschema).

Keep the ollowing in mind when using the capture-schema command:

■ Thenameoa .dbschema le must be unique across all deployed modules in a domain.

■ I more than one schema is accessible or the schema user, more than one table with thesame name might be captured i the -schemaname parameter o capture-schema is not set.

■ The schema name must be upper case.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009206

■ Table names in databases are case-sensitive. Make sure that the table name matches thename in the database.

■ PostgreSQL databases internally convert all names to lower case. Beore running thecapture-schema command on a PostgreSQL database, make sure table and column namesare lower case in the sun-cmp-mappings.xml le.

■ An Oracle database user running the capture-schema command needs ANALYZE ANY

TABLE privileges i that user does not own the schema. These privileges are granted to theuser by the database administrator.

Confguring the CMP ResourceAn EJB module that contains CMP beans requires the JNDI name o a JDBC resource in thejndi-name subelement o the cmp-resource element in the sun-ejb-jar.xml le. SetPersistenceManagerFactory properties as properties o the cmp-resource element in thesun-ejb-jar.xml le. See “cmp-resource” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

In the Admin Console, open the Resources component, then select JDBC. Click the Help buttonin the Admin Console or inormation on creating a new JDBC resource.

For a list o the JDBC drivers currently supported by the Communications Server, see the Sun

GlassFish Communications Server 2 0 Release Notes F ti pp t d d th

Perormance-Related Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 207/326

GlassFish Communications Server 2.0 Release Notes. For congurations o supported and otherdrivers, see “Congurations or Specic JDBC Drivers” in Sun GlassFish CommunicationsServer 2.0 Administration Guide.

For example, i the JDBC resource has the JNDI name jdbc/MyDatabase, set the CMP resourcein the sun-ejb-jar.xml le as ollows:

<cmp-resource>

<jndi-name>jdbc/MyDatabase</jndi-name></cmp-resource>

Perormance-Related FeaturesThe Communications Server provides the ollowing eatures to enhance perormance or allow more ne-grained data checking. These eatures are supported only or entity beans with

container managed persistence.

■ “Version Column Consistency Checking” on page 208■ “Relationship Preetching” on page 208■ “Read-Only Beans” on page 209■ “Deault Fetch Group Flags” on page 210

Chapter 10 • Using Container-Managed Persistence 207

Note – Use o any o these eatures results in a non-portable application.

Version Column Consistency Checking

The version consistency eature saves the bean state at rst transactional access and caches it

between transactions. The state is copied rom the cache instead o being read rom thedatabase. The bean state is veried by primary key and version column values at ush orcustom queries (or dirty instances only) and at commit (or clean and dirty instances).

▼ To UseVersion Consistency

Create theversioncolumn in theprimary table.

Give theversion column a numeric data type.

Provideappropriate update triggerson the version column.

These triggers must increment the version column on each update o the specied row.

Speciy the version column.

This is specied in the check-version-of-accessed-instances subelement o the

consistency element in the sun-cmp-mappings xml le See “consistency” in Sun GlassFish

1

2

3

4

Perormance-Related Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 208/326

consistency element in the sun cmp mappings.xml le. See consistency in Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

MaptheCMP bean to an existing schema.

Automatic schema generation is not supported or beans with version column consistency checking. Instead, work with your database administrator to create the schema and add therequired triggers.

Relationship Preetching

In many cases when an entity bean’s state is etched rom the database, its relationship elds arealways accessed in the same transaction. Relationship preetching saves database round trips by etching data or an entity bean and those beans reerenced by its CMR elds in a singledatabase round trip.

To enable relationship preetching or a CMR eld, use the default subelement o thefetched-with element in the sun-cmp-mappings.xml le. By deault, these CMR elds arepreetched whenever findByPrimaryKey or a custom nder is executed or the entity, or whenthe entity is navigated to rom a relationship. (Recursive preetching is not supported, because itdoes not usually enhance perormance.) See“etched-with” in Sun GlassFish CommunicationsServer 2.0 Application Deployment Guide.

5

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009208

To disable preetching or specic custom nders, use the prefetch-disabled element in thesun-ejb-jar.xml le. See “preetch-disabled” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Multilevel relationship preetching is supported or CMP 2.1 entity beans. To enable multilevelrelationship preetching, set the ollowing property using the asadmin create-jvm-options

command:

asadmin create-jvm-options -Dcom.sun.jdo.spi.persistence.support.sqlstore.MULTILEVEL_PREFETCH=true

Read-Only Beans

Another eature that the Communications Server provides is the read-only bean, an entity beanthat is never modied by an EJB client. Read-only beans avoid database updates completely.

Note – Read-only beans are specic to the Communications Server and are not part o theEnterprise JavaBeans Specication, v2.1. Use o this eature or an EJB 2.1 bean results in anon-portable application.

A read-only bean can be used to cache a database entry that is requently accessed but rarely 

updated (externally by other beans) When the data that is cached by a read-only bean isupdated by another bean the read only bean can be notied to reresh its cached data

Perormance-Related Features

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 209/326

updated (externally by other beans). When the data that is cached by a read only bean isupdated by another bean, the read-only bean can be notied to reresh its cached data.

The Communications Server provides a number o ways by which a read-only bean’s state canbe rereshed. By setting the refresh-period-in-seconds element in the sun-ejb-jar.xml leand the trans-attribute element (or @TransactionAttribute annotation) in theejb-jar.xml le, it is easy to congure a read-only bean that is one o the ollowing:

■ Always rereshed

■ Periodically rereshed■ Never rereshed■ Programmatically rereshed

Access to CMR elds o read-only beans is not supported. Deployment will succeed, but anexception will be thrown at runtime i a get or set method is invoked.

Read-only beans are best suited or situations where the underlying data never changes, orchanges inrequently. For urther inormation and usage guidelines, see“Using Read-Only Beans” on page 186.

Chapter 10 • Using Container-Managed Persistence 209

Deault Fetch Group FlagsUsing the ollowing ags can improve perormance.

Setting -DAllowManagedFieldsInDefaultFetchGroup=true allows CMP elds that by deaultcannot be placed into the deault etch group to be loaded along with all other elds that areetched when the CMP state is loaded into memory. These could be multiple elds mapped to

the same column in the database table, or example, an instance eld and a CMR. By deault thisagissetto false.

For additional inormation, see “level” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide.

Setting -DAllowMediatedWriteInDefaultFetchGroup species how updated CMP elds arewritten back to the database. I the ag is false, all elds in the CMP bean are written back tothe database i at least one eld in the deault etch group has been changed in a transaction. I 

the ag is true, only elds modied by the bean are written back to the database. Speciyingtrue can improve perormance, particularly on database tables with many columns that havenot been updated. By deault this ag is set to false.

To set one o these ags, use the asadmin create-jvm-options command. For example:

asadmin create-jvm-options --user adminuser -DAllowManagedFieldsInDefaultFetchGroup=true

Confguring Queries or 1 1 Finders

Deault Fetch GroupFlags

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 210/326

Confguring Queries or 1.1 FindersThis section contains the ollowing topics:

■ “About JDOQL Queries” on page 210■ “Query Filter Expression” on page 211■ “Query Parameters” on page 212■ “Query Variables” on page 212■ “JDOQL Examples” on page 213

About JDOQL QueriesThe Enterprise JavaBeans Specication, v1.1 does not speciy the ormat o the nder methoddescription. The Communications Server uses an extension o Java Data Objects Query Language (JDOQL) queries to implement nder and selector methods. You can speciy the

ollowing elements o the underlying JDOQL query:■ Filter expression - A Java-like expression that species a condition that each object

returned by the query must satisy. Corresponds to the WHERE clause in EJB QL.

■ Query parameterdeclaration - Species the name and the type o one or more query inputparameters. Follows the syntax or ormal parameters in the Java language.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009210

■ Query variable declaration - Species the name and type o one or more query variables.Follows the syntax or local variables in the Java language. A query lter might use query 

 variables to implement joins.

■ Query orderingdeclaration - Species the ordering expression o the query. Correspondsto the ORDER BY clause o EJB QL.

The Communications Server specic deployment descriptor (sun-ejb-jar.xml) provides the

ollowing elements to store the EJB 1.1 nder method settings:

query-filter

query-params

query-variables

query-ordering

The bean developer uses these elements to construct a query. When the nder method that uses

these elements executes, the values o these elements are used to execute a query in the database.The objects rom the JDOQL query result set are converted into primary key instances to bereturned by the EJB 1.1 ejbFind method.

The JDO specication, JSR12(http://jcp.org/en/jsr/detail?id=12 ), provides acomprehensive description o JDOQL. The ollowing inormation summarizes the elementsused to dene EJB 1.1 nders.

Query Filter Expression

ConfguringQueriesor 1.1 Finders

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 211/326

Query Filter ExpressionThe lter expression is a String containing a Boolean expression evaluated or each instance o the candidate class. I the lter is not specied, it deaults to true. Rules or constructing validexpressions ollow the Java language, with the ollowing diferences:

■ Equality and ordering comparisons between primitives and instances o wrapper classes are valid.

■ Equality and ordering comparisons o Date elds and Date parameters are valid.■ Equality and ordering comparisons o String elds and String parameters are valid.

■ White space (non-printing characters space, tab, carriage return, and line eed) is aseparator and is otherwise ignored.

■ The ollowing assignment operators are not supported.

■ Comparison operators such as =, +=, and so on■ Pre- and post-increment■ Pre- and post-decrement

■ Methods, including object construction, are not supported, except or these methods.

Collection.contains(Object o)

Collection.isEmpty()

Chapter 10 • Using Container-Managed Persistence 211

String.startsWith(String s)

String.endsWith(String e)

In addition, the Communications Server supports the ollowing nonstandard JDOQLmethods.

String.like(String pattern)

String.like(String pattern, char escape)

String.substring(int start, int length)

String.indexOf(String str)

String.indexOf(String str, int start)

String.length()

Math.abs(numeric n)

Math.sqrt(double d)

■ Navigation through a null-valued eld, which throws a NullPointerException, is treated asi the sub-expression returned false.

Note – Comparisons between oating point values are by nature inexact. Thereore, equality comparisons (== and !=) with oating point values should be used with caution. Identiers inthe expression are considered to be in the name space o the candidate class, with the addition o declared parameters and variables. As in the Java language,this is a reserved word, and reersto the current instance being evaluated.

The ollowing expressions are supported.

ConfguringQueries or 1.1 Finders

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 212/326

g p pp

■ Relational operators (==, !=, >, <, >=, <=)■ Boolean operators (&, &&, |, ||, ~, !)■ Arithmetic operators (+, -, *, /)■ String concatenation, only or String + String■ Parentheses to explicitly mark operator precedence■ Cast operator■

Promotion o numeric operands or comparisons and arithmetic operationsThe rules or promotion ollow the Java rules extended by BigDecimal, BigInteger, and numericwrapper classes. See the numeric promotions o the Java language specication.

Query ParametersThe parameter declaration is a String containing one or more parameter type declarations

separated by commas. This ollows the Java syntax or method signatures.

QueryVariablesThe type declarations ollow the Java syntax or local variable declarations.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009212

 JDOQL ExamplesThis section provides a ew query examples.

Example 1

The ollowing query returns all players called Michael. It denes a lter that compares the name

eld with a string literal:

name == "Michael"

The finder element o the sun-ejb-jar.xml le looks like this:

<finder>

<method-name>findPlayerByName</method-name>

<query-filter>name == "Michael"</query-filter>

</finder>

Example 2

This query returns all products in a specied price range. It denes two query parameters whichare the lower and upper bound or the price: double low, double high. The lter compares thequery parameters with the price eld:

low < price && price < high

Q d i i i di

ConfguringQueriesor 1.1 Finders

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 213/326

Query ordering is set to price ascending.

The finder element o the sun-ejb-jar.xml le looks like this:

<finder>

<method-name>findInRange</method-name>

<query-params>double low, double high</query-params>

<query-filter>low &lt; price &amp;&amp; price &lt high</query-filter>

<query-ordering>price ascending</query-ordering>

</finder>

Example 3

This query returns all players having a higher salary than the player with the specied name. Itdenes a query parameter or the name java.lang.String name. Furthermore, it denes a

 variable to which the player’s salary is compared. It has the type o the persistence capable class

that corresponds to the bean:

mypackage.PlayerEJB_170160966_JDOState player

The lter compares the salary o the current player denoted by the this keyword with the salary o the player with the specied name:

Chapter 10 • Using Container-Managed Persistence 213

(this.salary > player.salary) && (player.name == name)

The finder element o the sun-ejb-jar.xml le looks like this:

<finder>

<method-name>findByHigherSalary</method-name>

<query-params>java.lang.String name</query-params>

<query-filter>

(this.salary &gt; player.salary) &amp;&amp; (player.name == name)

</query-filter>

<query-variables>

mypackage.PlayerEJB_170160966_JDOState player

</query-variables>

</finder>

CMP Restrictions and OptimizationsThis section discusses restrictions and perormance optimizations that pertain to using CMP.

■ “Disabling ORDER BY Validation” on page 214■ “Setting the Heap Size on DB2” on page 215■ “Eager Loading o Field State” on page 215■ “Restrictions on Remote Interaces” on page 215■ “PostgreSQL Case Insensitivity” on page 215■ “No Support or lock-when-loaded on Sybase” on page 216■ “Sybase Finder Limitation” on page 216

CMP Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 214/326

■ Sybase Finder Limitation on page 216■ “Date and Time Fields” on page 216■ “Set RECURSIVE_TRIGGERS to false on MSSQL” on page 217■ “MySQL Database Restrictions” on page 217

Disabling ORDER BYValidationEJB QL as dened in the EJB 2.1 Specication denes certain restrictions or the SELECT clauseo an ORDER BY query (see section 11.2.8 ORDER BY Clause). This ensures that a query doesnot order by a eld that is not returned by the query. By deault, the EJB QL compiler checks theabove restriction and throws an exception i the query does not conorm.

However, some databases support SQL statements with an ORDER BY column that is notincluded in the SELECT clause. To disable the validation o the ORDER BY clause against theSELECT clause, set the DISABLE_ORDERBY_VALIDATION JVM option as ollows:

asadmin create-jvm-options --user adminuser

-Dcom.sun.jdo.spi.persistence.support.ejb.ejbqlc.DISABLE_ORDERBY_VALIDATION=true

The DISABLE_ORDERBY_VALIDATION option is set to false by deault. Setting it to true results ina non-portable module or application.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009214

Setting the Heap Size on DB2

On DB2, the database conguration parameter APPLHEAPSZ determines the heap size. I you areusing the Sun GlassFish or DataDirect database driver, set this parameter to at least 2048 orCMP. For more inormation, see http://publib.boulder.ibm.com/

infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/opt/tsbp2024.htm .

Eager Loading o Field State

By deault, the EJB container loads the state or all persistent elds (excluding relationship,BLOB, and CLOB elds) beore invoking the ejbLoad method o the abstract bean. Thisapproach might not be optimal or entity objects with large state i most business methodsrequire access to only parts o the state.

Use the fetched-with element in sun-cmp-mappings.xml or elds that are used inrequently.See “etched-with” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

Restrictions on Remote Interaces

The ollowing restrictions apply to the remote interace o an EJB 2.1 bean that uses CMP:

■ Do not expose the get and set methods or CMR elds or the persistence collection classes

that are used in container-managed relationships through the remote interace o the bean.H t th t d t th d th t d t th CMP ld

CMP Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 215/326

However, you are ree to expose the get and set methods that correspond to the CMP eldso the entity bean through the bean’s remote interace.

■ Do not expose the container-managed collection classes that are used or relationshipsthrough the remote interace o the bean.

■ Do not expose local interace types or local home interace types through the remoteinterace or remote home interace o the bean.

Dependent value classes can be exposed in the remote interace or remote home interace, andcan be included in the client EJB JAR le.

PostgreSQL Case Insensitivity

Case-sensitive behavior cannot be achieved or PostgresSQL databases. PostgreSQL databases

internally convert all names to lower case, which makes the ollowing workarounds necessary:■ In the CMP 2.1 runtime, PostgreSQL table and column names are not quoted, which makes

these names case insensitive.

■ Beore running the capture-schema command on a PostgreSQL database, make sure tableand column names are lower case in the sun-cmp-mappings.xml le.

Chapter 10 • Using Container-Managed Persistence 215

No Support or lock-when-loaded on Sybase

For EJB 2.1 beans, the lock-when-loaded consistency level is implemented by placing updatelocks on the data corresponding to a bean when the data is loaded rom the database. There isno suitable mechanism available on Sybase databases to implement this eature. Thereore, thelock-when-loaded consistency level is not supported on Sybase databases. See“consistency” inSun GlassFish Communications Server 2.0 Application Deployment Guide.

Sybase Finder Limitation

I a nder method with an input greater than 255 characters is executed and the primary key column is mapped to a VARCHAR column, Sybase attempts to convert type VARCHAR to typeTEXT and generates the ollowing error:

com.sybase.jdbc2.jdbc.SybSQLException: Implicit conversion from datatype

’TEXT’ to ’VARCHAR’ is not allowed. Use the CONVERT function to run this

query.

To avoid this error, make sure the nder method input is less than 255 characters.

Date and Time FieldsI ldt i J d t ti t (j il D j l D j l Ti

CMP Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 216/326

IaeldtypeisaJavadateortimetype(java.util.Date, java.sql.Date, java.sql.Time,java.sql.Timestamp), make sure that the eld value exactly matches the value in the database.

For example, the ollowing code uses a java.sql.Date type as a primary key eld:

java.sql.Date myDate = new java.sql.Date(System.currentTimeMillis())

BeanA.create(myDate, ...);

For some databases, this code results in only the year, month, and date portion o the eld valuebeing stored in the database. Later i the client tries to nd this bean by primary key as ollows,the bean is not ound in the database because the value does not match the one that is stored inthe database.

myBean = BeanA.findByPrimaryKey(myDate);

Similar problems can happen i the database truncates the timestamp value while storing it, or i a custom query has a date or time value comparison in its WHERE clause.

For automatic mapping to an Oracle database, elds o type java.util.Date, java.sql.Date,and java.sql.Time are mapped to Oracle’s DATE data type. Fields o typejava.sql.Timestamp are mapped to Oracle’s TIMESTAMP(9) data type.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009216

Set RECURSIVE_TRIGGERS to false on MSSQL

For version consistency triggers on MSSQL, the property RECURSIVE_TRIGGERS must be set tofalse, which is the deault. I set to true, triggers throw a java.sql.SQLException.

Set this property as ollows:

EXEC sp_dboption ’database-name’, ’recursive triggers’, ’FALSE’go

You can test this property as ollows:

SELECT DATABASEPROPERTYEX(’database-name’, ’IsRecursiveTriggersEnabled’)

go

MySQL Database Restrictions

The ollowing restrictions apply when you use a MySQL database with the CommunicationsServer or persistence.

■ MySQL treats int1 and int2 as reserved words. I you want to dene int1 and int2 as eldsin your table, use ‘int1‘ and ‘int2‘ eld names in your SQL le.

■ When VARCHAR elds get truncated, a warning is displayed instead o an error. To get anerror message, start the MySQL database in strict SQL mode.

CMP Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 217/326

error message, start the MySQL database in strict SQL mode.

■ The order o elds in a oreign key index must match the order in the explicitly createdindex on the primary table.

■ The CREATE TABLE syntax in the SQL le must end with the ollowing line.

) Engine=InnoDB;

InnoDB provides MySQL with a transaction-sae (ACID compliant) storage engine havingcommit, rollback, and crash recovery capabilities.

■ Fora FLOAT type eld, the correct precision must be dened. By deault, MySQL uses ourbytes to store a FLOAT type that does not have an explicit precision denition. For example,this causes a number such as 12345.67890123 to be rounded of to 12345.7 during anINSERT. To prevent this, speciy FLOAT(10,2) in the DDL le, which orces the database touse an eight-byte double-precision column. For more inormation, see

http://dev.mysql.com/doc/mysql/en/numeric-types.html .■ To use || as the string concatenation symbol, start the MySQL server with the

--sql-mode="PIPES_AS_CONCAT" option. For more inormation, seehttp://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html andhttp://dev.mysql.com/doc/mysql/en/ansi-mode.html .

Chapter 10 • Using Container-Managed Persistence 217

■ MySQL always starts a new connection when autoCommit==true is set. This ensures thateach SQL statement orms a single transaction on its own. I you try to rollback or commitan SQL statement, you get an error message.

javax.transaction.SystemException: java.sql.SQLException:

Can’t call rollback when autocommit=true

javax.transaction.SystemException: java.sql.SQLException:Error open transaction is not closed

To resolve this issue, add relaxAutoCommit=true to the JDBC URL. For more inormation,see http://forums.mysql.com/read.php?39,31326,31404 .

■ Change the trigger create ormat rom the ollowing:

CREATE TRIGGER T_UNKNOWNPKVC1

BEFORE UPDATE ON UNKNOWNPKVC1FOR EACH ROW

WHEN (NEW.VERSION = OLD.VERSION)

BEGIN

:NEW.VERSION := :OLD.VERSION + 1;

END;

/

To the ollowing:

DELIMITER |

CREATE TRIGGER T UNKNOWNPKVC1

CMP Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 218/326

CREATE TRIGGER T_UNKNOWNPKVC1

BEFORE UPDATE ON UNKNOWNPKVC1

FOR EACH ROW

WHEN (NEW.VERSION = OLD.VERSION)

BEGIN

:NEW.VERSION := :OLD.VERSION + 1;

END

|DELIMITER ;

For more inormation, see http://dev.mysql.com/doc/mysql/en/create-trigger.html .

■ MySQL does not allow a DELETE on a row that contains a reerence to itsel. Here is anexample that illustrates the issue.

create table EMPLOYEE (

empId int NOT NULL,salary float(25,2) NULL,

mgrId int NULL,

PRIMARY KEY (empId),

FOREIGN KEY (mgrId) REFERENCES EMPLOYEE (empId)

) ENGINE=InnoDB;

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009218

insert into Employee values (1, 1234.34, 1);

delete from Employee where empId = 1;

This example ails with the ollowing error message.

ERROR 1217 (23000): Cannot delete or update a parent row:

a foreign key constraint fails

To resolve this issue, change the table creation script to the ollowing:

create table EMPLOYEE (

empId int NOT NULL,

salary float(25,2) NULL,

mgrId int NULL,

PRIMARY KEY (empId),

FOREIGN KEY (mgrId) REFERENCES EMPLOYEE (empId)ON DELETE SET NULL

) ENGINE=InnoDB;

insert into Employee values (1, 1234.34, 1);

delete from Employee where empId = 1;

This can be done only i the oreign key eld is allowed to be null. For more inormation, seehttp://bugs.mysql.com/bug.php?id=12449 and http://dev.mysql.com/doc/mysql/

en/innodb-foreign-key-constraints.html .■ When an SQL script has oreign key constraints dened capture-schema ails to capture

CMP Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 219/326

■ When an SQL script has oreign key constraints dened, capture schema ails to capturethe table inormation correctly. To work around the problem, remove the constraints andthen run capture-schema. Here is an example that illustrates the issue.

CREATE TABLE ADDRESSBOOKBEANTABLE (ADDRESSBOOKNAME VARCHAR(255)

NOT NULL PRIMARY KEY,

CONNECTEDUSERS BLOB NULL,

OWNER VARCHAR(256),

FK_FOR_ACCESSPRIVILEGES VARCHAR(256),

CONSTRAINT FK_ACCESSPRIVILEGE FOREIGN KEY (FK_FOR_ACCESSPRIVILEGES)

REFERENCES ACCESSPRIVILEGESBEANTABLE (ROOT)

) ENGINE=InnoDB;

To resolve this issue, change the table creation script to the ollowing:

CREATE TABLE ADDRESSBOOKBEANTABLE (ADDRESSBOOKNAME VARCHAR(255)NOT NULL PRIMARY KEY,

CONNECTEDUSERS BLOB NULL,

OWNER VARCHAR(256),

FK_FOR_ACCESSPRIVILEGES VARCHAR(256)

) ENGINE=InnoDB;

Chapter 10 • Using Container-Managed Persistence 219

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 220/326

220

Developing Java Clients

This chapter describes how to develop, assemble, and deploy Java clients in the ollowing

sections:

■ “Introducing the Application Client Container” on page 221■ “Developing Clients Using the ACC” on page 223

Introducing the Application Client ContainerThe Application Client Container (ACC) includes a set o Java classes, libraries, and other les

that are required or and distributed with Java client programs that execute in their own JavaVirtual Machine (JVM). The ACC manages the execution o Java EE application client

11C H A P T E R 1 1

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 221/326

components (application clients), which are used to access a variety o Java EE services (such asJMS resources, EJB components, web services, security, and so on.) rom a JVM outside the SunGlassFish Communications Server.

The ACC communicates with the Communications Server using RMI-IIOP protocol andmanages the details o RMI-IIOP communication using the client ORB that is bundled with it.

Compared to other Java EE containers, the ACC is lightweight.

For inormation about debugging application clients, see “Application Client Debugging” onpage 71.

Note – Interoperability between application clients and Communications Servers running underdiferent major versions is not supported.

ACC Security

The ACC determines when authentication is needed. This typically occurs when the clientreers to an EJB component or when annotations in the client's main class trigger injection

221

which, in turn, requires contact with the Communications Server's naming service. Toauthenticate the end user, the ACC prompts or any required inormation, such as a usernameand password. The ACC itsel provides a very simple dialog box to prompt or and read these

 values.

The ACC integrates with the Communications Server’s authentication system. It also supportsSSL (Secure Socket Layer)/IIOP i congured and when necessary; see“Using RMI/IIOP Over

SSL” on page 232.

You can provide an alternate implementation to gather authentication inormation, tailored tothe needs o the application client. To do so, include the class to perorm these duties in theapplication client and identiy the ully-qualied name o this class in thecallback-handler

element o the application-client.xml descriptor or the client. The ACC uses this classinstead o its deault class or asking or and reading the authentication inormation. The classmust implement the javax.security.auth.callback.CallbackHandler interace. See the

Java EE specication, section 9.2, Application Clients: Security , or more details.

Application clients can use “Programmatic Login” on page 107.

For more inormation about security or application clients, see the Java EE 5 Specication,Section EE.9.7, “Java EE Application Client XML Schema.”

ACC NamingThe client container enables the application clients to use the Java Naming and Directory

Introducing the Application Client Container

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 222/326

The client container enables the application clients to use the Java Naming and Directory Interace (JNDI) to look up Java EE services (such as JMS resources, EJB components, webservices, security, and so on.) and to reerence congurable parameters set at the time o deployment.

ACC Annotation

Annotation is supported or application clients. For more inormation, see section 9.4 o theJava EE 5 Specication and “Java EE Standard Annotation” in Sun GlassFish CommunicationsServer 2.0 Application Deployment Guide.

 Java Web StartJava Web Start allows your application client to be easily launched and automatically downloaded and updated. It is enabled or all application clients by deault. For moreinormation, see “Using Java Web Start” on page 226.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009222

Developing Clients Using the ACCThis section describes the procedure to develop, assemble, and deploy client applications usingthe ACC. This section describes the ollowing topics:

■ “To Access an EJB Component From an Application Client” on page 223■ “To Access a JMS Resource From an Application Client” on page 225■

“Using Java Web Start” on page 226■ “Running an Application Client Using the appclient Script” on page 232■ “Using the package-appclient Script” on page 232■ “The client.policy File” on page 232■ “Using RMI/IIOP Over SSL” on page 232■ “Connecting to a Remote EJB Module Through a Firewall” on page 234

▼ To Access an EJB Component From an ApplicationClient

In your client code, reerence theEJB component by using an @EJB annotation or by looking up

the JNDI nameas defned in the ejb-jar.xml fle.

For more inormation about annotations in application clients, see section 9.4 o the Java EE 5Specication.

For more inormation about naming and lookups, see “Accessing the Naming Context” onpage 277.

1

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 223/326

I load balancing is enabled as in Step 7 and the EJB components being accessed are in adiferent cluster, the endpoint list must be included in the lookup, as ollows:

corbaname:host1: port1,host2: port2,.../NameService#ejb/ jndi-name

Defne the @EJB annotations or the ejb-ref elements in the application-client.xml fle.

Defne the corresponding ejb-ref elements in the sun-application-client.xml fle.

For more inormation on the application-client.xml le, see the Java EE 5 Specication,Section EE.9.7, “Java EE Application Client XML Schema.”

For more inormation on the sun-application-client.xml le, see “Thesun-application-client.xml le” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide. For a general explanation o how to map JNDI names using reerenceelements, see “Mapping Reerences” on page 282.

Deploy the application client and EJB component together in an application.

For more inormation on deployment, see theSun GlassFish Communications Server 2.0 Application Deployment Guide. To get the client JAR le, use the --retrieve option o theasadmin deploy command.

2

3

Chapter 11 • Developing Java Clients 223

To retrieve the stubs and ties whether or not you requested their generation during deployment,use the asadmin get-client-stubs command. For details, see the Sun GlassFish

Communications Server 2.0 Reerence Manual .

Ensurethat theclient JAR fle includes theollowing fles:

■ A Java class to access the bean.

■ application-client.xml - (optional) Java EE application client deployment descriptor.For inormation on the application-client.xml le, see the Java EE 5 Specication,Section EE.9.7, “Java EE Application Client XML Schema.”

■ sun-application-client.xml - (optional) Communications Server specic clientdeployment descriptor. For inormation on the sun-application-client.xml le, see“The sun-application-client.xml le” in Sun GlassFish Communications Server 2.0

 Application Deployment Guide.

■ The MANIFEST.MF le. This le contains a reerence to the main class, which states thecomplete package prex and class name o the Java client.

Prepare theclient machine. This step is notneeded or Java Web Start.

I you are using the appclient script, either package the application client to run on a remoteclient system using the package-appclient script, or copy the ollowing JAR les to the clientmachine manually and include them in the classpath on the client side:

■ appserv-rt.jar - available at as-install /lib■ javaee.jar - available at as-install /lib

■ The client JAR le

4

5

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 224/326

■ The client JAR le

For more inormation, see “Using the package-appclient Script” on page 232.

To access EJB componentsthat are residing in a remote system, make theollowing changes to

the sun-acc.xml fle. This step is notneeded or Java Web Start.

■ Dene the target-server element’s address attribute to reerence the remote servermachine. See “target-server” in Sun GlassFish Communications Server 2.0 Application

Deployment Guide.

■ Dene the target-server element’s port attribute to reerence the ORB port on the remoteserver.

This inormation can be obtained rom the domain.xml le on the remote system. For more

inormation on domain.xml le, see the Sun GlassFish Communications Server 2.0 Administration Reerence.

To set up load balancing andailover o remote EJB reerences, defne at leasttwo

target-server elements in the sun-acc.xml fle.This step is notneeded or JavaWeb Start.

6

7

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009224

Note – Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see “Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

I the Communications Server instance on which the application client is deployed participates

in a cluster, the ACC nds all currently active IIOP endpoints in the cluster automatically.However, a client should have at least two endpoints specied or bootstrapping purposes, incase one o the endpoints has ailed.

The target-server elements speciy one or more IIOP endpoints used or load balancing. Theaddress attribute is an IPv4 address or host name, and the port attribute species the portnumber. See “client-container” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide.

Run the application client.

See “Using Java Web Start” on page 226 or “Running an Application Client Using the appclient

Script” on page 232.

▼ To Access a JMS Resource From an Application Client

Create a JMSclient.For detailed instructions on developing a JMS client, see “Chapter 33: The Java Message ServiceAPI” in the Java EE 5 Tutorial (http://java sun com/javaee/5/docs/tutorial/doc/

8

1

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 225/326

API in the Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/

index.html).

Next, confgure a JMS resource on the Communications Server.

For inormation on conguring JMS resources, see “Creating JMS Resources: Destinations and

Connection Factories” on page 290.

Defne the @Resource or @Resources annotations or the resource-ref elements in the

application-client.xml fle. Defne the corresponding resource-ref elements in the

sun-application-client.xml fle.

For more inormation on the application-client.xml le, see the Java EE 5 Specication,Section EE.9.7, “Java EE Application Client XML Schema.”

For more inormation on the sun-application-client.xml le, see “Thesun-application-client.xml le” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide. For a general explanation o how to map JNDI names using reerenceelements, see “Mapping Reerences” on page 282.

Ensurethat theclient JARfle includes theollowingfles:

2

3

4

Chapter 11 • Developing Java Clients 225

■ A Java class to access the resource.

■ application-client.xml - (optional) Java EE application client deployment descriptor.For inormation on the application-client.xml le, see the Java EE 5 Specication,Section EE.9.7, “Java EE Application Client XML Schema.”

■ sun-application-client.xml - (optional) Communications Server specic clientdeployment descriptor. For inormation on thesun-application-client.xml le, see

“The sun-application-client.xml le” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

■ The MANIFEST.MF le. This le contains a reerence to the main class, which states thecomplete package prex and class name o the Java client.

Prepare theclient machine.This step is notneeded or JavaWeb Start.

I you are using the appclient script, either package the application client to run on a remote

client system using the package-appclient script, or copy the ollowing JAR les to the clientmachine manually and include them in the classpath on the client side:

■ appserv-rt.jar - available at as-install /lib

■ javaee.jar - available at as-install /lib

■ imqjmsra.jar - available at as-install /lib/install/aplications/jmsra

■ The client JAR le

For more inormation, see “Using the package-appclient Script” on page 232.

Run the application client.

See “Using Java Web Start” on page 226 or “Running an Application Client Using the appclient

5

6

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 226/326

See Using Java Web Start on page 226 or Running an Application Client Using the appclient

Script” on page 232.

Using Java Web StartJava Web Start allows your application client to be easily launched and automatically downloaded and updated. General inormation about Java Web Start is available athttp://java.sun.com/products/javawebstart/reference/api/index.html .

Java Web Start is discussed in the ollowing topics:

■ “Enabling and Disabling Java Web Start” on page 227

■ “Downloading and Launching an Application Client” on page 227■ “The Application Client URL” on page 228■ “Signing JAR Files Used in Java Web Start” on page 229■ “Error Handling” on page 231■ “Vendor Icon, Splash Screen, and Text” on page 231

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009226

Enabling and Disabling Java Web Start

Java Web Start is enabled or all application clients by deault.

The application developer or deployer can speciy that Java Web Start is always disabled or anapplication client by setting the value o the eligible element to false in thesun-application-client.xml le. See the Sun GlassFish Communications Server 2.0 Application Deployment Guide.

The Communications Server administrator can disable Java Web Start or a previously deployed eligible application client using the asadmin set command.

To disable Java Web Start or all eligible application clients in an application, use the ollowingcommand:

asadmin set --user adminuser

domain1.applications.j2ee-application.app-name.java-web-start-enabled="false"

To disable Java Web Start or a stand-alone eligible application client, use the ollowingcommand:

asadmin set --user adminuser

domain1.applications.appclient-module.module-name.java-web-start-enabled="false"

Setting java-web-start-enabled="true" re-enables Java Web Start or an eligible applicationclient. For more inormation about the asadmin set command, see the Sun GlassFish

Communications Server 2.0 Reerence Manual .

Downloading and Launching an Application Client

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 227/326

Downloading and Launching an Application Client

I Java Web Start is enabled or your deployed application client, you can launch it or testing.Simply click on the Launch button next to the application client or application's listing on theApp Client Modules page in the Admin Console.

On other machines, you can download and launch the application client using Java Web Start inthe ollowing ways:

■ Using a web browser, directly enter the URL or the application client. See “The ApplicationClient URL” on page 228.

■ Click on a link to the application client rom a web page.

■ Use the Java Web Start command javaws, speciying the URL o the application client as acommand line argument.

■ I the application has previously been downloaded using Java Web Start, you haveadditional alternatives.

■ Use the desktop icon that Java Web Start created or the application client. When JavaWeb Start downloads an application client or the rst time it asks you i such an iconshould be created.

Chapter 11 • Developing Java Clients 227

■ Use the Java Web Start control panel to launch the application client.

When you launch an application client, Java Web Start contacts the server to see i a newerclient version is available. This means you can redeploy an application client without having toworry about whether client machines have the latest version.

The Application Client URLThe deault URL or an application or module generally is as ollows:

http://host : port /context-root 

The deault URL or a stand-alone application client module is as ollows:

http://host : port /appclient-module-id 

The deault URL or an application client module embedded within an application is as ollows.Note that the relative path to the application client JAR le is included.

http://host : port /application-id /appclient-path

I the context-root , appclient-module-id , or application-id is not specied during deployment,the name o the JAR or EAR le without the extension is used. I the application client module

or application is not in JAR or EAR le ormat, an appclient-module-id or application-id isgenerated.

Regardless o how thecontext-root or id is determined, it is written to the server log For details

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 228/326

Regardless o how thecontext root or id is determined, it is written to the server log. For detailsabout naming, see “Naming Standards” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.

To set a diferent URL or an application client, use the context-root subelement o thejava-web-start-access element in the sun-application-client.xml le. This overrides theappclient-module-id or application-id . See Sun GlassFish Communications Server 2.0 Application Deployment Guide.

You can also pass arguments to the ACC or to the application client's main method as query parameters in the URL. I multiple application client arguments are specied, they are passed inthe order specied.

A question mark separates the context root rom the arguments. Ampersands (&) separate the

arguments and their values. Each argument and each value must begin with arg=.Hereisanexample URL with a -color argument or a stand-alone application client. The -color

argument is passed to the application client's main method.

http://localhost:8080/testClient?arg=-color&arg=red

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009228

Note – I you are using the javaws URL command to launch Java Web Start with a URL thatcontains arguments, enclose the URL in double quotes (") to avoid breaking the URL at theampersand (&) symbol.

Ideally, you should build your production application clients with user-riendly interaces that

collect inormation which might otherwise be gathered as command-line arguments. Thisminimizes the degree to which users must customize the URLs that launch application clientsusing Java Web Start. Command-line argument support is useul in a developmentenvironment and or existing application clients that depend on it.

Signing JAR Files Used in JavaWeb Start

Java Web Start enorces a security sandbox. By deault it grants any application, includingapplication clients, only minimal privileges. Because Java Web Start applications can be soeasily downloaded, Java Web Start provides protection rom potentially harmul programs thatmight be accessible over the network. I an application requires a higher privilege level than thesandbox permits, the code that needs privileges must be in a JAR le that was signed. When JavaWeb Start downloads such a signed JAR le, it displays inormation about the certicate thatwas used to sign the JAR, and it asks you whether you want to trust that signed code. I youagree, the code receives elevated permissions and runs. I you reject the signed code, Java Web

Start does not start the downloaded application.

The Communications Server serves two types o signed JAR les in response to Java Web Startrequests. One type is a JAR le installed as part o the Communications Server, which starts an

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 229/326

requests. One type is a JAR le installed as part o the Communications Server, which starts anapplication client during a Java Web Start launch: as-install /lib/appserv-jwsacc.jar.

The other type is a generated application client JAR le. As part o deployment, theCommunications Server generates a new application client JAR le that contains classes,

resources, and descriptors needed to run the application client on end-user systems. When youdeploy an application with the asadmin deploy command's --retrieve option, use theasadmin get-client-stubs command, or select the Generate RMIStubs option rom the EJBModules deployment page in the Admin Console, this is the JAR le retrieved to your system.Because application clients need access beyond the minimal sandbox permissions to work inthe Java Web Start environment, the generated application client JAR le must be signed beoreit can be downloaded to and executed on an end-user system.

A JAR le can be signed automatically or manually. The ollowing sections describe the ways o signing JAR les.

■ “Automatically Signing JAR Files” on page 230■ “Manually Signing appserv-jwsacc.jar”onpage230■ “Manually Signing the Generated Application Client JAR File” on page 230

Chapter 11 • Developing Java Clients 229

Automatically Signing JAR Files

The Communications Server automatically creates a signed version o the required JAR le i none exists. When a Java Web Start request or the appserv-jwsacc.jar le arrives, theCommunications Server looks or domain-dir /java-web-start/appserv-jwsacc.jar . Whena request or an application's generated application client JAR le arrives, the CommunicationsServer looks in the directory domain-dir /java-web-start/app-name or a le with the samename as the generated JAR le created during deployment.

In either case, i the requested signed JAR le is absent or older than its unsigned counterpart,the Communications Server creates a signed version o the JAR le automatically and depositsit in the relevant directory. Whether the Communications Server just signed the JAR le or not,it serves the le rom the domain-dir /java-web-start directory tree in response to the JavaWeb Start request.

To sign these JAR les, the Communications Server uses its sel-signed certicate. When you

create a new domain, either by installing the Communications Server or by using the asadmincreate-domain command, the Communications Server creates a sel-signed certicate andadds it to the domain's key store.

A sel-signed certicate is generally untrustworthy because no certication authority vouchesor its authenticity. The automatic signing eature uses the same certicate to create all requiredsigned JAR les. To sign diferent JAR les with diferent certicates, do the signing manually.

Manually Signing appserv-jwsacc.jar

You can sign the appserv-jwsacc.jar le manually any time ater you have installed theCommunications Server. Copy the unsigned le rom as-install /lib to a diferent workingdirectory and use thejarsigner command provided with the JDK to create a signed version o

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 230/326

directory and use thejarsigner command provided with the JDK to create a signed version o exactly the same name using your certicate. Then manually copy the signed le intodomain-dir /java-web-start. From then on, the Communications Server serves the JAR lesigned with your certicate whenever a Java Web Start request asks that domain or theappserv-jwsacc.jar le. Note that you can sign each domain's appserv-jwsacc.jar le

diferently.

Remember that i you create a new domain and do not sign appserv-jwsacc.jar manually orthat domain, the Communications Server creates an auto-signed version o it or use by the new domain. Also, i you create a domain-specic signedappserv-jwsacc.jar, delete the domain,and then create a new domain with the same name as the just-deleted domain, theCommunications Server does not remember the earlier signed appserv-jwsacc.jar. You mustrecreate the manually signed version.

Manually Signing the Generated Application Client JAR File

You can sign the generated application client JAR le or an application any time ater you havedeployed the application. As you deploy the application, you can speciy the asadmin deploy

command's --retrieve option or select the Generate RMIStubs option on the EJB Modules

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009230

deployment page in the Admin Console. Doing either o these tasks returns a copy o thegenerated application client JAR le to a directory you speciy. Or, ater you have deployed anapplication, you can download the generated application client JAR le using theasadmin

get-client-stubs command.

Once you have a copy o the generated application client JAR le, you can sign it using thejarsigner tool and your certicate. Then place the signed JAR le in the

domain-dir /java-web-start/app-name directory. You do not need to restart the server tostart using the new signed JAR le.

Error Handling

When an application client is launched using Java Web Start, any error that the applicationclient logic does not catch and handle is written to System.err and displayed in a dialog box.This display appears i an error occurs even beore the application client logic receives control.

It also appears i the application client code does not catch and handle errors itsel.

Vendor Icon, Splash Screen, andText

To speciy a vendor-specic icon, splash screen, text string, or a combination o these or JavaWeb Start download and launch screens, use thevendor element in thesun-application-client.xml le. The complete ormat o this element's data is as ollows:

<vendor>icon-image-URI ::splash-screen-image-URI ::vendor-text </vendor>

The ollowing example vendor element contains an icon, a splash screen, and a text string:

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 231/326

<vendor>images/icon.jpg::otherDir/splash.jpg::MyCorp, Inc.</vendor>

The ollowing example vendor element contains an icon and a text string:

<vendor>images/icon.jpg::MyCorp, Inc.</vendor>

The ollowing example vendor element contains a splash screen and a text string; note the initialdouble colon:

<vendor>::otherDir/splash.jpg::MyCorp, Inc.</vendor>

The ollowing example vendor element contains only a text string:

<vendor>MyCorp, Inc.</vendor>

The deault value is the text string Application Client.

For more inormation about the sun-application-client.xml le, see the Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

Chapter 11 • Developing Java Clients 231

Running an Application Client Using the appclient

ScriptTo run an application client that does not have Java Web Start enabled, you can launch the ACCusing the appclient script. This is optional. This script is located in the as-install /bin

directory. For details, see theSun GlassFish Communications Server 2.0 Reerence Manual .

Using the package-appclient ScriptYou can package an application client that does not have Java Web Start enabled into a singleappclient.jar le using the package-appclient script. This is optional. This script is locatedin the as-install /bin directory. For details, see theSun GlassFish Communications Server 2.0Reerence Manual .

The client.policy FileThe client.policy le is the J2SE policy le used by the application client. Each applicationclient has a client.policy le. The deault policy le limits the permissions o Java EEdeployed application clients to the minimal set o permissions required or these applications tooperate correctly. I an application client requires more than this deault set o permissions, editthe client.policy le to add the custom permissions that your application client needs. Use

the J2SE standard policy tool or any text editor to edit this le.For more inormation on using the J2SE policy tool, see http://java.sun.com/docs/books/

tutorial/security1.2/tour2/index.html .

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 232/326

For more inormation about the permissions you can set in the client.policy le, seehttp://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html .

Using RMI/IIOP Over SSLYou can congure RMI/IIOP over SSL in two ways: using a username and password, or using aclient certicate.

To use a username and password, congure the ior-security-config element in thesun-ejb-jar.xml le. The ollowing conguration establishes SSL between an applicationclient and an EJB component using a username and password. The user has to login to the ACCusing either the sun-acc.xml mechanism or the “Programmatic Login” on page 107mechanism.

<ior-security-config>

<transport-config>

<integrity>required</integrity>

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009232

<confidentiality>required</confidentiality>

<establish-trust-in-target>supported</establish-trust-in-target>

<establish-trust-in-client>none</establish-trust-in-client>

</transport-config>

<as-context>

<auth-method>username_password</auth-method>

<realm>default</realm>

<required>true</required>

</as-context><sas-context>

<caller-propagation>none</caller-propagation>

</sas-context>

</ior-security-config>

For more inormation about the sun-ejb-jar.xml and sun-acc.xml les, see the Sun GlassFishCommunications Server 2.0 Application Deployment Guide.

To use a client certicate, congure the ior-security-config element in thesun-ejb-jar.xml le. The ollowing conguration establishes SSL between an applicationclient and an EJB component using a client certicate.

<ior-security-config>

<transport-config>

<integrity>required</integrity>

<confidentiality>required</confidentiality>

<establish-trust-in-target>supported</establish-trust-in-target>

<establish-trust-in-client>required</establish-trust-in-client>

</transport-config>

<as-context>

<auth-method>none</auth-method>

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 233/326

<realm>default</realm>

<required>false</required>

</as-context>

<sas-context>

<caller-propagation>none</caller-propagation>

</sas-context>

</ior-security-config>

To use a client certicate, you must also speciy the system properties or the keystore andtruststore to be used in establishing SSL. To use SSL with the Application Client Container(ACC), you need to set VMARGS environment variable in one o the ollowing ways:

■ Set the environment variable VMARGS in the shell. For example, in the ksh or bash shell, thecommand to set this environment variable would be as ollows:

export VMARGS="-Djavax.net.ssl.keyStore=${keystore.db.file}

-Djavax.net.ssl.trustStore=${truststore.db.file}

-Djavax.net.ssl.keyStorePass word=${ssl.password}

-Djavax.net.ssl.trustStorePassword=${ssl.password} "

Chapter 11 • Developing Java Clients 233

■ Set the env element in the asant script (see Chapter 3, “The asant Utility”). For example:

<target name="runclient">

<exec executable="${S1AS_HOME}/bin/appclient">

<env key="VMARGS" value=" -Djavax.net.ssl.keyStore=${keystore.db.file}

-Djavax.net.ssl.trustStore=${truststore.db.file}

-Djavax.net.ssl.keyStorePasword=${ssl.password}

-Djavax.net.ssl.trustStorePassword=${ssl.password} "/>

<arg value="-client"/>

<arg value="${appClient.jar}"/>

</exec>

</target>

Connecting to a Remote EJB ModuleThrough a

FirewallTo deploy and run an application client that connects to an EJB module on a CommunicationsServer instance that is behind a rewall, you must set ORB Virtual Address AgentImplementation (ORBVAA) options. Use the asadmin create-jvm-options command asollows:

asadmin create-jvm-options --user adminuser -Dcom.sun.corba.ee.ORBVAAHost= public-IP-adress

asadmin create-jvm-options --user adminuser -Dcom.sun.corba.ee.ORBVAAPort= public-port asadmin create-jvm-options --user adminuser

-Dcom.sun.corba.ee.ORBUserConfigurators.com.sun.corba.ee.impl.plugin.hwlb.VirtualAddressAgentImpl=x

Set the ORBVAAHost and ORBVAAPort options to the host and port o the public address. The

Developing Clients Using the ACC

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 234/326

Set the ORBVAAHost and ORBVAAPort options to the host and port o the public address. TheORBUserConfigurators option tells the ORB to create an instance o theVirtualAddressAgentImpl class and invoke the configure method on the resulting object,which must implement the com.sun.corba.ee.spi.orb.ORBConfigurator interace. TheORBUserConfigurators value doesn't matter. Together, these options create an ORB that inturn creates Object reerences (the underlying implementation o remote EJB reerences)containing the public address, while the ORB listens on the private address specied or theIIOP port in the Communications Server conguration.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009234

Developing Connectors

This chapter describes Sun GlassFish Communications Server support or the J2EETM 1.5

Connector Architecture (CA).

The J2EE Connector Architecture provides a Java solution to the problem o connectivity between multiple application servers and existing enterprise inormation systems (EISs). By using the J2EE Connector architecture, EIS vendors no longer need to customize their productor each application server. Application server vendors who conorm to the J2EE Connectorarchitecture do not need to write custom code to add connectivity to a new EIS.

This chapter uses the terms connector and resource adapter interchangeably. Both terms reer toa resource adapter module that is developed in conormance with the J2EE ConnectorSpecication.

b h

12C H A P T E R 1 2

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 235/326

For more inormation about connectors, see J2EE Connector Architecture(http://java.sun.com/j2ee/connector/) and “Chapter 37: J2EE Connector Architecture” inthe Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/index.html ).

For connector examples, see http://developers.sun.com/prodtech/appserver/reference/techart/as8_connectors.

This chapter includes the ollowing topics:

■ “Connector Support in the Communications Server” on page 236■ “Deploying and Conguring a Stand-Alone Connector Module” on page 237■ “Redeploying a Stand-Alone Connector Module” on page 238■

“Deploying and Conguring an Embedded Resource Adapter” on page 238■ “Advanced Connector Conguration Options” on page 239■ “Inbound Communication Support” on page 242■ “Conguring a Message Driven Bean to Use a Resource Adapter” on page 243

235

Connector Support in the Communications ServerThe Communications Server supports the development and deployment o resource adaptersthat are compatible with Connector specication (and, or backward compatibility, theConnector 1.0 specication).

The Connector 1.0 specication denes the outbound connectivity system contracts betweenthe resource adapter and the Communications Server. The Connector 1.5 specicationintroduces major additions in dening system level contracts between the CommunicationsServer and the resource adapter with respect to the ollowing:

■ Inbound connectivity rom an EIS - Denes the transaction and message inow systemcontracts or achieving inbound connectivity rom an EIS. The message inow contract alsoserves as a standard message provider pluggability contract, thereby allowing variousproviders o messaging systems to seamlessly plug in their products with any applicationserver that supports the message inow contract.

■ Resource adapter lie cycle management and thread management - These eatures areavailable through the liecycle and work management contracts.

Connector Architecture or JMS and JDBCIn the Admin Console, connector, JMS, and JDBC resources are handled diferently, but they use the same underlying Connector architecture. In the Communications Server, all

communication to an EIS, whether to a message provider or an RDBMS, happens through theConnector architecture. To provide JMS inrastructure to clients, the Communications Serveruses the Sun GlassFish Message Queue sotware. To provide JDBC inrastructure to clients, theCommunications Server uses its own JDBC system resource adapters. The application server

t ti ll k th t d t il bl t li t th t i th

ConnectorSupport in the Communications Server

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 236/326

automatically makes these system resource adapters available to any client that requires them.

For more inormation about JMS in the Communications Server, see Chapter 18, “Using theJava Message Service.” For more inormation about JDBC in the Communications Server, seeChapter 15, “Using the JDBC API or Database Access.”

Connector ConfgurationThe Communications Server does not need to use sun-ra.xml, which previousCommunications Server versions used, to store server-specic deployment inormation insidea Resource Adapter Archive (RAR) le. (However, the sun-ra.xml le is still supported orbackward compatibility.) Instead, the inormation is stored in the server conguration. As a

result, you can create multiple connector connection pools or a connection denition in aunctional resource adapter instance, and you can create multiple user-accessible connectorresources (that is, registering a resource with a JNDI name) or a connector connection pool. Inaddition, dynamic changes can be made to connector connection pools and the connectorresource properties without restarting the Communications Server.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009236

Deploying and Confguring a Stand-Alone Connector ModuleYou can deploy a stand-alone connector module using the Admin Console or the asadmin

command. For inormation about using the Admin Console, click the Help button in theAdmin Console. For inormation about using the asadmin command, see the Sun GlassFishCommunications Server 2.0 Reerence Manual .

Deploying a stand-alone connector module allows multiple deployed Java EE applications toshare the connector module. A resource adapter conguration is automatically created or theconnector module.

▼ To Deploy and Confgure a Stand-Alone ConnectorModule

Deploy theconnector module in oneo theollowingways.

■ In the Admin Console, open the Applications component and select Connector Modules.When you deploy the connector module, a resource adapter conguration is automatically created or the connector module.

■ Use the asadmin deploy or asadmin deploydir command. To override the deaultconguration properties o a resource adapter, i necessary, use the asadmin

create-resource-adapter-config command.

Confgure connector connection pools or the deployed connector module in one o theollowing ways:

■ In the Admin Console, open the Resources component, select Connectors, and select

1

2

Deploying and Confguringa Stand-Alone ConnectorModule

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 237/326

In the Admin Console, open the Resources component, select Connectors, and selectConnector Connection Pools.

■ Use the asadmin create-connector-connection-pool command.

Confgure connector resources or the connector connection pools in one o the ollowing ways.■ In the Admin Console, open the Resources component, select Connectors, and select

Connector Resources.

■ Use the asadmin create-connector-resource command.

This associates a connector resource with a JNDI name.

Create an administered object or an inbound resource adapter, i necessary, in one o the

ollowing ways:

■ In the Admin Console, open the Resources component, select Connectors, and selectAdmin Object Resources.

■ Use the asadmin create-admin-object command.

3

4

Chapter 12 • Developing Connectors 237

Redeploying a Stand-Alone Connector ModuleRedeployment o a connector module maintains all connector connection pools, connectorresources, and administered objects dened or the previously deployed connector module.You need not recongure any o these resources.

However, you should redeploy any dependent modules. A dependent module uses or reers to a

connector resource o the redeployed connector module. Redeployment o a connector moduleresults in the shared class loader reloading the new classes. Other modules that reer to the oldresource adapter classes must be redeployed to gain access to the new classes. For moreinormation about class loaders, see Chapter 2, “Class Loaders.”

During connector module redeployment, the server log provides a warning indicating that alldependent applications should be redeployed. Client applications or application componentsusing the connector module’s resources may throw class cast exceptions i dependentapplications are not redeployed ater connector module redeployment.

To disable automatic redeployment, set the --force option to false. In this case, i theconnector module has already been deployed, the Communications Server provides an errormessage.

Deploying and Confguring an Embedded Resource AdapterA connector module can be deployed as a Java EE component in a Java EE application. Suchconnectors are only visible to components residing in the same Java EE application. Simply deploy this Java EE application as you would any other Java EE application.

Redeploying a Stand-Alone ConnectorModule

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 238/326

You can create new connector connection pools and connector resources or a connectormodule embedded within a Java EE application by prexing the connector name withapp-name#. For example, i an application appX.ear has jdbcra.rar embedded within it, theconnector connection pools and connector resources reer to the connector module asappX#jdbcra.

However, an embedded connector module cannot be undeployed using the nameapp-name#connector-name. To undeploy the connector module, you must undeploy theapplication in which it is embedded.

The association between the physical JNDI name or the connector module in theCommunications Server and the logical JNDI name used in the application component is

specied in the Communications Server specic XML descriptor sun-ejb-jar.xml.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009238

Advanced Connector Confguration OptionsYou can use these advanced connector conguration options:

■ “Thread Pools” on page 239■ “Security Maps” on page 239■ “Overriding Conguration Properties” on page 240■ “Testing a Connector Connection Pool” on page 240■ “Handling Invalid Connections” on page 241■ “Setting the Shutdown Timeout” on page 241■ “Using Last Agent Optimization o Transactions” on page 242

Thread Pools

Connectors can submit work instances to the Communications Server or execution. By deault, the Communications Server services work requests or all connectors rom its deaultthread pool. However, you can associate a specic user-created thread pool to service work requests rom a connector. A thread pool can service work requests rom multiple resourceadapters. To create a thread pool:

■ In the Admin Console, select Thread Pools under the relevant conguration. For details,click the Help button in the Admin Console.

■ Use the asadmin create-threadpool command. For details, see the Sun GlassFishCommunications Server 2.0 Reerence Manual .

To associate a connector with a thread pool:

■ In the Admin Console, open the Applications component and select Connector Modules.

AdvancedConnector Confguration Options

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 239/326

, p pp pDeploy the module, or select the previously deployed module. Speciy the name o thethread pool in the Thread Pool ID eld. For details, click the Help button in the AdminConsole.

■ Use the --threadpoolid option o the asadmin create-resource-adapter-configcommand. For details, see theSun GlassFish Communications Server 2.0 Reerence Manual .

I you create a resource adapter conguration or a connector module that is already deployed,the connector module deployment is restarted with the new conguration properties.

Security Maps

Create a security map or a connector connection pool to map an application principal or a usergroup to a back end EIS principal. The security map is usually used in situations where one ormore EIS back end principals are used to execute operations (on the EIS) initiated by variousprincipals or user groups in the application.

Chapter 12 • Developing Connectors 239

To create or update security maps or a connector connection pool:

■ In the Admin Console, open the Resources component, select Connectors, select ConnectorConnection Pools, and select the Security Maps tab. For details, click the Help button in theAdmin Console.

■ Use the asadmin create-connector-security-map command. For details, see the Sun

GlassFish Communications Server 2.0 Reerence Manual .

I a security map already exists or a connector connection pool, the new security map isappended to the previous one. The connector security map conguration supports the use o the wildcard asterisk (*) to indicate all users or all user groups.

When an application principal initiates a request to an EIS, the Communications Server rstchecks or an exact match to a mapped back end EIS principal using the security map denedor the connector connection pool. I there is no exact match, the Communications Server uses

the wild card character specication, i any, to determined the mapped back end EIS principal.

Overriding Confguration Properties

You can override the properties (config-property elements) specied in the ra.xml leoaresource adapter. Use the asadmin create-resource-adapter-config command to create a

conguration or a resource adapter. Use this command’s --property option to speciy aname-value pair or a resource adapter property.

You can use the asadmin create-resource-adapter-config command either beore or aterresource adapter deployment. I it is executed ater deploying the resource adapter, the existing

AdvancedConnector Confguration Options

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 240/326

resource adapter is restarted with the new properties. For details, see theSun GlassFish

Communications Server 2.0 Reerence Manual .

You can also use token replacement or overriding resource adapter conguration properties inindividual server instances when the resource adapter is deployed to a cluster. For example, ora property called inboundPort, you can assign the value ${inboundPort}. You can then assign adiferent value to this property or each server instance. Changes to system properties take efectupon server restart.

Testing a Connector Connection PoolAter conguring a connector connection pool, use the asadmin ping-connection-pool

command to test the health o the underlying connections. For details, see theSun GlassFish

Communications Server 2.0 Reerence Manual .

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009240

Handling Invalid Connections

I a resource adapter generates a ConnectionErrorOccured event, the Communications Serverconsiders the connection invalid and removes the connection rom the connection pool.Typically, a resource adapter generates a ConnectionErrorOccured event when it nds aManagedConnection object unusable. Reasons can be network ailure with the EIS, EIS ailure,atal problems with resource adapter, and so on. I the fail-all-connections property in the

connection pool conguration is set to true, all connections are destroyed and the pool isrecreated.

The is-connection-validation-required property species whether connections have to be validated beore being given to the application. I a resource’s validation ails, it is destroyed,and a new resource is created and returned.

You can set the fail-all-connections and is-connection-validation-required

conguration properties during creation o a connector connection pool. Or, you can use theasadmin set command to dynamically recongure a previously set property. For details, seethe Sun GlassFish Communications Server 2.0 Reerence Manual .

The interace ValidatingManagedConnectionFactory exposes the methodgetInvalidConnections to allow retrieval o the invalid connections. The CommunicationsServer checks i the resource adapter implements this interace, and i it does, invalidconnections are removed when the connection pool is resized.

Setting the Shutdown Timeout

AdvancedConnector Confguration Options

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 241/326

According to the Connector specication, while an application server shuts down, all resourceadapters should be stopped. A resource adapter might hang during shutdown, since shutdownis typically a resource intensive operation. To avoid such a situation, you can set a timeout that

aborts resource adapter shutdown i exceeded. The deault timeout is 30 seconds per resourceadapter module. To congure this timeout:

■ In the Admin Console, select Connector Service under the relevant conguration and editthe shutdown Timeout eld. For details, click the Help button in the Admin Console.

■ Use the ollowing command:

asadmin set --user adminuser server1.connector-service.shutdown-timeout-in-seconds="num-secs"

For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

The Communications Server deactivates all message-driven bean deployments beore stoppinga resource adapter.

Chapter 12 • Developing Connectors 241

Using Last Agent Optimization o Transactions

Transactions that involve multiple resources or multiple participant processes are distributed or global transactions. A global transaction can involve one non-XA resource i last agentoptimization is enabled. Otherwise, all resources must be XA. For more inormation abouttransactions in the Communications Server, see Chapter 16, “Using the Transaction Service.”

The Connector specication requires that i a resource adapter supports XATransaction,theManagedConnection created rom that resource adapter must support both distributed andlocal transactions. Thereore, even i a resource adapter supports XATransaction,youcancongure its connector connection pools as non-XA or without transaction support or betterperormance. A non-XA resource adapter becomes the last agent in the transactions in which itparticipates.

The value o the connection pool conguration property transaction-support deaults to the value o the transaction-support property in the ra.xml le. The connection pool

conguration property can override the ra.xml le property i the transaction level in theconnection pool conguration property is lower. I the value in the connection poolconguration property is higher, it is ignored.

Inbound Communication SupportThe Connector specication denes the transaction and message inow system contracts or

achieving inbound connectivity rom an EIS. The message inow contract also serves as astandard message provider pluggability contract, thereby allowing various message providers toseamlessly plug in their products with any application server that supports the message inow contract. In the inbound communication model, the EIS initiates all communication to anapplication An application can be composed o enterprise beans (session entity or

Inbound CommunicationSupport

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 242/326

application. An application can be composed o enterprise beans (session, entity, ormessage-driven beans), which reside in an EJB container.

Incoming messages are received through a message endpoint, which is a message-driven bean.

This message-driven bean asynchronously consumes messages rom a message provider. Anapplication can also synchronously send and receive messages directly using messaging styleAPIs.

A resource adapter supporting inbound communication provides an instance o anActivationSpec JavaBean class or each supported message listener type. Each class contains aset o congurable properties that speciy endpoint activation conguration inormationduring message-driven bean deployment. The requiredconfig-property element in the

ra.xml le provides a list o conguration property names required or each activationspecication. An endpoint activation ails i the required property values are not specied.Values or the properties that are overridden in the message-driven bean’s deploymentdescriptor are applied to the ActivationSpec JavaBean when the message-driven bean isdeployed.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009242

Administered objects can also be specied or a resource adapter, and these JavaBeans arespecic to a messaging style or message provider. For example, some messaging styles may needapplications to use special administered objects (such as Queue and Topic objects in JMS).Applications use these objects to send and synchronously receive messages using connectionobjects using messaging style APIs. For more inormation about administered objects, seeChapter 18, “Using the Java Message Service.”

Confguring a Message Driven Bean to Use a Resource AdapterThe Connectors specication’s message inow contract provides a generic mechanism to plugin a wide-range o message providers, including JMS, into a Java-EE-compatible applicationserver. Message providers use a resource adapter and dispatch messages to message endpoints,which are implemented as message-driven beans.

The message-driven bean developer provides activation conguration inormation in themessage-driven bean’s ejb-jar.xml le. Conguration inormation includesmessaging-style-specic conguration details, and possibly message-provider-specic details aswell. The message-driven bean deployer uses this conguration inormation to set up theactivation specication JavaBean. The activation conguration properties specied inejb-jar.xml override conguration properties in the activation specication denition in thera.xml le.

According to the EJB specication, the messaging-style-specic descriptor elements contained

within the activation conguration element are not specied because they are specic to amessaging provider. In the ollowing sample message-driven bean ejb-jar.xml, amessage-driven bean has the ollowing activation conguration property names:destinationType, SubscriptionDurability,and MessageSelector.

Confguring a Message Driven Bean toUse a Resource Adapter

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 243/326

<!-- A sample MDB that listens to a JMS Topic -->

<!-- message-driven bean deployment descriptor -->

...

<activation-config><activation-config-property>

<activation-config-property-name>

destinationType

</activation-config-property-name>

<activation-config-property-value>

javax.jms.Topic

</activation-config-property-value>

</activation-config-property>

<activation-config-property>

<activation-config-property-name>

SubscriptionDurability

</activation-config-property-name>

<activation-config-property-value>

Chapter 12 • Developing Connectors 243

Durable

</activation-config-property-value>

</activation-config-property>

<activation-config-property>

<activation-config-property-name>

MessageSelector

</activation-config-property-name>

<activation-config-property-value>

JMSType = ’car’ AND color = ’blue’</activation-config-property-value>

</activation-config-property>

...

</activation-config>

...

When the message-driven bean is deployed, the value or theresource-adapter-mid elementin the sun-ejb-jar.xml le is set to the resource adapter module name that delivers messages

to the message endpoint (to the message-driven bean). In the ollowing example, the jmsra JMSresource adapter, which is the bundled resource adapter or the Sun GlassFish Message Queuemessage provider, is specied as the resource adapter module identier or theSampleMDB bean.

<sun-ejb-jar>

<enterprise-beans>

<unique-id>1</unique-id>

<ejb>

<ejb-name>SampleMDB</ejb-name>

<jndi-name>SampleQueue</jndi-name>

<!-- JNDI name of the destination from which messages would be

delivered from MDB needs to listen to -->

...

<mdb-resource-adapter>

Confguring a Message DrivenBeanto Usea Resource Adapter

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 244/326

<resource-adapter-mid>jmsra</resource-adapter-mid>

<!-- Resource Adapter Module Id that would deliver messages to

this message endpoint -->

</mdb-resource-adapter>...

</ejb>

...

</enterprise-beans>

...

</sun-ejb-jar>

When the message-driven bean is deployed, the Communications Server uses the

resourceadapter-mid setting to associate the resource adapter with a message endpointthrough the message inow contract. This message inow contract with the application servergives the resource adapter a handle to the MessageEndpointFactory and the ActivationSpec

JavaBean, and the adapter uses this handle to deliver messages to the message endpointinstances (which are created by the MessageEndpointFactory).

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009244

When a message-driven bean rst created or use on the Communications Server 7 is deployed,the Connector runtime transparently transorms the previous deployment style to the currentconnector-based deployment style. I the deployer species neither a resource-adapter-mid

property nor the Message Queue resource adapter’s activation conguration properties, theConnector runtime maps the message-driven bean to the jmsra system resource adapter andconverts the JMS-specic conguration to the Message Queue resource adapter’s activationconguration properties.

Confguring a Message Driven Bean toUse a Resource Adapter

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 245/326

Chapter 12 • Developing Connectors 245

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 246/326

246

Developing Liecycle Listeners

Liecycle listener modules provide a means o running short or long duration Java-based tasks

within the application server environment, such as instantiation o singletons or RMI servers.These modules are automatically initiated at server startup and are notied at various phases o the server lie cycle.

All liecycle module classes and interaces are in theas-install /lib/appserv-ext.jar le.

For Javadoc tool pages relevant to liecycle modules, go to http://glassfish.dev.java.net/

nonav/javaee5/api/index.html and click on the com.sun.appserv.server package.

The ollowing sections describe how to create and use a liecycle listener module:

■ “Server Lie Cycle Events” on page 247■ “The LifecycleListener Interace” on page 248■ “The LifecycleEvent Class” on page 248■ “The Server Liecycle Event Context” on page 249

13C H A P T E R 1 3

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 247/326

The Server Liecycle Event Context on page 249■ “Deploying a Liecycle Module” on page 249■ “Considerations or Liecycle Modules” on page 250

Server Lie Cycle Events

A liecycle module listens or and perorms its tasks in response to the ollowing events in theserver lie cycle:

■ Ater the INIT_EVENT, the server reads the conguration, initializes built-in subsystems(such as security and logging services), and creates the containers.

■ Ater the STARTUP_EVENT, the server loads and initializes deployed applications.

■ Ater the READY_EVENT, the server is ready to service requests.

■ Ater the SHUTDOWN_EVENT, the server destroys loaded applications and stops.

247

■ Ater the TERMINATION_EVENT, the server closes the containers, the built-in subsystems, andthe server runtime environment.

These events are dened in the LifecycleEvent class.

The liecycle modules that listen or these events implement the LifecycleListener interace.

The LifecycleListener InteraceTo create a liecycle module is to congure a customized class that implements thecom.sun.appserv.server.LifecycleListener interace. You can create and simultaneously execute multiple liecycle modules.

The LifecycleListener interace denes this method:

public void handleEvent(com.sun.appserv.server.LifecycleEvent event)

throws ServerLifecycleException

This method responds to a liecycle event and throws acom.sun.appserv.server.ServerLifecycleException i an error occurs.

A sample implementation o the LifecycleListener interace is theLifecycleListenerImpl.java le, which you can use or testing liecycle events.

The LifecycleEvent ClassThe com.sun.appserv.server.LifecycleEvent class denes a server lie cycle event. The

The LifecycleListener Interace

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 248/326

pp y yollowing methods are associated with the event:

■ public java.lang.Object getData()

This method returns an instance o java.util.Properties that contains the propertiesdened or the liecycle module in the domain.xml le. For more inormation about thedomain.xml le, see the Sun GlassFish Communications Server 2.0 Administration Reerence.

■ public int getEventType()

This method returns the type o the last event, which is INIT_EVENT, STARTUP_EVENT,READY_EVENT, SHUTDOWN_EVENT, or TERMINATION_EVENT.

public com.sun.appserv.server.LifecycleEventContextgetLifecycleEventContext()

This method returns the liecycle event context, described next.

A LifecycleEvent instance is passed to the LifecycleListener.handleEvent method.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009248

The Server Liecycle Event Context

The com.sun.appserv.server.LifecycleEventContext interace exposes runtimeinormation about the server. The liecycle event context is created when the LifecycleEvent

class is instantiated at server initialization. The LifecycleEventContext interace denes thesemethods:

■ public java.lang.String[] getCmdLineArgs()

This method returns the server startup command-line arguments.

■ public java.lang.String getInstallRoot()

This method returns the server installation root directory.

■ public java.lang.String getInstanceName()

This method returns the server instance name.

public javax.naming.InitialContext getInitialContext()

This method returns the initial JNDI naming context. The naming environment or liecyclemodules is installed ater the STARTUP_EVENT. A liecycle module can look up any resourceby its jndi-name attribute ater the READY_EVENT.

I a liecycle module needs to look up resources, it can do so ater the READY_EVENT.Itcanusethe getInitialContext() method to get the initial context to which all the resources arebound.

Deploying a Liecycle Module

You can deploy a liecycle module using the ollowing tools:

Deploying a Liecycle Module

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 249/326

You can deploy a liecycle module using the ollowing tools:

■ In the Admin Console, open the Applications component and go to the Liecycle Modules

page. For details, click the Help button in the Admin Console.■ Use the asadmin create-lifecycle-module command. For details, see the Sun GlassFish

Communications Server 2.0 Reerence Manual .

You do not need to speciy a classpath or the liecycle module i you place it in thedomain-dir /lib or domain-dir /lib/classes directory or the Domain Administration Server.Do not place it in the lib directory or a particular instance, or it will be deleted when thatinstance synchronizes with the Domain Administration Server.

Ater you deploy a liecycle module, you must restart the server to activate it. The serverinstantiates it and registers it as a liecycle event listener at server initialization.

Chapter 13 • Developing Liecycle Listeners 249

Note – I the is-failure-fatal setting is set to true (the deault is false), liecycle moduleailure prevents server initialization or startup, but not shutdown or termination.

Considerations or Liecycle Modules

The resources allocated at initialization or startup should be reed at shutdown or termination.The liecycle module classes are called synchronously rom the main server thread, thereore itis important to ensure that these classes don’t block the server. Liecycle modules can createthreads i appropriate, but these threads must be stopped in the shutdown and terminationphases.

The LieCycleModule class loader is the parent class loader or liecycle modules. Each liecyclemodule’s classpath in domain.xml is used to construct its class loader. All the support classes

needed by a liecycle module must be available to the LieCycleModule class loader or its parent,the Connector class loader.

You must ensure that the server.policy le is appropriately set up, or a liecycle moduletrying to perorm a System.exec() might cause a security access violation. For details, see “Theserver.policy File” on page 95.

The congured properties or a liecycle module are passed as properties ater theINIT_EVENT.

The JNDI naming context is not available beore theSTARTUP_EVENT

. I a liecycle modulerequires the naming context, it can get this ater the STARTUP_EVENT, READY_EVENT, orSHUTDOWN_EVENT.

Considerations or Liecycle Modules

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 250/326

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009250

Developing Custom MBeans

An MBean is a managed Java object, similar to a JavaBeanTM, that ollows the design patterns set

orth in the instrumentation level o the Java

TM

Management Extensions (JMX

TM

) specication.An MBean can represent a device, an application, or any resource that needs to be managed.MBeans expose a management interace: a set o readable and/or writable attributes and a set o invokable operations, along with a sel-description. The actual runtime interace o an MBeandepends on the type o that MBean. MBeans can also emit notications when certain denedevents occur. Unlike other components, MBeans have no annotations or deploymentdescriptors.

The Sun GlassFish Communications Server supports the development o custom MBeans as

part o the sel-management inrastructure or as separate applications. All types o MBeans(standard, dynamic, open, and model) are supported. For more about sel-management, seeChapter 20, “Using the Application Server Management Extensions,” and Chapter 21,“Conguring Management Rules,” in Sun GlassFish Communications Server 2.0 AdministrationGuide.

14C H A P T E R 1 4

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 251/326

For general inormation about JMX technology, including how to download the JMXspecication, see http://java.sun.com/products/JavaManagement/index.jsp .

For a useul overview o JMX technology, see http://java.sun.com/

javase/6/docs/technotes/guides/jmx/overview/JMXoverviewTOC.html .

For a tutorial o JMX technology, see http://java.sun.com/

javase/6/docs/technotes/guides/jmx/tutorial/tutorialTOC.html .

This chapter includes the ollowing topics:

■ “The MBean Lie Cycle” on page 252■ “MBean Class Loading” on page 253■ “Creating, Deleting, and Listing MBeans” on page 253■ “The MBeanServer in the Communications Server” on page 255■ “Enabling and Disabling MBeans” on page 256■ “Handling MBean Attributes” on page 256

251

The MBean Lie CycleThe MBean lie cycle proceeds as ollows:

1. The MBean's class les are installed in the Communications Server. See “MBean ClassLoading” on page 253.

2. The MBean is deployed using the asadmin create-mbean command or the Admin Console.See “Creating, Deleting, and Listing MBeans” on page 253.

3. The MBean class is loaded. This also results in loading o other classes. The delegationmodel is used. See the class loader diagram in“The Class Loader Hierarchy” on page 33.

4. The MBean is instantiated. Its deault constructor is invoked reectively. This is why theMBean class must have a deault constructor.

5. The MBean's ObjectName is determined according to the ollowing algorithm.

■ I you speciy the ObjectName, it is used as is. The domain must be user:. The property 

name server is reserved and cannot be used.The Communications Server automatically appends server=target to the ObjectName

when the MBean is registered, where the target is the name o the server instance orcluster to which the MBean is deployed.

■ I the MBean implements the MBeanRegistration interace, it must provide anObjectName in its preregister() method that ollows the same rules.

■ I the ObjectName is not specied directly or through the MBeanRegistration interace,

the deault is user:type=impl-class-name.6. All attributes are set using setAttribute calls in the order in which the attributes are

specied. Attempting to speciy a read-only attribute results in an error.

I attribute values are set during MBean deployment, these values are passed in as String

objects. Thereore, attribute types must be Java classes having constructors that acceptString objects I you speciy an attribute that does not have such a constructor, an error is

TheMBean Lie Cycle

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 252/326

String objects. I you speciy an attribute that does not have such a constructor, an error isreported.

Attribute values specied during MBean deployment are persisted to the CommunicationsServer conguration. Changes to attributes ater registration through a JMX connector suchas JConsole do not afect the Communications Server conguration. To change an attribute

 value in the Communications Server conguration, use the asadmin set command. See“Handling MBean Attributes” on page 256.

7. I the MBean is enabled, the MBeanServer.registerMBean(Object, ObjectName) methodis used to register the MBean in the MBeanServer. This is the only method called by theCommunications Server runtime. See “The MBeanServer in the Communications Server”

on page 255.

MBeans are enabled by deault. Disabling an MBean deregisters it. See“Enabling andDisabling MBeans” on page 256.

8. The MBean is automatically loaded, instantiated, and registered upon each server restart.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009252

9. When the MBean is deleted using the asadmin delete-mbean command or the AdminConsole, the MBean is rst deregistered i it is enabled, then the MBean denition is deletedrom the conguration. The class les are not deleted, however.

MBean Class Loading

Ater you develop a custom MBean, copy its class les (or JAR le) into the MBean class loaderdirectory, domain-dir /applications/mbeans. You have two choices o where to place any dependent classes:

■ Common class loader – Copy the classes as JAR les into the domain-dir /lib directory, orcopy the classes as .class les into the domain-dir /lib/classes directory. The classes areloaded when you restart the Communications Server. The classes are available to all otherMBeans, applications, and modules deployed on servers that share the same conguration.

■ MBean class loader – Copy the classes into the domain-dir /applications/mbeans

directory. No restart is required. The classes are available to all other MBeans deployed onservers that share the same conguration, but not to applications and modules.

Ater copying the classes, register the MBean using the asadmin create-mbean command. See“The asadmin create-mbean Command” on page 253.

For general inormation about Communications Server class loaders, see Chapter 2, “ClassLoaders.”

Creating, Deleting, and Listing MBeansThis section describes the ollowing commands:

■ Use the asadmin create mbean command to deploy or register an MBean

Creating, Deleting, and Listing MBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 253/326

■ Use the asadmin create-mbean command to deploy, or register , an MBean.■ Use the asadmin delete-mbean command to undeploy an MBean.■

Use the asadmin list-mbeans command to list deployed MBeans.

To perorm these tasks using the Admin Console, open the Custom MBeans component. Fordetails, click the Help button in the Admin Console.

The asadmin create-mbean Command

Ater installing the MBean classes as explained in “MBean Class Loading” on page 253,usetheasadmin create-mbean command to deploy the MBean. This registers the MBean in theMBeanServer that is part o the Communications Server runtime environment. For moreinormation about the MBeanServer, see “The MBeanServer in the Communications Server” onpage 255.

Chapter 14 • Developing Custom MBeans 253

Here is a simple example o an asadmin create-mbean command in which TextPatterns is theimplementation class. The --attributes and --target options are not required.

asadmin create-mbean --user adminuser --target server1 --attributes color=red:font=Times TextPatterns

Other options not included in the example are as ollows:

■ --name deaults to the implementation class name■ --objectname

is explained in “The MBean Lie Cycle” on page 252■ --enabled deaults to true and is explained in “Enabling and Disabling MBeans” onpage 256

All options must precede the implementation class.

For ull details on the asadmin create-mbean command, see the Sun GlassFishCommunications Server 2.0 Reerence Manual .

For more inormation about MBean attributes, see “Handling MBean Attributes” on page 256.

Note – To redeploy an MBean, simply install its new classes into the Communications Server asdescribed in “MBean Class Loading” on page 253. Then either restart the server or use asadmin

delete-mbean ollowed by asadmin create-mbean.

The asadmin delete-mbean CommandTo undeploy an MBean, use the asadmin delete-mbean command. This removes itsregistration rom the MBeanServer, but does not delete its code. Here is an example asadmin

delete-mbean command in which TextPatterns is the implementation class. The --target

option is not required.

Creating,Deleting, and Listing MBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 254/326

asadmin delete-mbean --user adminuser --target server1 TextPatterns

For ull details on the asadmin delete-mbean command, see the Sun GlassFishCommunications Server 2.0 Reerence Manual .

The asadmin list-mbeans Command

To list MBeans that have been deployed, use the asadmin list-mbeans command. Note that

this command only lists the MBean denitions and not the MBeans registered in theMBeanServer. Here is an example asadmin list-mbeans command. The --target option isnot required.

asadmin list-mbeans --user adminuser --target server1

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009254

The output o the asadmin list-mbeans command lists the ollowing inormation:

■ Implementation class – The name o the implementation class without the extension.

■ Name – The name o the registered MBean, which deaults to but may be diferent rom theimplementation class name.

■ Object name – The ObjectName o the MBean, which is explained in “The MBean LieCycle” on page 252.

Object type – For custom MBeans, the object type is always user. System MBeans haveother object types.

■ Enabled – Whether the MBean is enabled. MBeans are enabled by deault. See “Enablingand Disabling MBeans” on page 256.

For ull details on the asadmin list-mbeans command, see the Sun GlassFish CommunicationsServer 2.0 Reerence Manual .

The MBeanServer in the Communications ServerCustom MBeans are registered in the PlatformMBeanServer returned by thejava.lang.management.ManagementFactory.getPlatformMBeanServer() method. ThisMBeanServer is associated with a standard JMX connector server.

You can use any JMX connector to look up MBeans in this MBeanServer just as you would any other MBeanServer. I your JMX connector is remote, you can connect to this MBeanServer

using the ollowing inormation:

■ Host name o the Communications Server machine■ MBeanServer port, which is 8686 by deault■ Administrator username■ Administrator password

The MBeanServer in the CommunicationsServer

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 255/326

For example, i you use JConsole, you can enter this inormation under the Remote tab.JConsole is a generic JMX connector you can use to look up and manage MBeans. For moreinormation about JConsole, see http://java.sun.com/developer/technicalArticles/

J2SE/jconsole.html, the JMX tutorial at http://java.sun.com/

javase/6/docs/technotes/guides/jmx/tutorial/tutorialTOC.html , and “UsingJConsole” in Sun GlassFish Communications Server 2.0 Administration Guide.

The connection to this MBeanServer is non-SSL by deault or the developer prole and SSL by deault or the cluster prole.

I SSL is enabled, you must provide the location o the truststore that contains the servercerticate that the JMX connector should trust. For example, i you are using JConsole, yousupply this location at the command line as ollows:

jconsole -J-Djavax.net.ssl.trustStore=home-directory /.asadmintruststore

Chapter 14 • Developing Custom MBeans 255

Look up the MBean by its name. By deault, the name is the same as the implementation class.

You can recongure the JMX connector server's naming service port in one o the ollowingways:

■ In the Admin Console, open the Admin Service component under the relevantconguration, select the system subcomponent, edit the Port eld, and select Save. Fordetails, click the Help button in the Admin Console.

■ Use the asadmin set command as in the ollowing example:

asadmin set --user adminuser server1.admin-service.jmx-connector.system.port=8687

For details, see theSun GlassFish Communications Server 2.0 Reerence Manual .

Enabling and Disabling MBeansA custom MBean is enabled by deault. You can disable an MBean during deployment by usingthe asadmin create-mbean command's optional --enabled=false option. See “The asadmin

create-mbean Command” on page 253.

Ater deployment, you can disable an MBean using the asadmin set command. For example:

asadmin set --user adminuser server1.applications.mbean.TextPatterns.enabled=false

I the MBean name is diferent rom the implementation class, you must use the name in theasadmin set command. In this example, the name is TextPatterns.

For ull details on the asadmin set command, see the Sun GlassFish Communications Server 2.0Reerence Manual .

Enabling and Disabling MBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 256/326

Handling MBean AttributesYou can set MBean attribute values that are not read-only in the ollowing ways:

■ In the MBean code itsel, which does not afect the Communications Server conguration

■ During deployment using the asadmin create-mbean command

■ During deployment using the Custom MBeans component in the Admin Console

■ Using the asadmin set command

■ Using a JMX connector such as JConsole, which does not afect the Communications Serverconguration

In the Communications Server conguration, MBean attributes are stored as properties.Thereore, using the asadmin set command means editing properties. For example:

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009256

asadmin set --user adminuser server1.applications.mbean.TextPatterns.property.color=blue

I the MBean name is diferent rom the implementation class, you must use the MBean namein the asadmin set command. In this example, the name is TextPatterns.

For ull details on the asadmin set command, see the Sun GlassFish Communications Server 2.0Reerence Manual .

Handling MBeanAttributes

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 257/326

Chapter 14 • Developing Custom MBeans 257

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 258/326

258

Using Services and APIs

P A R T I I I

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 259/326

259

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 260/326

260

Using the JDBC API or Database Access

This chapter describes how to use the JavaTM Database Connectivity (JDBCTM) API or databaseaccess with the Sun GlassFish Communications Server. This chapter also provides high levelJDBC implementation instructions or servlets and EJB components using theCommunications Server. I the JDK version 1.6 is used, the Communications Server supportsthe JDBC 4.0 API, which encompasses the JDBC 3.0 API and the JDBC 2.0 Optional PackageAPI.

The JDBC specications are available at http://java.sun.com/products/jdbc/

download.html.

A useul JDBC tutorial is located at http://java.sun.com/docs/books/tutorial/jdbc/index.html.

Note – The Communications Server does not support connection pooling or transactions or anapplication’s database access i it does not use standard Java EE DataSource objects.

15C H A P T E R 1 5

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 261/326

This chapter discusses the ollowing topics:

■ “General Steps or Creating a JDBC Resource” on page 261■ “Creating Applications That Use the JDBC API” on page 263■ “Restrictions and Optimizations” on page 267

General Steps or Creating a JDBC Resource

To prepare a JDBC resource or use in Java EE applications deployed to the CommunicationsServer, perorm the ollowing tasks:

■ “Integrating the JDBC Driver” on page 262■ “Creating a Connection Pool” on page 262■ “Testing a JDBC Connection Pool” on page 263

261

■ “Creating a JDBC Resource” on page 263

For inormation about how to congure some specic JDBC drivers, see“Congurations orSpecic JDBC Drivers” in Sun GlassFish Communications Server 2.0 Administration Guide.

Integrating the JDBC Driver

To use JDBC eatures, you must choose a JDBC driver to work with the CommunicationsServer, then you must set up the driver. This section covers these topics:

■ “Supported Database Drivers” on page 262■ “Making the JDBC Driver JAR Files Accessible” on page 262

Supported Database Drivers

Supported JDBC drivers are those that have been ully tested by Sun. For a list o the JDBC

drivers currently supported by the Communications Server, see theSun GlassFishCommunications Server 2.0 Release Notes. For congurations o supported and other drivers,see “Congurations or Specic JDBC Drivers” in Sun GlassFish Communications Server 2.0 Administration Guide.

Note – Because the drivers and databases supported by the Communications Server areconstantly being updated, and because database vendors continue to upgrade their products,always check with Sun technical support or the latest database support inormation.

Making the JDBC Driver JAR Files Accessible

To integrate the JDBC driver into a Communications Server domain, copy the JAR les into thedomain-dir /lib directory, then restart the server. This makes classes accessible to allapplications or modules deployed on servers that share the same conguration. For moreinormation about Communications Server class loaders, see Chapter 2, “Class Loaders.”

General Steps or Creating a JDBC Resource

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 262/326

Creating a Connection Pool

When you create a connection pool that uses JDBC technology (a JDBC connection pool )intheCommunications Server, you can dene many o the characteristics o your databaseconnections.

You can create a JDBC connection pool in one o these ways:

■ In the Admin Console, open the Resources component, open the JDBC component, andselect Connection Pools. For details, click the Help button in the Admin Console.

■ Use the asadmin create-jdbc-connection-pool command. For details, see the SunGlassFish Communications Server 2.0 Reerence Manual .

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009262

For a complete description o JDBC connection pool eatures, see theSun GlassFishCommunications Server 2.0 Administration Guide

Testing a JDBC Connection Pool

You can test a JDBC connection pool or usability in one o these ways:

■ In the Admin Console, open the Resources component, open the JDBC component, selectConnection Pools, and select the connection pool you want to test. Then select the Pingbutton in the top right corner o the page. For details, click the Help button in the AdminConsole.

■ Use the asadmin ping-connection-pool command. For details, see the Sun GlassFishCommunications Server 2.0 Reerence Manual .

Both these commands ail and display an error message unless they successully connect to the

connection pool.

For inormation about how to tune a connection pool, see the Sun GlassFish CommunicationsServer 2.0 Perormance Tuning Guide.

Creating a JDBC Resource

A JDBC resource, also called a data source, lets you make connections to a database usinggetConnection(). Create a JDBC resource in one o these ways:

■ In the Admin Console, open the Resources component, open the JDBC component, andselect JDBC Resources. For details, click the Help button in the Admin Console.

■ Use the asadmin create-jdbc-resource command. For details, see the Sun GlassFishCommunications Server 2.0 Reerence Manual .

Creating ApplicationsThat Use the JDBCAPI

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 263/326

Creating Applications That Use the JDBC APIAn application that uses the JDBC API is an application that looks up and connects to one ormore databases. This section covers these topics:

■ “Sharing Connections” on page 264■

“Obtaining a Physical Connection From a Wrapped Connection” on page 264■ “Marking Bad Connections” on page 264■ “Using Non-Transactional Connections” on page 265■ “Using JDBC Transaction Isolation Levels” on page 266■ “Allowing Non-Component Callers” on page 267

Chapter 15 • Using the JDBC API or Database Access 263

Sharing ConnectionsWhen multiple connections acquired by an application use the same JDBC resource, theconnection pool provides connection sharing within the same transaction scope. For example,suppose Bean A starts a transaction and obtains a connection, then calls a method in Bean B. I Bean B acquires a connection to the same JDBC resource with the same sign-on inormation,and i Bean A completes the transaction, the connection can be shared.

Connections obtained through a resource are shared only i the resource reerence declared by the Java EE component allows it to be shareable. This is specied in a component’s deploymentdescriptor by setting the res-sharing-scope element to Shareable or the particular resourcereerence. To turn of connection sharing, set res-sharing-scope to Unshareable.

For general inormation about connections and JDBC URLs, see Chapter 3, “JDBC Resources,”in Sun GlassFish Communications Server 2.0 Administration Guide.

Obtaining a Physical Connection From a WrappedConnection

The DataSource implementation in the Communications Server provides a getConnection

method that retrieves the JDBC driver’s SQLConnection rom the Communications Server’sConnection wrapper. The method signature is as ollows:

public java.sql.Connection getConnection(java.sql.Connection con)throws java.sql.SQLException

For example:

InitialContext ctx = new InitialContext();

com.sun.appserv.jdbc.DataSource ds = (com.sun.appserv.jdbc.DataSource)

ctx.lookup("jdbc/MyBase");

Creating ApplicationsThat Usethe JDBCAPI

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 264/326

Connection con = ds.getConnection();

Connection drivercon = ds.getConnection(con);

// Do db operations.

// Do not close driver connection.

con.close(); // return wrapped connection to pool.

Marking Bad Connections

The DataSource implementation in the Communications Server provides amarkConnectionAsBad method. A marked bad connection is removed rom its connection poolwhen it is closed. The method signature is as ollows:

public void markConnectionAsBad(java.sql.Connection con)

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009264

For example:

com.sun.appserv.jdbc.DataSource ds=

(com.sun.appserv.jdbc.DataSource)context.lookup( "dataSource");

Connection con = ds.getConnection();

Statement stmt = null;

try{

stmt = con.createStatement();

stmt.executeUpdate("Update");

}

catch (BadConnectionException e){

dataSource.markConnectionAsBad(con) //marking it as bad for removal

}

finally{

stmt.close();

con.close(); //Connection will be destroyed during close.

}

Using Non-Transactional Connections

You can speciy a non-transactional database connection in any o these ways:

■ Check the Non-Transactional Connections box on the JDBC Connection Pools page in theAdmin Console. The deault is unchecked. For more inormation, click the Help button inthe Admin Console.

■ Speciy the --nontransactionalconnections option in the asadmin

create-jdbc-connection-pool command. For more inormation, see theSun GlassFishCommunications Server 2.0 Reerence Manual .

■ Use the DataSource implementation in the Communications Server, which provides agetNonTxConnection method. This method retrieves a JDBC connection that is not in thescope o any transaction. There are two variants.

Creating ApplicationsThat Use the JDBCAPI

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 265/326

public java.sql.Connection getNonTxConnection() throws java.sql.SQLException

public java.sql.Connection getNonTxConnection(String user, String password)

throws java.sql.SQLException

■ Create a resource with the JNDI name ending in __nontx. This orces all connections lookedup using this resource to be non transactional.

Typically, a connection is enlisted in the context o the transaction in which a getConnection

call is invoked. However, a non-transactional connection is not enlisted in a transaction contexteven i a transaction is in progress.

The main advantage o using non-transactional connections is that the overhead incurred inenlisting and delisting connections in transaction contexts is avoided. However, use such

Chapter 15 • Using the JDBC API or Database Access 265

connections careully. For example, i a non-transactional connection is used to query thedatabase while a transaction is in progress that modies the database, the query retrieves theunmodied data in the database. This is because the in-progress transaction hasn’t committed.For another example, i a non-transactional connection modies the database and a transactionthat is running simultaneously rolls back, the changes made by the non-transactionalconnection are not rolled back.

Here is a typical use case or a non-transactional connection: a component that is updating a

database in a transaction context spanning over several iterations o a loop can reresh cacheddata by using a non-transactional connection to read data beore the transaction commits.

Using JDBC Transaction Isolation Levels

For general inormation about transactions, see Chapter 16, “Using the Transaction Service,”and Chapter 12, “Transactions,” in Sun GlassFish Communications Server 2.0 Administration

Guide. For inormation about last agent optimization, which can improve perormance, see“Transaction Scope” on page 270.

Not all database vendors support all transaction isolation levels available in the JDBC API. TheCommunications Server permits speciying any isolation level your database supports. Theollowing table denes transaction isolation levels.

TABLE 15–1 TransactionIsolationLevels

Transaction Isolation Level Description

TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads, and phantom reads can occur.

TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable reads and phantomreads can occur.

TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are prevented; phantomreads can occur.

TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads and phantom reads are prevented.

Creating ApplicationsThat Usethe JDBCAPI

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 266/326

Note that you cannot call setTransactionIsolation() during a transaction.

You can set the deault transaction isolation level or a JDBC connection pool. For details, see“Creating a Connection Pool” on page 262.

To veriy that a level is supported by your database management system, test your databaseprogrammatically using the supportsTransactionIsolationLevel() method in

java.sql.DatabaseMetaData , as shown in the ollowing example:

InitialContext ctx = new InitialContext();

DataSource ds = (DataSource)

ctx.lookup("jdbc/MyBase");

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009266

Connection con = ds.getConnection();DatabaseMetaData dbmd = con.getMetaData();

if (dbmd.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE)

{ Connection.setTransactionIsolation(TRANSACTION_SERIALIZABLE); }

For more inormation about these isolation levels and what they mean, see the JDBC APIspecication.

Note – Applications that change the isolation level on a pooled connection programmatically risk polluting the pool, which can lead to errors.

Allowing Non-Component Callers

You can allow non-Java-EE components, such as servlet lters, liecycle modules, and thirdparty persistence managers, to use this JDBC connection pool. The returned connection isautomatically enlisted with the transaction context obtained rom the transaction manager.Standard Java EE components can also use such pools. Connections obtained by non-component callers are not automatically closed at the end o a transaction by the container.They must be explicitly closed by the caller.

You can enable non-component callers in the ollowing ways:

■ Check the Allow Non Component Callers box on the JDBC Connection Pools page in the

Admin Console. The deault is false. For more inormation, click the Help button in theAdmin Console.

■ Speciy the --allownoncomponentcallers option in the asadmin

create-jdbc-connection-pool command. For more inormation, see theSun GlassFishCommunications Server 2.0 Reerence Manual .

■ Create a JDBC resource with a __pm sux.

Restrictions and Optimizations

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 267/326

Restrictions and OptimizationsThis section discusses restrictions and perormance optimizations that afect using the JDBCAPI.

Disabling Stored Procedure Creation on Sybase

By deault, DataDirect and Sun GlassFish JDBC drivers or Sybase databases create a storedprocedure or each parameterized PreparedStatement. On the Communications Server,exceptions are thrown when primary key identity generation is attempted. To disable thecreation o these stored procedures, set the property PrepareMethod=direct.

Chapter 15 • Using the JDBC API or Database Access 267

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 268/326

268

Using the Transaction Service

The Java EE platorm provides several abstractions that simpliy development o dependabletransaction processing or applications. This chapter discusses Java EE transactions and

transaction support in the Sun GlassFish Communications Server.

This chapter contains the ollowing sections:

■ “Transaction Resource Managers” on page 269■ “Transaction Scope” on page 270■ “Distributed Transaction Recovery” on page 271■ “Conguring the Transaction Service” on page 272■

“The Transaction Manager, the Transaction Synchronization Registry, andUserTransaction”onpage272■ “Transaction Logging” on page 273■ “Storing Transaction Logs in a Database” on page 273■ “Recovery Workarounds” on page 274

For more inormation about the JavaTM Transaction API (JTA) and Java Transaction Service(JTS), see Chapter 12, “Transactions,” in Sun GlassFish Communications Server 2.0Administration Guide and the ollowing sites: http://java.sun.com/products/jta/ and

16C H A P T E R 1 6

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 269/326

 Administration Guide and the ollowing sites: http://java.sun.com/products/jta/ andhttp://java.sun.com/products/jts/ .

You might also want to read “Chapter 35: Transactions” in the Java EE 5 Tutorial(http://java.sun.com/javaee/5/docs/tutorial/doc/index.html ).

Transaction Resource ManagersThere are three types o transaction resource managers:

■ Databases - Use o transactions prevents databases rom being let in inconsistent states dueto incomplete updates. For inormation about JDBC transaction isolation levels, see “UsingJDBC Transaction Isolation Levels” on page 266.

269

The Communications Server supports a variety o JDBC XA drivers. For a list o the JDBCdrivers currently supported by the Communications Server, see theSun GlassFishCommunications Server 2.0 Release Notes. For congurations o supported and otherdrivers, see “Congurations or Specic JDBC Drivers” in Sun GlassFish CommunicationsServer 2.0 Administration Guide.

■ Java Message Service (JMS) Providers - Use o transactions ensures that messages arereliably delivered. The Communications Server is integrated with Sun GlassFish MessageQueue, a ully capable JMS provider. For more inormation about transactions and the JMSAPI, see Chapter 18, “Using the Java Message Service.”

■ J2EE Connector Architecture (CA) components - Use o transactions prevents legacy EISsystems rom being let in inconsistent states due to incomplete updates. For moreinormation about connectors, see Chapter 12, “Developing Connectors.”

For details about how transaction resource managers, the transaction service, and applicationsinteract, see Chapter 12, “Transactions,” in Sun GlassFish Communications Server 2.0 Administration Guide.

Transaction ScopeA local transaction involves only one non-XA resource and requires that all participatingapplication components execute within one process. Local transaction optimization is specicto the resource manager and is transparent to the Java EE application.

In the Communications Server, a JDBC resource is non-XA i it meets any o the ollowingcriteria:

■ In the JDBC connection pool conguration, the DataSource class does not implement thejavax.sql.XADataSource interace.

■ The Global Transaction Support box is not checked, or the Resource Type setting does notexist or is not set to javax.sql.XADataSource.

A transaction remains local i the ollowing conditions remain true:

TransactionScope

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 270/326

g

■ One and only one non-XA resource is used. I any additional non-XA resource is used, thetransaction is aborted.

■ No transaction importing or exporting occurs.

Transactions that involve multiple resources or multiple participant processes are distributed or global transactions. A global transaction can involve one non-XA resource i last agentoptimization is enabled. Otherwise, all resourced must be XA. The

use-last-agent-optimization property is set to true by deault. For details about how to setthis property, see “Conguring the Transaction Service” on page 272.

I only one XA resource is used in a transaction, one-phase commit occurs, otherwise thetransaction is coordinated with a two-phase commit protocol.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009270

A two-phase commit protocol between the transaction manager and all the resources enlistedor a transaction ensures that either all the resource managers commit the transaction or they allabort. When the application requests the commitment o a transaction, the transactionmanager issues a PREPARE_TO_COMMIT request to all the resource managers involved. Each o these resources can in turn send a reply indicating whether it is ready or commit (PREPARED) ornot(NO). Only when all the resource managers are ready or a commit does the transactionmanager issue a commit request (COMMIT) to all the resource managers. Otherwise, thetransaction manager issues a rollback request (ABORT) and the transaction is rolled back.

Distributed Transaction Recovery

Note – Some topics in the documentation pertain to eatures that are available only in domains

that are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see“Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

To enable cluster-wide automatic recovery, you must rst acilitate storing o transaction logsin a shared le system. You can do this in one o these ways:

■ Set the Communications Server's log-root attribute to a shared le system base directory 

and set the transaction service's tx-log-dir attribute to a relative path.

■ Set tx-log-dir to an absolute path to a shared le system directory, in which case log-root

is ignored or transaction logs.

■ Seta system-property called TX-LOG-DIR in the domain.xml le to a shared le systemdirectory.

<server config-ref="server-config" name="server">

DistributedTransaction Recovery

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 271/326

<system-property name="TX-LOG-DIR"value="/net/tulsa/nodeagents/na/instance1/logs" />

</server>

Next, you must set the transaction service's delegated-recovery property to true (the deaultis false).

For inormation about setting tx-log-dir and delegated-recovery,see “Conguring the

Transaction Service” on page 272. For inormation about setting log-root and other generallogging settings, see Chapter 19, “Conguring Logging,” in Sun GlassFish Communications

Server 2.0 Administration Guide. For inormation about system-property and the domain.xml

le, see the Sun GlassFish Communications Server 2.0 Administration Reerence.

Chapter 16 • Using the Transaction Service 271

Confguring theTransaction ServiceYou can congure the transaction service in the Communications Server in the ollowing ways:

■ To congure the transaction service using the Admin Console, open the Transaction Servicecomponent under the relevant conguration. For details, click the Help button in theAdmin Console.

■ To congure the transaction service, use the asadmin set command to set the ollowing

attributes.

server.transaction-service.automatic-recovery = false

server.transaction-service.heuristic-decision = rollback

server.transaction-service.keypoint-interval = 2048

server.transaction-service.retry-timeout-in-seconds = 600

server.transaction-service.timeout-in-seconds = 0

server.transaction-service.tx-log-dir = domain-dir /logs

You can also set these properties:

server.transaction-service.property.oracle-xa-recovery-workaround = false

server.transaction-service.property.disable-distributed-transaction-logging = false

server.transaction-service.property.xaresource-txn-timeout = 600

server.transaction-service.property.pending-txn-cleanup-interval = 60

server.transaction-service.property.use-last-agent-optimization = true

server.transaction-service.property.db-logging-resource = jdbc/TxnDS

server.transaction-service.property.delegated-recovery = false

server.transaction-service.property.wait-time-before-recovery-insec = 60

server.transaction-service.property.xa-servername = myserver

You can use the asadmin get command to list all the transaction service attributes andproperties. For details, see theSun GlassFish Communications Server 2.0 Reerence Manual .

The Transaction Manager, the Transaction Synchronization

Confguringthe Transaction Service

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 272/326

Registry, and UserTransaction

You can access the Communications Server transaction manager, a javax.transaction.

TransactionManager implementation, using the JNDI subcontext java:comp/

TransactionManager or java:appserver/TransactionManager . You can access theCommunications Server transaction synchronization registry, a javax.transaction.

TransactionSynchronizationRegistry implementation, using the JNDI subcontextjava:comp/TransactionSynchronizationRegistry or java:appserver/

TransactionSynchronizationRegistry . You can also request injection o aTransactionManager or TransactionSynchronizationRegistry object using the @Resource

annotation. Accessing the transaction synchronization registry is recommended. For details,see Java Specication Request (JSR) 907 (http://www.jcp.org/en/jsr/detail?id=907 ).

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009272

You can also access java:comp/UserTransaction .

Transaction Logging

The transaction service writes transactional activity into transaction logs so that transactionscan be recovered. You can control transaction logging in these ways:

■ Set the location o the transaction log les using the Transaction Log Location setting in theAdmin Console, or set the tx-log-dir attribute using the asadmin set command.

■ Turn of transaction logging by setting the disable-distributed-transaction-logging

property to true and the automatic-recovery attribute to false.Dothis only i perormance is more important than transaction recovery.

Storing Transaction Logs in a Database

For multi-core machines, logging transactions to a database may be more ecient.

To log transactions to a database, ollow these steps:

1. Create a JDBC connection Pool, and set the non-transactional-connections attribute to

true.2. Create a JDBC resource that uses the connection pool and note the JNDI name o the JDBC

resource.

3. Create a table named txn_log_table with the schema shown in Table 16–1.

4. Add the db-logging-resource property to the transaction service. For example:

asadmin set --user adminuser server1.transaction-service.property.db-logging-resource="jdbc/TxnDS"

StoringTransactionLogs in a Database

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 273/326

The property's value should be the JNDI name o the JDBC resource congured previously.

5. To disable le synchronization, use the ollowing asadmin create-jvm-options

command:

asadmin create-jvm-options --user adminuser -Dcom.sun.appserv.transaction.nofdsync

6. Restart the server.

For inormation about JDBC connection pools and resources, see Chapter 15, “Using the JDBCAPI or Database Access.” For more inormation about the asadmin create-jvm-options

command, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Chapter 16 • Using the Transaction Service 273

TABLE 16–1 Schemaor txn_log_table

Column Name JDBC Type

LOCALTID BIGINT

SERVERNAME VARCHAR(n)

GTRID VARBINARY

The size o the SERVERNAME column should be at least the length o the Communications Serverhost name plus 10 characters.

The size o the GTRID column should be at least 64 bytes.

To dene the SQL used by the transaction manager when it is storing its transaction logs in thedatabase, use the ollowing ags:

-Dcom.sun.jts.dblogging.insertquery=sql statement -Dcom.sun.jts.dblogging.deletequery=sql statement 

The deault statements are as ollows:

-Dcom.sun.jts.dblogging.insertquery=insert into txn_log_table values ( ?, ? , ? )

-Dcom.sun.jts.dblogging.deletequery=delete from txn_log_table where localtid = ? and servername = ?

To set one o these ags using the asadmin create-jvm-options command, you must quotethe statement. For example:

create-jvm-options ’-Dcom.sun.jts.dblogging.deletequery=delete from txn_log_table where gtrid = ?’

You can also set JVM options in the Admin Console. In the developer prole, select theApplication Server component and the JVM Settings tab. In the cluster prole, select the JVMSettings component under the relevant conguration. These ags and their statements mustalso be quoted in the Admin Console. For example:

’ Dcom sun jts dblogging deletequery delete from txn log table where gtrid ?’

RecoveryWorkarounds

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 274/326

’-Dcom.sun.jts.dblogging.deletequery=delete from txn_log_table where gtrid = ?’

RecoveryWorkaroundsThe Communications Server provides workarounds or some known issues with the recovery implementations o the ollowing JDBC drivers. These workarounds are used unless explicitly disabled.

In the Oracle thin driver, the XAResource.recover method repeatedly returns the same set o in-doubt Xids regardless o the input ag. According to the XA specications, the TransactionManager initially calls this method with TMSTARTSCAN and then with TMNOFLAGSrepeatedly until no Xids are returned. TheXAResource.commit method also has some issues.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009274

To disable the Communications Server workaround, set the oracle-xa-recovery-workaroundproperty value to false. For details about how to set this property, see “Conguring theTransaction Service” on page 272.

Note – These workarounds do not imply support or any particular JDBC driver.

RecoveryWorkarounds

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 275/326

Chapter 16 • Using the Transaction Service 275

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 276/326

276

Using the Java Naming and Directory Interace

A naming service maintains a set o bindings, which relate names to objects. The Java EEnaming service is based on the Java Naming and Directory InteraceTM (JNDI) API. The JNDI

API allows application components and clients to look up distributed resources, services, andEJB components. For general inormation about the JNDI API, see http://java.sun.com/

products/jndi/.

You can also see the JNDI tutorial at http://java.sun.com/products/jndi/tutorial/ .

This chapter contains the ollowing sections:

■ “Accessing the Naming Context” on page 277■ “Conguring Resources” on page 281■ “Using a Custom jndi.properties File” on page 282■ “Mapping Reerences” on page 282

Accessing the Naming ContextThe Communications Server provides a naming environment, or context , which is compliant

with standard Java EE requirements A Context object provides the methods or binding namesb b d b b d l h b d Th

17C H A P T E R 1 7

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 277/326

with standard Java EE requirements. A Co e object provides the methods or binding namesto objects, unbinding names rom objects, renaming objects, and listing the bindings. TheInitialContext is the handle to the Java EE naming service that application components andclients use or lookups.

The JNDI API also provides subcontext unctionality. Much like a directory in a le system, asubcontext is a context within a context. This hierarchical structure permits better organizationo inormation. For naming services that support subcontexts, the Context class also provides

methods or creating and destroying subcontexts.The rest o this section covers these topics:

■ “Global JNDI Names” on page 278■ “Accessing EJB Components Using the CosNaming Naming Context” on page 279

277

“Accessing EJB Components in a Remote Application Server” on page 279■ “Naming Environment or Liecycle Modules” on page 280

Note – Each resource within a server instance must have a unique name. However, two resourcesin diferent server instances or diferent domains can have the same name.

Global JNDI Names

Global JNDI names are assigned according to the ollowing precedence rules:

1. A global JNDI name assigned in the sun-ejb-jar.xml, sun-web.xml, orsun-application-client.xml deployment descriptor le has the highest precedence. See“Mapping Reerences” on page 282.

2. A global JNDIname assigned in a mapped-name element in the ejb-jar.xml, web.xml, orapplication-client.xml deployment descriptor le has the second highest precedence.The ollowing elements have mapped-name subelements: resource-ref,resource-env-ref, ejb-ref, message-destination, message-destination-ref,session, message-driven,and entity.

3. A global JNDIname assigned in a mappedName attribute o an annotation has the thirdhighest precedence. The ollowing annotations have mappedName attributes:@javax.annotation.Resource , @javax.ejb.EJB, @javax.ejb.Stateless,@javax.ejb.Stateful, and @javax.ejb.MessageDriven.

4. A deault global JNDI name is assigned in some cases i no name is assigned in deploymentdescriptors or annotations.

■ For an EJB 2.x dependency or a session or entity bean with a remote interace, the deaultis the ully qualied name o the home interace.

■ For an EJB 3.0 dependency or a session bean with a remote interace, the deault is the

ully qualied name o the remote business interace.

Accessing the Naming Context

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 278/326

u y qua ed a e o t e e ote bus ess te ace.■ I both EJB 2.x and EJB 3.0 remote interaces are specied, or i more than one 3.0

remote interace is specied, there is no deault, and the global JNDI name must bespecied.

■ For all other component dependencies that must be mapped to global JNDI names, thedeault is the name o the dependency relative to java:comp/env. For example, in the@Resource(name="jdbc/Foo") DataSource ds; annotation, the global JNDI name is

jdbc/Foo.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009278

Accessing EJB Components Using the CosNamingNaming Context

The preerred way o accessing the naming service, even in code that runs outside o a Java EEcontainer, is to use the no-argument InitialContext constructor. However, i EJB client codeexplicitly instantiates an InitialContext that points to the CosNaming naming service, it isnecessary to set the java.naming.factory.initial property to com.sun.jndi.cosnaming.

CNCtxFactory in the client JVM when accessing EJB components. You can set this property as acommand-line argument, as ollows:

-Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory

Or you can set this property in the code, as ollows:

Properties properties = null;

try {

properties = new Properties();properties.put("java.naming.factory.initial",

"com.sun.jndi.cosnaming.CNCtxFactory");

...

The java.naming.factory.initial property applies to only one instance; it is notcluster-aware.

Accessing EJB Components in a Remote ApplicationServer

The recommended approach or looking up an EJB component in a remote CommunicationsServer rom a client that is a servlet or EJB component is to use the Interoperable NamingService syntax. Host and port inormation is prepended to any global JNDI names and isautomatically resolved during the lookup. The syntax or an interoperable global name is as

ollows:

Accessing the Naming Context

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 279/326

corbaname:iiop:host : port #a/b/name

This makes the programming model or accessing EJB components in anotherCommunications Server exactly the same as accessing them in the same server. The deployercan change the way the EJB components are physically distributed without having to change thecode.

For Java EE components, the code still perorms a java:comp/env lookup on an EJB reerence.The only diference is that the deployer maps the ejb-reference element to an interoperablename in an Communications Server deployment descriptor le instead o to a simple globalJNDI name.

Chapter 17 • Using the Java Naming and Directory Interace 279

For example, suppose a servlet looks up an EJB reerence using java:comp/env/ejb/Foo,andthe target EJB component has a global JNDI name o a/b/Foo.

The ejb-ref element in sun-web.xml looks like this:

<ejb-ref>

<ejb-ref-name>ejb/Foo</ejb-ref-name>

<jndi-name>corbaname:iiop:host : port #a/b/Foo</jndi-name>

<ejb-ref>

The code looks like this:

Context ic = new InitialContext();

Object o = ic.lookup("java:comp/env/ejb/Foo");

For a client that doesn’t run within a Java EE container, the code just uses the interoperableglobal name instead o the simple global JNDI name. For example:

Context ic = new InitialContext();

Object o = ic.lookup("corbaname:iiop:host : port #a/b/Foo");

Objects stored in the interoperable naming context and component-specic (java:comp/env)naming contexts are transient. On each server startup or application reloading, all relevantobjects are re-bound to the namespace.

Naming Environment or Liecycle Modules

Liecycle listener modules provide a means o running short or long duration tasks based onJava technology within the application server environment, such as instantiation o singletonsor RMI servers. These modules are automatically initiated at server startup and are notied at

 various phases o the server lie cycle. For details about liecycle modules, see Chapter 13,“Developing Liecycle Listeners.”

The congured properties or a liecycle module are passed as properties during server

Accessing the Naming Context

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 280/326

initialization (the INIT_EVENT). The initial JNDI naming context is not available until serverinitialization is complete. A liecycle module can get the InitialContext or lookups using themethod LifecycleEventContext.getInitialContext() during, and only during, theSTARTUP_EVENT, READY_EVENT, or SHUTDOWN_EVENT server lie cycle events.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009280

Confguring ResourcesThe Communications Server exposes the ollowing special resources in the namingenvironment. Full administration details are provided in the ollowing sections:

■ “External JNDI Resources” on page 281■ “Custom Resources” on page 281

External JNDI Resources

An external JNDI resource denes custom JNDI contexts and implements thejavax.naming.spi.InitialContextFactory interace. There is no specic JNDI parentcontext or external JNDI resources, except or the standard java:comp/env/.

Create an external JNDI resource in one o these ways:

■ To create an external JNDI resource using the Admin Console, open the Resourcescomponent, open the JNDI component, and select External Resources. For details, click theHelp button in the Admin Console.

■ To create an external JNDI resource, use the asadmin create-jndi-resource command.For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Custom ResourcesA custom resource species a custom server-wide resource object actory that implements thejavax.naming.spi.ObjectFactory interace. There is no specic JNDI parent context orexternal JNDI resources, except or the standard java:comp/env/.

Create a custom resource in one o these ways:

■ To create a custom resource using the Admin Console, open the Resources component,

open the JNDI component, and select Custom Resources. For details, click the Help buttonin the Admin Console.

Confguring Resources

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 281/326

in the Admin Console.

■ To create a custom resource, use the asadmin create-custom-resource command. Fordetails, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

Chapter 17 • Using the Java Naming and Directory Interace 281

Using a Custom jndi.properties FileTo use a custom jndi.properties le, speciy the path to the le in one o the ollowing ways:

■ Use the Admin Console. In the developer prole, select the Communications Servercomponent and select the JVM Settings tab. In the cluster prole, select the JVM Settingscomponent under the relevant conguration. Then select the Path Settings tab and edit theClasspath Prex eld. For details, click the Help button in the Admin Console.

Edit the classpath-prefix attribute o the java-config element in the domain.xml le.For details about domain.xml,seethe Sun GlassFish Communications Server 2.0 Administration Reerence.

This adds the jndi.properties le to the Shared Chain class loader. For more inormationabout class loading, seeChapter 2, “Class Loaders.”

For each property ound in more than one jndi.properties le, the Java EE naming serviceeither uses the rst value ound or concatenates all o the values, whichever makes sense.

Mapping ReerencesThe ollowing XML elements in the Communications Server deployment descriptors mapresource reerences in application client, EJB, and web or SIP application components to JNDInames congured in the Communications Server:

■ resource-env-ref - Maps the @Resource or @Resources annotation (or the

resource-env-ref element in the corresponding Java EE XML le) to the absolute JNDIname congured in the Communications Server.

■ resource-ref - Maps the @Resource or @Resources annotation (or the resource-ref

element in the corresponding Java EE XML le) to the absolute JNDI name congured inthe Communications Server.

■ ejb-ref - Maps the @EJB annotation (or the ejb-ref element in the corresponding Java EEXML le) to the absolute JNDI name congured in the Communications Server.

JNDI names or EJB components must be unique. For example, appending the applicationname and the module name to the EJB name is one way to guarantee unique names In this

Using a Custom jndi.properties File

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 282/326

name and the module name to the EJB name is one way to guarantee unique names. In thiscase, mycompany.pkging.pkgingEJB.MyEJB would be the JNDI name or an EJB in themodule pkgingEJB.jar, which is packaged in the pkging.ear application.

These elements are part o the sun-web.xml, sun-ejb-ref.xml,andsun-application-client.xml deployment descriptor les. For more inormation about how these elements behave in each o the deployment descriptor les, seeAppendix A, “Deployment

Descriptor Files,” in Sun GlassFish Communications Server 2.0 Application Deployment Guide.The rest o this section uses an example o a JDBC resource lookup to describe how to reerenceresource actories. The same principle is applicable to all resources (such as JMS destinations,JavaMail sessions, and so on).

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009282

The @Resource annotation in the application code looks like this:

@Resource(name="jdbc/helloDbDs") javax.sql.DataSource ds;

This reerences a resource with the JNDI name o java:comp/env/jdbc/helloDbDs .Ithisisthe JNDI name o the JDBC resource congured in the Communications Server, the annotationalone is enough to reerence the resource.

However, you can use an Communications Server specic deployment descriptor to override

the annotation. For example, the resource-ref element in the sun-web.xml le maps theres-ref-name (the name specied in the annotation) to the JNDI name o another JDBCresource congured in the Communications Server.

<resource-ref>

<res-ref-name>jdbc/helloDbDs</res-ref-name>

<jndi-name>jdbc/helloDbDataSource</jndi-name>

</resource-ref>

Mapping Reerences

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 283/326

Chapter 17 • Using the Java Naming and Directory Interace 283

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 284/326

284

Using the Java Message Service

This chapter describes how to use the JavaTM Message Service (JMS) API. The Sun Java SystemCommunications Server has a ully integrated JMS provider: the Sun Java System Message

Queue sotware.

For general inormation about the JMS API, see “Chapter 31: The Java Message Service API” inthe Java EE 5 Tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc/index.html ).

For detailed inormation about JMS concepts and JMS support in the Communications Server,see Chapter 4, “Conguring Java Message Service Resources,” in Sun GlassFish CommunicationsServer 2.0 Administration Guide.

This chapter contains the ollowing sections:

■ “The JMS Provider” on page 286■ “Message Queue Resource Adapter” on page 287■ “Generic Resource Adapter” on page 287■ “Administration o the JMS Service” on page 287■ “Restarting the JMS Client Ater JMS Conguration” on page 291■ “JMS Connection Features” on page 291■

“Load-Balanced Message Inow” on page 292■ “Transactions and Non-Persistent Messages” on page 293

18C H A P T E R 1 8

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 285/326

■ “Authentication With ConnectionFactory”onpage293■ “Message Queue varhome Directory” on page 294■ “Delivering SOAP Messages Using the JMS API” on page 294

285

The JMS ProviderThe Communications Server support or JMS messaging, in general, and or message-drivenbeans, in particular, requires messaging middleware that implements the JMS specication: aJMS provider. The Communications Server uses the Sun GlassFish Message Queue sotware asits native JMS provider. The Message Queue sotware is tightly integrated intotheCommunications Server, providing transparent JMS messaging support. This support isknown within Communications Server as the JMS Service. The JMS Service requires only 

minimal administration.

The relationship o the Message Queue sotware to the Communications Server can be one o these types: EMBEDDED, LOCAL, or REMOTE. The efects o these choices on the Message Queuebroker lie cycle are as ollows:

■ Ithetypeis EMBEDDED, the Communications Server and Message Queue sotware run in thesame JVM, and the networking stack is bypassed. The Message Queue broker is started andstopped automatically by the Communications Server. This is the deault or the Domain

Administration Server (DAS).Lazy initialization starts the deault embedded broker on the rst access o JMS servicesrather than at Communications Server startup. EMBEDDED mode is not a supportedconguration or a cluster.

■ Ithetypeis LOCAL, the Message Queue broker starts when the Communications Serverstarts. This is the deault or all Communications Server instances except the DAS.

The LOCAL setting implicitly sets up a 1:1 relationship between an Communications Server

instance and a Message Queue broker. When you create an Communications Server cluster,a Message Queue cluster is automatically created as well. During cluster creation, eachinstance in the Communications Server cluster is automatically congured with a broker inthe Message Queue cluster, and a unique broker port is determined.

The rst Communications Server instance's Message Queue broker is set as the masterbroker. I you delete the rst Communications Server instance, you must use MessageQueue administration tools to migrate the master broker. For details, see“Managing aConventional Cluster’s Conguration Change Record” in Sun GlassFish Message Queue 4.4 Administration Guide.

Ith t i REMOTE th M Q b k t b t t d t l F i ti

The JMS Provider

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 286/326

■ Ithetypeis REMOTE, the Message Queue broker must be started separately. For inormationabout starting the broker, see the Sun GlassFish Message Queue 4.4 Administration Guide.

For more inormation about setting the type and the deault JMS host, see “Conguring the JMSService” on page 288.

For more inormation about the Message Queue sotware, reer to the documentation athttp://docs.sun.com/coll/1343.10 .

For general inormation about the JMS API, see the JMS web page at http://java.sun.com/

products/jms/index.html.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009286

Note – Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see“Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

Message Queue Resource AdapterThe Sun GlassFish Message Queue sotware is integrated into the Communications Serverusing a resource adapter that is compliant with the Connector specication. The module nameo this system resource adapter is jmsra. Every JMS resource is converted to a correspondingconnector resource o this resource adapter as ollows:

■ ConnectionFactory – A connector connection pool with a max-pool-size o 250 andacorresponding connector resource

■ Destination (Topic orQueue) – A connector administered object

You use connector conguration tools to manage JMS resources. For more inormation, seeChapter 12, “Developing Connectors.”

Generic Resource Adapter

The Communications Server provides a generic resource adapter or JMS, or those who wantto use a JMS provider other than Sun GlassFish Message Queue. For details, seehttp://genericjmsra.dev.java.net/ and “Conguring the Generic Resource Adapter orJMS” in Sun GlassFish Communications Server 2.0 Administration Guide.

Administration o the JMS Service

To congure the JMS Service and prepare JMS resources or use in applications deployed to theCommunications Server, you must perorm these tasks:

Administration o the JMS Service

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 287/326

■ “Conguring the JMS Service” on page 288■ “The Deault JMS Host” on page 289■ “Creating JMS Hosts” on page 289■ “Checking Whether the JMS Provider Is Running” on page 289■ “Creating Physical Destinations” on page 289■ “Creating JMS Resources: Destinations and Connection Factories” on page 290

For more inormation about JMS administration tasks, see Chapter 4, “Conguring JavaMessage Service Resources,” in Sun GlassFish Communications Server 2.0 Administration Guideand the Sun GlassFish Message Queue 4.4 Administration Guide.

Chapter 18 • Using the Java Message Service 287

Confguring the JMS ServiceThe JMS Service conguration is available to all inbound and outbound connections pertainingto the Communications Server cluster or instance. You can edit the JMS Service congurationin the ollowing ways:

■ To edit the JMS Service conguration using the Admin Console, open the Java MessageService component under the relevant conguration. For details, click the Help button in

the Admin Console.■ To congure the JMS service, use the asadmin set command to set the ollowing attributes:

server.jms-service.init-timeout-in-seconds = 60

server.jms-service.type = EMBEDDED

server.jms-service.start-args =

server.jms-service.default-jms-host = default_JMS_host

server.jms-service.reconnect-interval-in-seconds = 60

server.jms-service.reconnect-attempts = 3server.jms-service.reconnect-enabled = true

server.jms-service.addresslist-behavior = random

server.jms-service.addresslist-iterations = 3

server.jms-service.mq-scheme = mq

server.jms-service.mq-service = jms

You can also set these properties:

server.jms-service.property.instance-name = imqbroker

server.jms-service.property.instance-name-suffix =

server.jms-service.property.append-version = false

server.jms-service.property.user-name =

server.jms-service.property.password =

You can use the asadmin get command to list all the JMS service attributes and properties.For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

You can override the JMS Service conguration using JMS connection actory settings. For

Administration o the JMS Service

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 288/326

details, see Chapter 4, “Conguring Java Message Service Resources,” in Sun GlassFish

Communications Server 2.0 Administration Guide.

Note – The Communications Server instance must be restarted ater conguration o the JMSService.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009288

The Deault JMS HostA JMS host reers to a Sun GlassFish Message Queue broker. A deault JMS host or the JMSservice is provided, named default_JMS_host. This is the JMS host that the CommunicationsServer uses or perorming all Message Queue broker administrative operations, such ascreating and deleting JMS destinations.

I you have created a multi-broker cluster in the Message Queue sotware, delete the deault JMShost, then add the Message Queue cluster’s brokers as JMS hosts. In this case, the deault JMShost becomes the rst JMS host in the AddressList. For more inormation about theAddressList,see “JMS Connection Features” on page 291. You can also explicitly set the deaultJMS host; see “Conguring the JMS Service” on page 288.

When the Communications Server uses a Message Queue cluster, it executes Message Queuespecic commands on the deault JMS host. For example, when a physical destination is createdor a Message Queue cluster o three brokers, the command to create the physical destination isexecuted on the deault JMS host, but the physical destination is used by all three brokers in the

cluster.

Creating JMS Hosts

You can create additional JMS hosts in the ollowing ways:

■ Use the Admin Console. Open the Java Message Service component under the relevant

conguration, then select the JMS Hosts component. For details, click the Help button in theAdmin Console.

■ Use the asadmin create-jms-host command. For details, see the Sun GlassFishCommunications Server 2.0 Reerence Manual .

For machines having more than one host, use the Host eld in the Admin Console or the-–mqhost option o create-jms-host to speciy the address to which the broker binds.

Checking Whether the JMS Provider Is Running

Administration o the JMS Service

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 289/326

You can use the asadmin jms-ping command to check whether a Sun GlassFish MessageQueue instance is running. For details, see the Sun GlassFish Communications Server 2.0Reerence Manual .

Creating Physical DestinationsProduced messages are delivered or routing and subsequent delivery to consumers using physical destinations in the JMS provider. A physical destination is identied and encapsulated

Chapter 18 • Using the Java Message Service 289

by an administered object (aTopic

orQueue

destination resource) that an applicationcomponent uses to speciy the destination o messages it is producing and the source o messages it is consuming.

I a message-driven bean is deployed and the Queue physical destination it listens to doesn’texist, the Communications Server automatically creates the physical destination and sets the

 value o the property maxNumActiveConsumers to -1 (see “Load-Balanced Message Inow” onpage 292). However, it is good practice to create the Queue physical destination beorehand.

You can create a JMS physical destination in the ollowing ways:

■ Use the Admin Console. Open the Resources component, open the JMS Resourcescomponent, then select Physical Destinations. For details, click the Help button in theAdmin Console.

■ Use the asadmin create-jmsdest command. This command acts on the deault JMS hosto its target. For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

To purge all messages currently queued at a physical destination, use the asadmin

flush-jmsdest command. This deletes the messages beore they reach any messageconsumers. For details, see the Sun GlassFish Communications Server 2.0 Reerence Manual .

To create a destination resource, see “Creating JMS Resources: Destinations and ConnectionFactories” on page 290.

Creating JMS Resources: Destinations and ConnectionFactories

You can create two kinds o JMS resources in the Communications Server:

■ ConnectionFactories– administered objects that implement the ConnectionFactory,QueueConnectionFactory, or TopicConnectionFactory interaces.

■ DestinationResources– administered objects that implement the Queue or Topic

interaces.

Administration o the JMS Service

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 290/326

In either case, the steps or creating a JMS resource are the same. You can create a JMS resourcein the ollowing ways:

■ To create a JMS resource using the Admin Console, open the Resources component, thenopen the JMS Resources component. Click Connection Factories to create a connection

actory, or click Destination Resources to create a queue or topic. For details, click the Helpbutton in the Admin Console.

■ A JMS resource is a type o connector. To create a JMS resource using the command line, see“Deploying and Conguring a Stand-Alone Connector Module” on page 237.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009290

Note – All JMS resource properties that used to work with version 7 o the CommunicationsServer are supported or backward compatibility.

Restarting the JMS Client Ater JMS ConfgurationWhen a JMS client accesses a JMS administered object or the rst time, the client JVM retrieves

the JMS service conguration rom the Communications Server. Further changes to theconguration are not available to the client JVM until the client is restarted.

 JMS Connection FeaturesThe Sun GlassFish Message Queue sotware supports the ollowing JMS connection eatures:

“Connection Pooling” on page 291■ “Connection Failover” on page 292

Both these eatures use the AddressList conguration, which is populated with the hosts andports o the JMS hosts dened in the Communications Server. The AddressList is updatedwhenever a JMS host conguration changes. The AddressList is inherited by any JMS resourcewhen it is created and by any MDB when it is deployed.

Note – In the Sun GlassFish Message Queue sotware, the AddressList property is calledimqAddressList.

Connection Pooling

The Communications Server pools JMS connections automatically.

To dynamically modiy connection pool properties using the Admin Console, go to either theConnection Factories page (see “Creating JMS Resources: Destinations and ConnectionF t i ” 290) th C t C ti P l ( “D l i d

JMS ConnectionFeatures

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 291/326

Factories” on page 290) or the Connector Connection Pools page (see “Deploying andConguring a Stand-Alone Connector Module” on page 237).

To use the command line, use the asadmin create-connector-connection-pool command tomanage the pool (see “Deploying and Conguring a Stand-Alone Connector Module” onpage 237.

For the developer prole, the addresslist-behavior JMS service attribute is set to random by deault. This means that each ManagedConnection (physical connection) created rom theManagedConnectionFactory selects its primary broker in a random way rom the AddressList.

Chapter 18 • Using the Java Message Service 291

For the cluster prole, theaddresslist-behavior

JMS service attribute is set topriority

by deault. This means that the rst broker in the AddressList is selected rst. This rst broker isthe local colocated Message Queue broker. I this broker is unavailable, connection attempts aremade to brokers in the order in which they are listed in the AddressList. This ensurescolocated production and consumption o messages and equitable load distribution across theMessage Queue broker cluster.

When a JMS connection pool is created, there is one ManagedConnectionFactory instanceassociated with it. I you congure the AddressList as a ManagedConnectionFactory property,the AddressList conguration in the ManagedConnectionFactory takes precedence over theone dened in the Communications Server.

Connection Failover

To speciy whether the Communications Server tries to reconnect to the primary broker i the

connection is lost, set thereconnect-enabled

attribute in the JMS service. To speciy thenumber o retries and the time between retries, set the reconnect-attempts andreconnect-interval-in-seconds attributes, respectively.

I reconnection is enabled and the primary broker goes down, the Communications Server triesto reconnect to another broker in the AddressList.The AddressList is updated whenever aJMS host conguration changes. The logic or scanning is decided by two JMS serviceattributes, addresslist-behavior and addresslist-iterations.

You can override these settings using JMS connection actory settings. For details, seeChapter4, “Conguring Java Message Service Resources,” in Sun GlassFish Communications Server 2.0 Administration Guide.

The Sun GlassFish Message Queue sotware transparently transers the load to another brokerwhen the ailover occurs. JMS semantics are maintained during ailover.

Load-Balanced Message InowYou can congure ActivationSpec properties o the jmsra resource adapter in the

Load-BalancedMessage Inow

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 292/326

You can congure ActivationSpec properties o the jmsra resource adapter in thesun-ejb-jar.xml le or a message-driven bean using activation-config-property

elements. Whenever a message-driven bean (EndPointFactory) is deployed, the connectorruntime engine nds these properties and congures them accordingly in the resource adapter.See “activation-cong-property” in Sun GlassFish Communications Server 2.0 ApplicationDeployment Guide.

The Communications Server transparently enables messages to be delivered in random ashionto message-driven beans having same ClientID.The ClientID is required or durablesubscribers.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009292

For nondurable subscribers in which the ClientID is not congured, all instances o a specicmessage-driven bean that subscribe to same topic are considered equal. When amessage-driven bean is deployed to multiple instances o the Communications Server, only oneo the message-driven beans receives the message. I multiple distinct message-driven beanssubscribe to same topic, one instance o each message-driven bean receives a copy o themessage.

To support multiple consumers using the same queue, set the maxNumActiveConsumers

property o the physical destination to a large value. I this property is set, the Sun GlassFishMessage Queue sotware allows multiple message-driven beans to consume messages romsame queue. The message is delivered randomly to the message-driven beans. I maxNumActiveConsumers is setto -1, there is no limit to the number o consumers.

To ensure that local delivery is preerred, setaddresslist-behavior to priority. This settingspecies that the rst broker in the AddressList is selected rst. This rst broker is the localcolocated Message Queue instance. I this broker is unavailable, connection attempts are made

to brokers in the order in which they are listed in the AddressList. This setting is the deault orCommunications Server instances that belong to a cluster.

Note – Some topics in the documentation pertain to eatures that are available only in domainsthat are congured to support clusters. Examples o domains that support clusters are domainsthat are created with the cluster prole. For inormation about proles, see“Usage Proles” inSun GlassFish Communications Server 2.0 Administration Guide.

Transactions and Non-Persistent Messages

During transaction recovery, non-persistent messages might be lost. I the broker ails betweenthe transaction manager’s prepare and commit operations, any non-persistent message in thetransaction is lost and cannot be delivered. A message that is not saved to a persistent store is

not available or transaction recovery.

AuthenticationWith ConnectionFactory

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 293/326

Authentication With ConnectionFactory

I your web, EJB, or client module has res-auth set to Container,butyouusetheConnectionFactory.createConnection("user","password") method to get a connection, theCommunications Server searches the container or authentication inormation beore using thesupplied user and password. Version 7 o the Communications Server threw an exception inthis situation.

Chapter 18 • Using the Java Message Service 293

Message Queue varhome DirectoryThe Sun GlassFish Message Queue sotware uses a deault directory or storing data such aspersistent messages and its log le. This directory is called varhome. The CommunicationsServer uses domain-dir /imq as the varhome directory i the type o relationship between theCommunications Server and the Message Queue sotware is LOCAL or EMBEDDED.Itherelationship type is REMOTE, the Message Queue sotware determines the varhome location. Formore inormation about the types o relationships between the Communications Server andMessage Queue, see “The JMS Provider” on page 286.

When executing Message Queue scripts such as as-install /imq/bin/imqusermgr,usethe-varhome option to point the scripts to the Message Queue data i the relationship type is LOCAL

or EMBEDDED. For example:

imqusermgr -varhome $AS_INSTALL/domains/domain1/imq add -u testuser

For more inormation about the Message Queue sotware, reer to the documentation at

http://docs.sun.com/coll/1343.10 .

Delivering SOAP Messages Using the JMS APIWeb service clients use the Simple Object Access Protocol (SOAP) to communicate with webservices. SOAP uses a combination o XML-based data structuring and Hyper Text TranserProtocol (HTTP) to dene a standardized way o invoking methods in objects distributed indiverse operating environments across the Internet.

For more inormation about SOAP, see the Apache SOAP web site at http://xml.apache.org/

soap/index.html.

You can take advantage o the JMS provider’s reliable messaging when delivering SOAPmessages. You can convert a SOAP message into a JMS message, send the JMS message, thenconvert the JMS message back into a SOAP message. The ollowing sections explain how to dothese conversions:

■ “To Send SOAP Messages Using the JMS API” on page 294■ “To Receive SOAP Messages Using the JMS API” on page 296

Message Queuevarhome Directory

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 294/326

▼ To Send SOAP Messages Using the JMS API

Import the MessageTransformer library.

import com.sun.messaging.xml.MessageTransformer;

This is the utility whose methods you use to convert SOAP messages to JMS messages and thereverse. You can then send a JMS message containing a SOAP payload as i it were a normalJMS message.

1

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009294

Initialize the TopicConnectionFactory, TopicConnection, TopicSession, and publisher.

tcf = new TopicConnectionFactory();

tc = tcf.createTopicConnection();

session = tc.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);

topic = session.createTopic(topicName);

publisher = session.createPublisher(topic);

Construct a SOAP messageusingthe SOAP with Attachments APIor Java (SAAJ).

/*construct a default soap MessageFactory */

MessageFactory mf = MessageFactory.newInstance();

* Create a SOAP message object.*/

SOAPMessage soapMessage = mf.createMessage();

/** Get SOAP part.*/

SOAPPart soapPart = soapMessage.getSOAPPart();

/* Get SOAP envelope. */

SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

/* Get SOAP body.*/

SOAPBody soapBody = soapEnvelope.getBody();

/* Create a name object. with name space */

/* http://www.sun.com/imq. */

Name name = soapEnvelope.createName("HelloWorld", "hw",

"http://www.sun.com/imq");

* Add child element with the above name. */

SOAPElement element = soapBody.addChildElement(name)

/* Add another child element.*/

element.addTextNode( "Welcome to Sun Java System Web Services." );

/* Create an atachment with activation API.*/

URL url = new URL ("http://java.sun.com/webservices/");

DataHandler dh = new DataHandler (url);

AttachmentPart ap = soapMessage.createAttachmentPart(dh);

/*set content type/ID. */

ap.setContentType("text/html");

ap.setContentId("cid-001");

/** add the attachment to the SOAP message.*/

soapMessage.addAttachmentPart(ap);

soapMessage.saveChanges();

Convert theSOAP messageto a JMSmessageby calling theMessageTransformer SOAPMessageintoJMSMessage() method

2

3

4

Delivering SOAP MessagesUsing the JMS API

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 295/326

MessageTransformer.SOAPMessageintoJMSMessage() method.

Message m = MessageTransformer.SOAPMessageIntoJMSMessage (soapMessage,

session );

Publish the JMS message.

publisher.publish(m);

Close the JMS connection.

tc.close();

5

6

Chapter 18 • Using the Java Message Service 295

▼ To Receive SOAP Messages Using the JMS APIImport the MessageTransformer library.

import com.sun.messaging.xml.MessageTransformer;

This is the utility whose methods you use to convert SOAP messages to JMS messages and thereverse. The JMS message containing the SOAP payload is received as i it were a normal JMSmessage.

Initialize the TopicConnectionFactory, TopicConnection, TopicSession, TopicSubscriber,

and Topic.

messageFactory = MessageFactory.newInstance();

tcf = new com.sun.messaging.TopicConnectionFactory();

tc = tcf.createTopicConnection();

session = tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

topic = session.createTopic(topicName);

subscriber = session.createSubscriber(topic);subscriber.setMessageListener(this);

tc.start();

Usethe OnMessage method to receive themessage. Use the SOAPMessageFromJMSMessage

method to convert theJMS message to a SOAP message.

public void onMessage (Message message) {

SOAPMessage soapMessage =

MessageTransformer.SOAPMessageFromJMSMessage( message,

messageFactory ); }

Retrieve the contento the SOAPmessage.

1

2

3

4

DeliveringSOAP MessagesUsing the JMS API

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 296/326

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009296

Using the JavaMail API

This chapter describes how to use the JavaMailTM API, which provides a set o abstract classesdening objects that comprise a mail system.

This chapter contains the ollowing sections:

■ “Introducing JavaMail” on page 297■ “Creating a JavaMail Session” on page 298■ “JavaMail Session Properties” on page 298■ “Looking Up a JavaMail Session” on page 298■ “Sending and Reading Messages Using JavaMail” on page 299

Introducing JavaMailThe JavaMail API denes classes such as Message, Store,and Transport.TheAPIcanbeextended and can be subclassed to provide new protocols and to add unctionality whennecessary. In addition, the API provides concrete subclasses o the abstract classes. Thesesubclasses, including MimeMessage and MimeBodyPart, implement widely used Internet mailprotocols and conorm to the RFC822 and RFC2045 specications. The JavaMail API includes

support or the IMAP4, POP3, and SMTP protocols.The JavaMail architectural components are as ollows:

■ The abstract layer declares classes interaces and abstract methods intended to support

19C H A P T E R 1 9

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 297/326

■ The abstract layer declares classes, interaces, and abstract methods intended to supportmail handling unctions that all mail systems support.

■ The internet implementation layer implements part o the abstract layer using the RFC822and MIME internet standards.

JavaMail uses the JavaBeans Activation Framework (JAF) to encapsulate message data and tohandle commands intended to interact with that data.

For more inormation, see Chapter 5, “Conguring JavaMail Resources,” in Sun GlassFishCommunications Server 2.0 Administration Guide and the JavaMail specication at

297

http://java.sun.com/products/javamail/ . A useul JavaMail tutorial is located athttp://java.sun.com/developer/onlineTraining/JavaMail/ .

Creating a JavaMail SessionYou can create a JavaMail session in the ollowing ways:

■ In the Admin Console, open the Resources component and select JavaMail Sessions. For

details, click the Help button in the Admin Console.■ Use the asadmin create-javamail-resource command. For details, see the Sun GlassFish

Communications Server 2.0 Reerence Manual .

 JavaMail Session Properties

You can set properties or a JavaMail Session object. Every property name must start with amail- prex. The Communications Server changes the dash (-) character to a period (.)inthename o the property and saves the property to the MailConfiguration and JavaMail Session

objects. I the name o the property doesn’t start with mail-, the property is ignored.

For example, i you want to dene the property mail.from in a JavaMail Session object, rstdene the property as ollows:

■ Name – mail-from

■ Value – [email protected]

Looking Up a JavaMail SessionThe standard Java Naming and Directory Interace (JNDI) subcontext or JavaMail sessions isjava:comp/env/mail.

Registering JavaMail sessions in the mail naming subcontext o a JNDI namespace, or in one o its child subcontexts, is standard. The JNDI namespace is hierarchical, like a le system’sdirectory structure, so it is easy to nd and nest reerences. A JavaMail session is bound to al i l JNDI Th id i b il h d l i l

Creating a JavaMail Session

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 298/326

logical JNDI name. The name identies a subcontext, mail, o the root context, and a logicalname. To change the JavaMail session, you can change its entry in the JNDI namespace withouthaving to modiy the application.

The resource lookup in the application code looks like this:

InitialContext ic = new InitialContext();

String snName = "java:comp/env/mail/MyMailSession";

Session session = (Session)ic.lookup(snName);

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009298

For more inormation about the JNDI API, see Chapter 17, “Using the Java Naming andDirectory Interace.”

Sending and Reading Messages Using JavaMailThe ollowing sections describe how to send and read messages using the JavaMail API:

“To Send a Message Using JavaMail” on page 299■ “To Read a Message Using JavaMail” on page 300

▼ To Send a Message Using JavaMail

Import thepackagesthat you need.

import java.util.*;

import javax.activation.*;

import javax.mail.*;

import javax.mail.internet.*;

import javax.naming.*;

Look up theJavaMail session.

InitialContext ic = new InitialContext();

String snName = "java:comp/env/mail/MyMailSession";Session session = (Session)ic.lookup(snName);

For more inormation, see “Looking Up a JavaMail Session” on page 298.

Override the JavaMailsession properties i necessary.

For example:

Properties props = session.getProperties();

props.put("mail.from", "[email protected]");

Create a MimeMessage.

The msgRecipient msgSubject and msgTxt variables in the ollowing example contain input

1

2

3

4

Sending and Reading Messages Using JavaMail

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 299/326

The msgRecipient, msgSubject, and msgTxt variables in the ollowing example contain inputrom the user:

Message msg = new MimeMessage(session);

msg.setSubject(msgSubject);

msg.setSentDate(new Date());

msg.setFrom();

msg.setRecipients(Message.RecipientType.TO,

InternetAddress.parse(msgRecipient, false));

msg.setText(msgTxt);

Chapter 19 • Using the JavaMail API 299

Send the message.

Transport.send(msg);

▼ To Read a Message Using JavaMail

Import thepackages that you need.

import java.util.*;

import javax.activation.*;

import javax.mail.*;

import javax.mail.internet.*;

import javax.naming.*;

Look up theJavaMail session.

InitialContext ic = new InitialContext();

String snName = "java:comp/env/mail/MyMailSession";

Session session = (javax.mail.Session)ic.lookup(snName);

For more inormation, see “Looking Up a JavaMail Session” on page 298.

Override the JavaMail session propertiesi necessary.

For example:

Properties props = session.getProperties();

props.put("mail.from", "[email protected]");

Geta Store object rom the Session, then connect to the mail server using theStore object’s

connect() method.

You must supply a mail server name, a mail user name, and a password.

Store store = session.getStore();

store.connect("MailServer", "MailUser", "secret");

Get the INBOX older.

Folder folder = store.getFolder("INBOX");

It is ecient to read the Message objects (which represent messages on the server) into an array.

5

1

2

3

4

5

6

Sending and Reading MessagesUsing JavaMail

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 300/326

Message[] messages = folder.getMessages();

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009300

Using the Application Server ManagementExtensions

Sun GlassFish Communications Server uses Communications Server Management eXtensions(AMX) (http://glassfish.dev.java.net/javaee5/amx/index.html ) or management and

monitoring purposes. AMX technology exposes managed resources or remote management asthe JavaTM Management eXtensions (JMXTM) API.

The Communications Server incorporates the JMX 1.2 Reerence Implementation(http://java.sun.com/products/JavaManagement/index.jsp ), which was developed by theJava Community Process as Java Specication Request (JSR) 3 (http://jcp.org/en/jsr/

detail?id=3), and the JMX Remote API 1.0 Reerence Implementation , which is JSR 160(http://jcp.org/en/jsr/detail?id=160).

This chapter assumes some amiliarity with the JMX technology, but the AMX interaces can beused or the most part without understanding JMX. For more inormation about JMX, see theJMX specications and Reerence Implementations (http://java.sun.com/products/

JavaManagement/download.html).

For inormation about creating custom MBeans, see Chapter 14, “Developing CustomMBeans.”

This chapter contains the ollowing topics:■ “About AMX” on page 302■ “AMX MBeans” on page 303■ “Dynamic Client Proxies” on page 306

20C H A P T E R 2 0

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 301/326

■ Dynamic Client Proxies on page 306■ “Connecting to the Domain Administration Server” on page 306■ “Examining AMX Code Samples” on page 307■ “Running the AMX Samples” on page 310

301

About AMXAMX is an API that exposes all o the Communications Server conguration, monitoring andJSR 77 MBeans as easy-to-use client-side dynamic proxies implementing the AMX interaces.To understand the design and implementation o the AMX API, you can get started with thiswhite paper (http://glassfish.dev.java.net/nonav/javaee5/amx/amx.html ).

Complete API documentation or AMX is provided in theCommunications Server package(http://glassfish.dev.java.net/nonav/javaee5/amx/javadoc/index.html ).

com.sun.appserv.management

The code samples in this section are taken rom the package:

com.sun.appserv.management.sample

The Communications Server is based around the concept o administration domains. Eachdomain consists o one or more managed resources. A managed resource can be an

Communications Server instance, a cluster o such instances, or a manageable entity within aserver instance. A managed resource is o a particular type, and each resource type exposes a seto attributes and administrative operations that change the resource’s state.

Managed resources are exposed as JMX management beans, or MBeans. While the MBeans canbe accessed using standard JMX APIs (or example, MBeanServerConnection), most users ndthe use o the AMX client-side dynamic proxies much more convenient.

Virtually all components o the Communications Server are visible or monitoring andmanagement through AMX. You can use third-party tools to perorm all commonadministrative tasks programmatically, based on the JMX and JMX Remote API standards.

The AMX API consists o a set o interaces. The interaces are implemented by client-sidedynamic proxies (http://glassfish.dev.java.net/nonav/javaee5/amx/

amx.html#AMXDynamicClientProxy), each o which is associated with a server-side MBean inthe Domain Administration Server (DAS). AMX provides routines to obtain proxies orMBeans, starting with the DomainRoot interace (see http://glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/DomainRoot.html ).

Note – The term AMX interace in the context o this document should be understood as

About AMX

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 302/326

synonymous with a client-side dynamic proxy implementing that interace.

You can navigate generically through the MBean hierarchy using the

com.sun.appserv.management.base.Container interace (see http://glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/base/Container.html ).When using AMX, the interaces dened are implemented by client-side dynamic proxies, but

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009302

they also implicitly dene the MBeanInfo that is made available by the MBean or MBeanscorresponding to it. Certain operations dened in the interace might have a diferent returntype or a slightly diferent name when accessed through the MBean directly. This results romthe act that direct access to JMX requires the use o ObjectName, whereas the AMX interacesuse strongly typed proxies implementing the interace(s).

AMX MBeansAll AMX MBeans are represented as interaces in a subpackage o com.sun.appserv.management (see http://glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/package-summary.html ) andare implemented by dynamic proxies on the client-side. Note that client-side means any client,wherever it resides. AMX may be used within the server itsel such as in a custom MBean. Whileyou can access AMX MBeans directly through standard JMX APIs, most users nd the use o 

AMX interace (proxy) classes to be most convenient.

An AMX MBean belongs to an Communications Server domain. There is exactly one domainper DAS. Thus all MBeans accessible through the DAS belong to a single CommunicationsServer administrative domain. All MBeans in an Communications Server administrativedomain, and hence within the DAS, belong to the JMX domain amx. All AMX MBeans can bereached by navigating through the DomainRoot.

Note – Any MBeans that do not have the JMX domain amx are not part o AMX, and are neitherdocumented nor supported or use by clients.

AMX denes diferent types o MBean, namely, confguration MBeans, monitoring MBeans,utility MBeans and Java EE management JSR 77 (http://jcp.org/en/jsr/detail?id=77)MBeans. These MBeans are logically related in the ollowing ways:

They all implement the com.sun.appserv.management.base.AMX interace (seehttp://glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/base/AMX.html ).

■ They all have a j2eeType and name property within their ObjectName.See

AMX MBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 303/326

y j yp p p y j

com.sun.appserv.management.base.XTypes (http://glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/base/XTypes.html )andcom.sun.appserv.management.j2ee.J2EETypes (http://glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/j2ee/J2EETypes.html )orthe available values o the j2eeType property.

■ All MBeans that logically contain other MBeans implement thecom.sun.appserv.management.base.Container interace.

Chapter 20 • Using the Application Server Management Extensions 303

■ JSR 77 MBeans that have a corresponding conguration or monitoring peer expose it usinggetConfigPeer() or getMonitoringPeer(). However, there are many conguration andmonitoring MBeans that do not correspond to JSR 77 MBeans.

Confguration MBeans

Conguration inormation or a given Communications Server domain is stored in a centralrepository that is shared by all instances in that domain. The central repository can only bewritten to by the DAS. However, conguration inormation in the central repository is madeavailable to administration clients through AMX MBeans.

The conguration MBeans are those that modiy the underlying domain.xml or related les.Collectively, they orm a model representing the conguration and deployment repository andthe operations that can be perormed on them.

The Group Attribute o conguration MBeans, obtained rom getGroup(),hasavalueo 

com.sun.appserv.management.base.AMX.GROUP_CONFIGURATION .

Monitoring MBeans

Monitoring MBeans provide transient monitoring inormation about all the vital componentso the Communications Server.

The Group Attribute o monitoring MBeans, obtained rom getGroup(),hasavalueo com.sun.appserv.management.base.AMX.GROUP_MONITORING .

Utility MBeans

Utility MBeans provide commonly used services to the Communications Server.

The Group Attribute o utility MBeans, obtained rom getGroup(),hasavalueo com.sun.appserv.management.base.AMX.GROUP_UTILITY .

J EE M t MB

AMX MBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 304/326

 Java EE Management MBeans

The Java EE management MBeans implement, and in some cases extend, the managementhierarchy as dened by JSR77(http://jcp.org/en/jsr/detail?id=77), which species the

management model or the whole Java EE platorm.

The AMX JSR 77 MBeans ofer access to conguration and monitoring MBeans using thegetMonitoringPeer() and getConfigPeer() methods.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009304

The Group Attribute o Java EE management MBeans, obtained rom getGroup(),hasavalueo com.sun.appserv.management.base.AMX.GROUP_JSR77 .

Other MBeans

MBeans that do not t into one o the above our categories have the valuecom.sun.appserv.management.base.AMX.GROUP_OTHER . One such example iscom.sun.appserv.management.deploy.DeploymentMgr (see http://

glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/deploy/

DeploymentMgr.html).

MBean Notifcations

All AMX MBeans that emit Notications place a java.util.Map within the UserData eldoastandard JMX Notication, which can be obtained using Notification.getUserData() .Within the map are one or more items, which vary according to the Notication type. EachNotication type, and the data available within the Notication, is dened in the Javadoc o theMBean (AMX interace) that emits it.

Note that certain standard Notications, such asjavax.management.AttributeChangeNotification (see http://java.sun.com/

javase/6/docs/api/javax/management/AttributeChangeNotification.html )donotandcannot ollow this behavior.

Access to MBean Attributes

An AMX MBean Attribute is accessible in three ways:

■ Dotted names using MonitoringDottedNames and ConfigDottedNames

■ Attributes on MBeans using getAttribute(s) and setAttributes(s) (rom the standard

AMX MBeans

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 305/326

JMX API)

■ Getters/setters within the MBean’s interace class, or example, getPort(), setPort(),andsoon

All dotted names that are accessible through the command line interace are available asAttributes within a single MBean. This includes properties, which are provided as Attributesbeginning with the prex property., or example, server.property.myproperty .

Chapter 20 • Using the Application Server Management Extensions 305

Note – Certain attributes that ought to be o a specic type, such as int, are declared asjava.lang.String. This is because the value o the attribute may be a template o a orm suchas ${HTTP_LISTENER_PORT}.

Dynamic Client Proxies

Dynamic Client Proxies are an important part o the AMX API, and enhance ease-o-use or theprogrammer.

JMX MBeans can be used directly by an MBeanServerConnection (see http://java.sun.com/

javase/6/docs/api/javax/management/MBeanServerConnection.html ) to the server.However, client proxies greatly simpliy access to Attributes and operations on MBeans,ofering get/set methods and type-sae invocation o operations. Compiling against the AMXinteraces means that compile-time checking is perormed, as opposed to server-side runtime

checking, when invoked generically through MBeanServerConnection.

See the API documentation or the com.sun.appserv.management package and itssub-packages or more inormation about using proxies. The API documentation explains theuse o AMX with proxies. I you are using JMX directly (or example, by usingMBeanServerConnection), the return type, argument types, and method names might

 vary as needed or the diference between a strongly-typed proxy interace and genericMBeanServerConnection/ObjectName interace.

Connecting to the Domain Administration ServerAs stated in “Conguration MBeans” on page 304, the AMX API allows client applications toconnect to Communications Server instances using the DAS. All AMX connections areestablished to the DAS only: AMX does not support direct connections to individual serverinstances. This makes it simple to interact with all servers, clusters, and so on, with a single

connection.

Sample code or connecting to the DAS is shown in “Connecting to the DAS” on page 307. Thecom.sun.appserv.management.helper.Connect class (see http://

glassfish dev java net/

Dynamic Client Proxies

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 306/326

glassfish.dev.java.net/

nonav/javaee5/amx/javadoc/com/sun/appserv/management/helper/Connect.html )isalsoavailable.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009306

Examining AMX Code SamplesAn overview o the AMX API and code samples that demonstrate various uses o the AMX APIcan be ound at http://glassfish.dev.java.net/nonav/javaee5/amx/samples/javadoc/

index.html and http://glassfish.dev.java.net/

nonav/javaee5/amx/samples/javadoc/amxsamples/Samples.html .

The sample implementation is based around the SampleMain class. The principal uses o AMXdemonstrated by SampleMain are the ollowing:

■ “Starting an Communications Server” on page 308■ “Deploying an Archive” on page 309■ “Displaying the AMX MBean Hierarchy” on page 309■ “Setting Monitoring States” on page 309■ “Accessing AMX MBeans” on page 309■ “Accessing and Displaying the Attributes o an AMX MBean” on page 309■ “Listing AMX MBean Properties” on page 309■

“Perorming Queries” on page 309■ “Monitoring Attribute Changes” on page 310■ “Undeploying Modules” on page 310■ “Stopping an Communications Server” on page 310

All o these actions are perormed by commands that you give to SampleMain. Although thesecommands are executed by SampleMain, they are dened as methods o the class Samples,which is also ound in the com.sun.appserv.management.sample package.

The SampleMain Class

The SampleMain class creates a connection to a DAS, and creates an interactive loop in whichyou can run the various commands dened in Samples that demonstrate diferent uses o AMX.

Connecting to the DASThe connection to the DAS is shown in the ollowing code.

[...]

Examining AMXCode Samples

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 307/326

public static AppserverConnectionSource

connect(

final String host,

final int port,

final String user,final String password,

final TLSParams tlsParams )

throws IOException

Chapter 20 • Using the Application Server Management Extensions 307

{

final String info = "host=" + host + ", port=" + port +", user=" + user + ", password=" + password +

", tls=" + (tlsParams != null);

SampleUtil.println( "Connecting...:" + info );

final AppserverConnectionSource conn =

new AppserverConnectionSource(

AppserverConnectionSource.PROTOCOL_RMI,

host, port, user, password, tlsParams, null);

conn.getJMXConnector( false );

SampleUtil.println( "Connected: " + info );

return( conn );

}

[...]

A connection to the DAS is obtained using an instance o thecom.sun.appserv.management.client.AppserverConnectionSource class. For theconnection to be established, you must know the name o the host and port number on whichthe DAS is running, and have the correct user name, password and TLS parameters.

Ater the connection to the DAS is established, DomainRoot is obtained as ollows:

DomainRoot domainRoot = appserverConnectionSource.getDomainRoot();

This DomainRoot instance is a client-side dynamic proxy to the MBeanamx:j2eeType=X-DomainRoot,name=amx .

See the API documentation orcom.sun.appserv.management.client.AppserverConnectionSource or urther detailsabout connecting to the DAS using the AppserverConnectionSource class.

However, i you preer to work with standard JMX, instead o getting DomainRoot,youcangetthe MBeanServerConnection or JMXConnector, as shown:

MBeanServerConnection conn =

appserverConnectionSource getMBeanServerConnection( false );

Examining AMX Code Samples

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 308/326

appserverConnectionSource.getMBeanServerConnection( false );

JMXConnector jmxConn =

appserverConnectionSource.getJMXConnector( false );

Starting an Communications Server

The Samples.startServer method demonstrates how to start an Communications Server.

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009308

In this sample AMX implementation, all the tasks are perormed by the commandstart-server when you run SampleMain.Seethe startServer method to see how thiscommand is implemented. Click the method name to see the source code.

Deploying an Archive

The Samples.uploadArchive() and deploy methods demonstrate how to upload and deploy aJava EE archive le.

Displaying the AMX MBean Hierarchy

The Samples.displayHierarchy method demonstrates how to display the AMX MBeanhierarchy.

Setting Monitoring StatesThe Samples.setMonitoring method demonstrates how to set monitoring states.

Accessing AMX MBeans

The Samples.handleList method demonstrates how to access many (but not all) conguration

elements.

Accessing and Displaying the Attributes o an AMXMBean

The Samples.displayAllAttributes method demonstrates how to access and display the

attributes o an AMX MBean.

Listing AMX MBean Properties

Examining AMXCode Samples

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 309/326

The Samples.displayAllProperties method demonstrates how to list AMX MBeanproperties.

Perorming Queries

The Samples.demoQuery method demonstrates how to perorm queries.

Chapter 20 • Using the Application Server Management Extensions 309

The demoQuery() method uses other methods that are dened by Samples, namely 

displayWild(),and displayJ2EEType().

Monitoring Attribute Changes

The Samples.demoJMXMonitor method demonstrates how to monitor attribute changes.

Undeploying ModulesThe Samples.undeploy method demonstrates how to undeploy a module.

Stopping an Communications Server

The Samples.stopServer method demonstrates how to stop an Communications Server. ThestopServer method simply calls the Samples.getJ2EEServer method on a given server

instance, and then calls J2EEServer.stop.

Running the AMX SamplesThe ollowing section lists the steps to run the AMX samples.

▼ To Run the AMX SampleEnsurethat theJAR fle appserv-ext.jar hasbeen added to your classpath. Some examples

also require thatj2ee.jar be present.

Defnea SampleMain.properties fle, whichprovides the parameters requiredbyAppserverConnectionSource to connect to theDAS.

The le SampleMain.properties le should use the ollowing ormat:connect.host=localhost

connect.port=8686

connect.user=admin

connect.password=admin123

t t t t l t t t

1

2

Running the AMX Samples

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 310/326

connect.truststore=sample-truststore

connect.truststorePassword=changeme

connect.useTLS=true

Scripts areprovided in the com.sun.appserv.management.sample package to runthe AMX

samples.

Start SampleMain by running the appropriate script or your platorm:

3

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009310

■ run-samples.sh on UNIX or Linux platorms■ run-samples.bat on Microsot Windows platorms

Ater SampleMain is running, you caninteract with it by typingthe commands examined above:

■ Enter Command> start-server serverName

■ Enter Command> list-attributes

You see output like this:

--- Attributes for X-DomainRoot=amx ---

AttributeNames=[...]

BulkAccessObjectName=amx:j2eeType=X-BulkAccess,name=na

DomainConfigObjectName=amx:j2eeType=X-DomainConfig,name=na

MBeanInfoIsInvariant=true

J2EEDomainObjectName=amx:j2eeType=J2EEDomain,name=amx

AppserverDomainName=amx

ObjectName=amx:j2eeType=X-DomainRoot,name=amx

[...]■ Enter Command> show-hierarchy

You see output like this:

X-DomainRoot=amx

X-ConfigDottedNames

X-SystemInfo

X-QueryMgr

X-DeploymentMgrX-UploadDownloadMgr

X-BulkAccess

X-MonitoringDottedNames

X-JMXMonitorMgr

X-Sample

X-DomainConfig

X-WebModuleConfig=admingui

X-WebModuleConfig=adminapp

X-WebModuleConfig=com_sun_web_ui

X-JDBCResourceConfig=jdbc/__default

X-JDBCResourceConfig=jdbc/__TimerPool

X-J2EEApplicationConfig=MEjbApp

[...]

4

Running the AMX Samples

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 311/326

■ Enter Command> list

You see output like this:

--- Top-level ---

ConfigConfig: [server2-config, default-config, server-config,

server3-config]

Chapter 20 • Using the Application Server Management Extensions 311

ServerConfig: [server3, server, server2]

StandaloneServerConfig: [server3, server, server2]ClusteredServerConfig: []

ClusterConfig: []

[...]

■ Enter Command> list-properties

You see output like this:

Properties for:

amx:j2eeType=X-JDBCConnectionPoolConfig,name=DerbyPool

Password=pbPublic

DatabaseName=jdbc:derby://localhost:9092/sun-appserv-samples

User=pbPublic

[...]

■ Enter Command> query

You see output like this:

--- Queried for j2eeType=X-*ResourceConfig ---

j2eeType=X-JDBCResourceConfig,name=jdbc/__default

j2eeType=X-JDBCResourceConfig,name=jdbc/__TimerPool

[...]

■ And so on or the other commands:

Enter Command> demo-jmx-monitor

Enter Command> set-monitoring monitoringLevel (one o HIGH, LOW or OFF)

Enter Command> stop-server serverName

Enter Command> quit

Running the AMX Samples

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 312/326

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009312

Index

Numbers and Symbols@OrderBy and session cache sharing, 133

AACC, 221-222

annotation, 222naming, 222security, 221-222, 232-234

ACC clientsappclient script, 232ailover, 224invoking a JMS resource, 225-226invoking an EJB component, 223-225

Java Web Start, 226-231load balancing, 224making a remote call, 224package-appclient script, 232running, 226-231, 232SSL, 221-222, 232-234

action attribute, 51, 55activation-cong-property element, 292-293

ActivationSpec properties, 292-293AddressList

and connections, 291-292and deault JMS host, 289

Admin Console, 30Ad i Obj t R 237

Admin Console (Continued)Classpath Prex and Sux elds, 35Classpath Prex or jndi.properties, 282CMP resource conguration, 207Connector Connection Pools page, 237Connector Modules page, 237Connector Resources page, 237

Connector Service pageShutdown Timeout eld, 241connector thread pool assignment, 239Custom MBeans page, 253Debug Enabled eld, 70Deault Virtual Server eld, 161Generate RMIStubs eld, 229HPROF conguration, 75

JACC Providers page, 93JavaMail Sessions page, 298JDBC Connection Pools page, 262

Allow Non Component Callers eld, 267Non-Transactional Connections eld, 265Ping button, 263

JDBC Resources page, 263JMS Hosts page, 289

JMS Resources page, 290JMS Service page, 288JNDI page

Custom Resources page, 281External Resources page, 281

JP b ti 76

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 313/326

Admin Object Resources page, 237Admin Service page, 256App Client Modules page, 227

Audit Modules page, 93

JProbe conguration, 76Libraries eld, 38Liecycle Modules page, 249

Locale eld, 159

313

Admin Console (Continued)

Logging tab, 72, 163Message Security page

creating providers, 100enabling providers, 99

Monitor tab, 163online help or, 30Physical Destinations page, 290Realms page, 87

role mapping conguration, 85Security Manager Enabled eld, 98Security Maps tab, 240SIP Service page

SIP Message Inspection properties, 74System Classpath eld, 35, 40Thread Pools page, 239Transaction Log Location eld, 273

Transaction Service page, 272Trust Congurations page, 91, 92Virtual Servers page, 161Web Services page

Publish tab, 115Registry tab, 115Test button, 116

Write to System Log eld, 141administered objects, 290

and connectors, 237allow-concurrent-access element, 189AllowManagedFieldsInDeaultFetchGroup ag, 210AllowMediatedWriteInDeaultFetchGroup ag, 210alternate document roots, 165-166AMX

about, 302-303MBeans, 303-306proxies, 306samples, 307-310

running, 310-312annotation

Ant, 30, 43-68

ANT_HOME environment variable, 43Apache Ant, 30, 43-68appclient script, 232Application class loader, 36Application Client Container, See ACCApplication Server Management eXtensions, See AMXapplications

disabling, 54-57examples, 31-32

appserv-ext.jar le, 247appserv-jwsacc.jar le, 229appserv-tags.jar le, 147appserv-tags.tld le, 147-148AppservPasswordLoginModule class, 88AppservRealm class, 88

asadmin command, 29create-admin-object, 237create-audit-module, 93create-auth-realm, 87create-connector-connection-pool, 237, 291create-connector-resource, 237create-connector-security-map, 240create-custom-resource, 281

create-domain, 230create-javamail-resource, 298create-jdbc-connection-pool, 262

--allownoncomponentcallers option, 267--nontransactionalconnections option, 265

create-jdbc-resource, 263create-jms-host, 289create-jmsdest, 290

create-jndi-resource, 281create-jvm-options, 188, 210

com.sun.appserv.transaction.nodsyncoption, 273

 java.security.debug option, 97

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 314/326

application clients, 222EJB 3.0 specication, 173JNDI names, 278message layer, 98schema generation, 126-127security, 83

create-liecycle-module, 249create-mbean, 253-254create-message-security-provider, 100create-resource-adapter-cong, 237, 239, 240create-threadpool, 239create-trust-cong, 91, 92

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009314

asadmin command (Continued)

delete-jvm-options java.security.manager option, 98

delete-mbean, 254deploy 

and connectors, 237--availabilityenabled option, 183--libraries option, 38--precompilejsp option, 151

--retrieve option, 223, 229schema generation, 130, 204

deploy-jbi-service-assembly, 117deploydir

and connectors, 237--availabilityenabled option, 183schema generation, 130, 204

ush-jmsdest, 290

generate-jvm-report, 71get, 272, 288get-client-stubs, 224, 229

 jms-ping, 289list-mbeans, 254-255list-timers, 178migrate-timers, 178ping-connection-pool, 240, 263

publish-to-registry, 115set

custom MBean attributes, 256custom MBean disabling, 256deault message security provider, 99deault principal settings, 85

 java-web-start-enabled attribute, 227 jbi-enabled property, 118JMS service settings, 288JMX connector port, 256SIP Message Inspection properties, 73transaction service settings, 272

undeploy 

asant script (Continued)

using or JSP precompilation, 58-59using or server administration, 51-54, 57-58using or undeployment, 48-51

asinstalldir attributesun-appserv-admin task, 58sun-appserv-component task, 56sun-appserv-deploy task, 47sun-appserv-instance task, 52sun-appserv-jspc task, 59sun-appserv-undeploy task, 50

audit modules, 93-94AuditModule class, 93-94authentication

application clients, 221-222audit modules, 94

JAAS, 87-89JMS, 293message-level, 105P-asserted identity, 82, 92programmatic login, 107realms, 86single sign-on, 110-111

authorization

audit modules, 94JAAS, 87-89JACC, 93roles, 84-86

automatic schema generationor CMP, 200-206Java Persistence options, 128-131

availability conguring HTTP session persistence, 157-158conguring SIP session persistence, 157-158eature summary, 29or ACC clients, 224or SIP modules 153-154

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 315/326

schema generation, 131, 205asant script, 30, 43-68

Application Server specic tasks, 44-63disabling deployed applications and modules, 54-57updating deployed applications and modules, 60using or deployment, 44-48

or SIP modules, 153 154or stateul session beans, 180-185or web modules, 153-154

o message-driven beans, 292-293availabilityenabled attribute, 46

315

B

bin directory, 43binding attribute, 62BLOB support, 199Bootstrap class loader, 35build.xml le, 30, 32

Ccache or servlets

deault conguration, 143example conguration, 143helper class, 142, 144

cache sharing and @OrderBy, 133cache tag, 149-150CacheHelper interace, 144

cacheKeyGeneratorAttrName property, 145cachinga bean's state using version consistency, 208data using a non-transactional connection, 266EJB components, 175entities, 193JSP les, 147-151read-only beans, 187

servlet results, 141-145stateul session beans, 180using a read-only bean or, 174, 188, 209

capture-schema command, 206-207cascade attribute, 49Catalina listeners, dening custom, 164-165catalog attribute, 63certicate realm, 86

checkpoint-at-end-o-method element, 184checkpointing, 180selecting methods or, 184

class-loader element, 37, 162class loaders, 33-42

application-specic, 38-39

classpath-sux attribute, 35

classpathre attribute, 59client JAR le, 41client.policy le, 232CLOB support, 200cluster attribute, 52CMP, See container-managed persistencecmp-resource element, 207cmt-max-runtime-exceptions property, 192Comet support, 167command attribute, 57command-line server conguration, See asadmin

commandcommit options, 193Common class loader, 35

using to circumvent isolation, 40

compiling JSP les, 151component subelement, 66-68cong attribute, 52connection actory, 189ConnectionFactory interace, 290Connector class loader, 36, 250connectors, 235-245

administered objects, 237

and JDBC, 236and JMS, 236and message-driven beans, 243-245and transactions, 270conguration options, 239-242conguring, 236connection pools, 237deployment, 237

embedded, 238generic JMS, 287inbound connectivity, 242-243invalid connections, 241last agent optimization, 242

d l t 238

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 316/326

circumventing isolation, 39-42delegation hierarchy, 33-36

isolation, 38classpath, changing, 35classpath attribute, 59, 61classpath-prex attribute, 35

redeployment, 238resources, 237shutdown timeout, 241Sun Java System Application Server support, 236testing connection pools, 240thread pools, 239

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009316

container-managed persistence

conguring 1.1 nders, 210-211data types or mapping, 201-203deployment descriptor, 196-197mapping, 196perormance eatures, 207-209preetching, 208-209resource manager, 207restrictions, 214-219

support, 195-196 version consistency, 208

context, or JNDI naming, 277-280context root, 140context.xml le, 167contextroot attribute, 45, 66converged web/SIP module, 139CosNaming naming service, 279

cp attribute, 61create-admin-object command, 237create-audit-module command, 93create-auth-realm command, 87create-connector-connection-pool command, 237, 291create-connector-resource command, 237create-connector-security-map command, 240create-custom-resource command, 281

create-domain command, 230create-javamail-resource command, 298create-jdbc-connection-pool command, 262

--allownoncomponentcallers option, 267--nontransactionalconnections option, 265

create-jdbc-resource command, 263create-jms-host command, 289create-jmsdest command, 290create-jndi-resource command, 281create-jvm-options command, 188, 210

com.sun.appserv.transaction.nodsync option, 273 java.security.debug option, 97

create-liecycle-module command, 249t b d 253 254

createtables attribute, 46

custom MBeansdeployment or registration, 253-254enabling and disabling, 256handling attributes o, 256-257lie cycle, 252-253listing inormation about, 254-255location and classloading, 253redeployment, 254

the MBeanServer, 255-256undeployment, 254

custom resource, 281

DDAS, connecting to, 306

data typesor CMP mapping, 201-203or schema generation, 127-128

database properties, 124databases

as transaction resource managers, 269CMP resource manager, 207properties, 124

schema capture, 206speciying or Java Persistence, 122-123supported, 262

dbvendorname attribute, 46debug attribute, 52, 64debugging, 69-78

enabling, 69-70generating a stack trace, 71

JPDA options, 70-71DeclareRoles annotation, 84-86deault virtual server, 161deault web module, 140, 161-162deault-web.xml le, 162-163delegation, class loader, 37d l j i d j i

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 317/326

create-mbean command, 253-254create-message-security-provider command, 100create-resource-adapter-cong command, 237, 239,

240create-threadpool command, 239create-trust-cong command, 91, 92

delete-jvm-options command, java.security.manageroption, 98

delete-mbean command, 254demoQuery method, 309-310deploy command

and connectors, 237

317

deploy command (Continued)

--availabilityenabled option, 183--libraries option, 38--precompilejsp option, 151--retrieve option, 223, 229schema generation, 130, 204

deploy-jbi-service-assembly command, 117deploydir command

and connectors, 237

--availabilityenabled option, 183schema generation, 130, 204

deploymentdisabling deployed applications and modules, 54-57read-only beans, 189undeploying an application or module, 48using asant script, 44-48

deployment descriptor les, 282

deploymentplan attribute, 46destdir attribute, 58, 61, 62destinations

destination resources, 290physical, 289-290

destroy method, 145development environment

creating, 27-32

tools or developers, 29-31digest authentication, 86directory listings, disabling, 162displayHierarchy method, 309distributable SIP application, 153distributable web application, 153distributed HTTP sessions, 153-154distributed SIP sessions, 153-154dns-cache-size JVM option, 171document root, 160, 162document roots, alternate, 165-166doGet method, 145, 146Domain Administration Server, See DASdomain attribute 60

dropandcreatetables attribute, 46

droptables attribute, 49

EEJB 3.0

Java Persistence, 121-137summary o changes, 173

EJB componentscaching, 175-176calling rom a diferent application, 41ushing, 177pooling, 175-176, 179remote bean invocations, 177security, 84thread pools, 177

EJB QL queries, 210-211ejb-re element, 282ejb-re mapping, using JNDI name instead, 42EJB reerence ailover, 224EJB Timer Service, 178ejbPassivate, 187enabled attribute, 46encoding, o servlets, 159-160

endorsed standards override mechanism, 37-38Enterprise Service Bus (ESB), 117-119env-classpath-ignored attribute, 35events, server lie cycle, 247example applications, 31-32explicitcommand attribute, 57extension attribute, 61, 62external JNDI resource, 281

Fail-all-connections property, 241ailover

or ACC clients 224

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 318/326

domain attribute, 60domain.xml le

conguring single sign-on, 111Shared Chain class loader, 282System class loader, 35, 40

doPost method, 145, 146

or ACC clients, 224JMS connection, 292object types supported or, 154, 181-182o SIP module sessions, 153-154o stateul session bean state, 180-185o web module sessions, 153-154

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009318

etch group, options or, 210

le attributecomponent element, 66sun-appserv-component task, 55sun-appserv-deploy task, 45sun-appserv-undeploy task, 49sun-appserv-update task, 60

le realm, 86leset subelement, 68

nder limitation or Sybase, 135, 216nder methods, 210-211at transactions, 193ush-jmsdest command, 290ush tag, 150-151ushing o EJB components, 177orce attribute, 45, 66

Ggenerate-jvm-report command, 71generatermistubs attribute, 46generic JMS resource adapter, 287genwsdl attribute, 61get-client-stubs command, 224, 229

get command, 272, 288getCharacterEncoding method, 160getCmdLineArgs method, 249getConnection method, 264getData method, 248getEventType method, 248getHeaders method, 164getInitialContext method, 249, 280

getInstallRoot method, 249getInstanceName method, 249getLiecycleEventContext method, 248GlassFish project, 28

host attribute

server element, 64sun-appserv-component task, 55sun-appserv-deploy task, 47sun-appserv-instance task, 52sun-appserv-undeploy task, 50

HPROF proler, 75-76HTTP sessions, 151-158

cookies, 152

distributed, 153-154object types supported or ailover, 154session managers, 154-158URL rewriting, 152

HttpServletRequest, 143

Iidempotent requests, 163IMAP4 protocol, 297-298inbound connectivity, 242-243Inet Oracle JDBC driver, 134, 199, 200INIT_EVENT, 247init method, 145InitialContext naming service handle, 277-280

installation, 27-28instance attribute, 52, 64instanceport attribute, 64instantiating servlets, 145internationalization, 159Interoperable Naming Service, 279-280is-connection-validation-required property, 241is-ailure-atal attribute, 250

is-read-only-bean element, 189isolation o class loaders, 38, 39-42

 JJ2EE Connector architecture 235 245

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 319/326

Hhandling requests, 145header management, 164help or Admin Console tasks, 30high availability, See availability 

J2EE Connector architecture, 235-245J2SE policy le, 232JACC, 93JAR le, client or a deployed application, 41Java Authentication and Authorization Service

(JAAS), 87-89

319

Java Authorization Contract or Containers, See JACC

Java Business Integration (JBI), 117-119Ant tasks or, 68

 java-cong element, 35Java Database Connectivity, See JDBCJava DB database, 122-123Java Debugger (jdb), 69Java EE, security model, 82Java EE Service Engine, 117-119

Java EE tutorial, 139Java Management Extensions

See JMXJava Message Service

See JMSJava Naming and Directory Interace, See JNDIJava optional package mechanism, 37Java Persistence, 121-137

annotation or schema generation, 126-127changing the provider, 132data types or schema generation, 127-128database or, 122-123deployment options or schema

generation, 128-131restrictions, 133-137

Java Platorm Debugger Architecture, See JPDA

Java Servlet API, 140Java Transaction API (JTA), 269-275Java Transaction Service (JTS), 269-275Java Web Start, 226-231

signing client JAR les, 229-231JavaBeans, 146JavaMail

and JNDI lookups, 298-299

architecture, 297creating sessions, 298dened, 297-300messages

reading, 300sending, 299-300

JDBC (Continued)

Connection wrapper, 264creating resources, 263integrating driver JAR les, 40, 262non-component callers, 267non-transactional connections, 265-266restrictions, 267sharing connections, 264specication, 261

supported drivers, 262transaction isolation levels, 266tutorial, 261

 jdbc realm, 86JDOQL, 210-211JMS, 189, 285-296

and transactions, 270authentication, 293

checking i provider is running, 289conguring, 288-289connection ailover, 292connection pooling, 291-292creating hosts, 289creating resources, 290-291debugging, 72deault host, 289

generic resource adapter, 287JMS Service administration, 287-291load balancing, 292-293provider, 286-287restarting the client, 291SOAP messages, 294-296system connector or, 287transactions and non-persistent messages, 293

 jms-ping command, 289 jmsra system JMS connector, 287JMX, 251-257, 301-312JNDI

and EJB components, 282and JavaMail, 298-299

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 320/326

sending, 299 300session properties, 298specication, 297

JConsole, 255JDBC

connection pool creation, 262-263

and JavaMail, 298 299and liecycle modules, 249, 250, 280custom resource, 281dened, 277-283external JNDI resources, 281or message-driven beans, 190

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009320

JNDI (Continued)

global names, 278mapping reerences, 282-283name or container-managed persistence, 207tutorial, 277using instead o ejb-re mapping, 42

 join tables, 198JPDA debugging options, 70-71JProbe proler, 76-78

JSP Engine class loader, 36JSP les

caching, 147-151command-line compiler, 151precompiling, 45, 58-59, 151specication, 146tag libraries, 147

 jspc command, 151

JSR 109, 113JSR 115, 82, 93, 94JSR 12, 211JSR 160, 301JSR 181, 114JSR 196, 82, 98JSR 220, 121, 173JSR 224, 113

JSR 289, 139JSR 3, 301JSR 77, 303-306JSR 907, 272-273

K

keep attribute, 61, 62key attributeo cache tag, 149o ush tag, 150

lib directory (Continued)

or a web application, 41libraries, 38-39, 39liecycle modules, 247

allocating and reeing resources, 250and class loaders, 250and the server.policy le, 250deployment, 249-250naming environment, 280

LiecycleEvent class, 248LiecycleEventContext interace, 249LiecycleListener interace, 248LiecycleListenerImpl.java le, 248LieCycleModule class loader, 36, 250list-mbeans command, 254-255list-timers command, 178listeners, Catalina, dening custom, 164-165

load balancingand idempotent requests, 163o ACC clients, 224o message-driven beans, 292-293

load-on-startup element in web.xml, 167locale, setting deault, 159lock-when-loaded consistency level, 216log adapter, SIP Message Inspection, 73-74

logging, 72in the web container, 163login, programmatic, 107login method, 109LoginModule, 88

Mmain.xml le, 32managed elds, 198-199mapping or container-managed persistence

considerations, 197-200data types, 201-203eatures, 196

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 321/326

Llast agent optimization, 242, 270ldap realm, 86lib directory 

and the Common class loader, 35

,mapping resource reerences, 282-283markConnectionAsBad method, 264-265MBean class loader, 35MBeans

accessing, 309

321

MBeans (Continued)

AMX, 302-303, 303-306attributes, 305-306conguration, 304custom

See custom MBeansdenition, 251-257displaying attributes, 309Java EE management, 304-305listing properties, 309monitoring, 304notications, 305other types, 305proxies, 306querying, 309-310undeploying, 310

using to stop a server instance, 310utility, 304mdb-connection-actory element, 190, 191message-driven beans, 72, 189

administering, 190connection actory, 189load balancing, 292-293monitoring, 190

onMessage runtime exception, 191-192pool monitoring, 191pooling, 190restrictions, 191-192using with connectors, 243-245

message security, 98-107application-specic, 102-105responsibilities, 100sample application, 105-107

migrate-timers command, 178Migration Tool, 31mime-mapping element, 162modules

disabling 54 57

N

naming service, 277-283native library path

conguring or hpro, 75conguring or JProbe, 77

nested transactions, 193NetBeans

about, 30proler, 75

nocache attribute, o cache tag, 149nodeagent attribute, 52, 64

OOasis Web Services Security, See message security object reerences supported or ailover, 154, 181-182

online help, 30onMessage method, 191, 296Open ESB Starter Kit, 117-119Oracle automatic mapping o date and time elds, 216Oracle Inet JDBC driver, 134, 199, 200Oracle Thin Type 4 Driver, workaround or, 274Oracle TopLink Essentials, 121oracle-xa-recovery-workaround property, 275

ORDER BY validation, disabling, 214output rom servlets, 141

PP-asserted identity authentication, 82, 92package-appclient script, 232package attribute, 59, 63pass-by-reerence element, 175permissions

changing in server.policy, 95-97deault in server.policy, 95

persistence storeor HTTP sessions, 153-154, 157-158

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 322/326

disabling, 54-57liecycle, 247

monitoring in the web container, 163MSSQL version consistency triggers, 217MySQL database restrictions, 135-137, 217-219

or SIP sessions, 153-154, 157-158or stateul session bean state, 180-185

persistence.xml le, 122-123, 128physical destinations, 289-290ping-connection-pool command, 240, 263

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009322

pool monitoring or MDBs, 191

pooling, 187POP3 protocol, 297-298port attribute

server element, 64sun-appserv-component task, 55sun-appserv-deploy task, 47sun-appserv-instance task, 52sun-appserv-undeploy task, 50

portname attribute, 61precompilejsp attribute, 45, 66precompiling JSP les, 151preetching, 208-209primary key, 195, 198prolers, 74-78programmatic login, 107ProgrammaticLogin class, 109

ProgrammaticLoginPermission permission, 108-109property attribute, 52protocol attribute, 61proxies, AMX, 306publish-to-registry command, 115

Qquery hints, 131-132Queue interace, 290QueueConnectionFactory interace, 290

Rread-only beans, 174-175, 186-189, 209

deploying, 189rereshing, 187-188

readonly.relative.reresh.mode ag, 188ReadOnlyBeanNotier, 188READY_EVENT, 247realms

reerences supported or ailover, 154, 181-182

reresh attribute, o cache tag, 149reresh-period-in-seconds element, 187removing servlets, 145request object, 145res-sharing-scope deployment descriptor setting, 264resource-adapter-mid element, 244resource adapters, See connectorsresource-env-re element, 282

resource managers, 269-270resource-re element, 282resource reerences, mapping, 282-283resourcedestdir attribute, 61retrievestubs attribute, 45, 66RFC 3325, 82RMI/IIOP over SSL, 232-234roles, 84-86

Ssample applications, 31-32schema capture, 206schema generation

automatic or CMP, 200-206

Java Persistence options or automatic, 128-131scope attributeo cache tag, 149o ush tag, 150

secondary table, 197security, 81-111

ACC, 221-222, 232-234annotations, 83application level, 83audit modules, 93-94declarative, 83disabling directory listings, 162EJB components, 84goals, 82JACC, 93

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 323/326

application-specic, 87conguring, 87custom, 87-89supported, 86

redirecting a URL, 167

Java EE model, 82JMS, 293message security, 98-107o containers, 83-84programmatic, 84

323

security (Continued)

programmatic login, 107roles, 84-86server.policy le, 95-98Sun Java System Application Server eatures, 82web applications, 84

security manager, enabling and disabling, 97-98security map, 239-240sei attribute, 61

serveradministering instances using asant, 51-54changing the classpath o, 35installation, 27-28lib directory o, 35, 43lie cycle events, 247optimizing or development, 28stopping an instance using an MBean, 310

using asant script to control, 57-58 value-added eatures, 174-177

server.policy le, 95-98and liecycle modules, 250changing permissions, 95-97deault permissions, 95ProgrammaticLoginPermission, 108

server subelement, 63-66

ServerLiecycleException, 248service method, 145, 146

o SipServlet, 146servicename attribute, 61ServletContext.log messages, 141servlets, 139-146

caching, 141-145character encoding, 159-160

destroying, 145engine, 145instantiating, 145invoking using a URL, 140-141output, 141removing, 145

t h dli 145

session beans, 179

container or, 179-180optimizing perormance, 185restrictions, 185

session cache sharing and @OrderBy, 133session managers, 154-158session persistence

or SIP modules, 153-154or stateul session beans, 180-185

or web modules, 153-154object types supported, 154, 181-182

set commandcustom MBean attributes, 256custom MBean disabling, 256deault message security provider, 99deault principal settings, 85

 java-web-start-enabled attribute, 227

 jbi-enabled property, 118JMS service settings, 288JMX connector port, 256SIP Message Inspection properties, 73transaction service settings, 272

setCharacterEncoding method, 160setContentType method, 160setLocale method, 160

setMonitoring method, 309setTransactionIsolation method, 266Shared Chain class loader, 35SHUTDOWN_EVENT, 247signing client JAR les, 229-231Simple Object Access Protocol, See SOAP messagessingle sign-on, 110-111SIP applications, 139-171

distributable, 153SIP Message Inspection log adapter, 73-74SIP Message Inspection properties, 73-74SIP sessions

distributed, 153-154object types supported or ailover, 154

i ti JVM ti 171

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 324/326

request handling, 145specication, 140

class loading, 162mime-mapping, 162object unsupported or ailover, 153

sip.timer.queue JVM option, 171Sitraka web site, 76-78SJSXP parser, 119SMTP protocol, 297-298SOAP messages, 294-296

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009324

SOAP with Attachments API or Java (SAAJ), 295

solaris realm, 86sourcedestdir attribute, 61, 62specication

application clients, 222connectors, 235EJB 2.1 and CMP, 195EJB 2.1 and JDOQL queries, 210EJB 3.0, 173

JAAS, 87Java Persistence, 121JavaBeans, 146JDBC, 261JMX, 251, 301JSP, 146Liberty Alliance Project, 99programmatic security, 84

security manager, 95servlet, 140

class loading, 37WSS, 99

srcdir attribute, 58stack trace, generating, 71STARTUP_EVENT, 247, 249stateul session beans, 180

object reerences supported or ailover, 181-182session persistence, 180-185

stateless session beans, 179StAX API, 119stubs

keeping, 45, 66sun-appserv-admin task, 57-58sun-appserv-component task, 54-57

sun-appserv-deploy task, 44-48sun-appserv-instance task, 51-54sun-appserv-jspc task, 58-59sun-appserv-undeploy task, 48-51sun-appserv-update task, 60sun-cmp-mappings.xml le, 197sun ejb jar xml le 183 184

Sun Java System Message Queue (Continued)

 varhome directory, 294sun-ra.xml le, 236sun-sip.xml le, and class loaders, 37sun-web.xml le

and class loaders, 37, 162supportsTransactionIsolationLevel method, 266Sybase

nder limitation, 135, 216

lock-when-loaded limitation, 216System class loader, 35using to circumvent isolation, 40

system-classpath attribute, 35

T

tag libraries, 147tags or JSP caching, 147-151target attribute, 47, 50, 55tasks, asant script, 44-63TERMINATION_EVENT, 248thread pools

and connectors, 239or bean invocation scheduling, 177

timeout attribute, o cache tag, 149tools, or developers, 29-31Topic interace, 290TopicConnectionFactory interace, 290toplink.application-location property, 129toplink.create-ddl-jdbc-le-name property, 129toplink.ddl-generation.output-mode property, 130toplink.ddl-generation property, 129toplink.drop-ddl-jdbc-le-name property, 129TopLink Essentials, See Oracle TopLink Essentialstoplink.platorm.class.name property, 122transaction-support property, 242transactions, 269-275

administration and monitoring, 194and EJB components, 192

d i t t JMS 293

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 325/326

sun-ejb-jar.xml le, 183, 184Sun Java Studio, 31

Sun Java System Message Queue, 72, 286-287checking to see i running, 289connector or, 287

and non-persistent JMS messages, 293and session persistence, 181, 184commit options, 193conguring, 272at, 193

325

transactions (Continued)

global, 193in the Java EE tutorial, 269-275JDBC isolation levels, 266local, 193local or global scope o, 270-271logging or recovery, 273logging to a database, 273-274nested, 193

resource managers, 269-270timeouts, 176transaction manager, 272-273transaction synchronization registry, 272-273UserTransaction, 272-273

trust handler, 92

Uundeploy command

schema generation, 131, 205undeployment, using asant script, 48-51uniquetablenames attribute, 46upload attribute, 47, 64uribase attribute, 59uriroot attribute, 59URL, redirecting, 167URL rewriting, 152use-thread-pool-id element, 177use-unique-table-names property, 204user attribute

server element, 64sun-appserv-component task, 55sun-appserv-deploy task, 47sun-appserv-instance task, 52sun-appserv-undeploy task, 50

utility classes, 38-39, 39

V

 veriy attribute, 45, 67

 version consistency, 208triggers, 217

 virtual servers, 160-161deault, 161

 virtualservers attribute, 47, 64

Wweb applications, 139-171deault, 140, 161-162distributable, 153security, 84

Web class loader, 36changing delegation in, 37, 162

web container, logging and monitoring, 163

web services, 113-120creating portable artiacts, 114debugging, 114, 116deployment, 114in the Java EE tutorial, 113Open ESB and JBI, 117-119registry, 115-116security 

See message security test page, 116URL, 116WSDL le, 116

webapp attribute, 59WebDav, 168-169Woodstox parser, 119wsdl attribute, 62

wsdllocation attribute, 62WSIT, 82WSS, See message security 

X

Index

8/22/2019 821-0193

http://slidepdf.com/reader/full/821-0193 326/326

V valves, dening custom, 164-165 varhome directory, 294 verbose attribute, 59, 61, 62 verbose mode, 72

XA resource, 270-271

XML parser, 119speciying alternative, 39

Sun GlassFishCommunications Server2.0 Developer's Guide • October 2009326