821 2418
821 2418
821 2418
1Application
Development Guide
Part No: 821241812
July 2011
Copyright 2010, 2011, Oracle and/or its afliates. All rights reserved.
This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual
property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license,
transmit, distribute, exhibit, perform, publish or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software,
unless required by lawfor interoperability, is prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If you fnd any errors, please report themto us in writing.
If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is
applicable:
U.S. GOVERNMENTRIGHTS
Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or
"commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specifc supplemental regulations. As such, the use, duplication,
disclosure, modifcation, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent
applicable by the terms of the Government contract, the additional rights set forth in FAR52.227-19, Commercial Computer Software License (December 2007).
Oracle America, Inc., 500 Oracle Parkway, Redwood City, CA94065.
This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently
dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall
be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its afliates disclaimany
liability for any damages caused by use of this software or hardware in dangerous applications.
Oracle and Java are registered trademarks of Oracle and/or its afliates. Other names may be trademarks of their respective owners.
Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARCtrademarks are used under license and are trademarks or registered
trademarks of SPARCInternational, Inc. AMD, Opteron, the AMDlogo, and the AMDOpteron logo are trademarks or registered trademarks of Advanced Micro
Devices. UNIXis a registered trademark of The Open Group.
This software or hardware and documentation may provide access to or information on content, products, and services fromthird parties. Oracle Corporation and
its afliates are not responsible for and expressly disclaimall warranties of any kind with respect to third-party content, products, and services. Oracle Corporation
and its afliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.
111130@25097
Contents
Preface ...................................................................................................................................................15
Part I Development Tasks andTools ........................................................................................................... 23
1 SettingUpa Development Environment ........................................................................................ 25
Installing and Preparing the Server for Development .................................................................... 25
High Availability Features .................................................................................................................. 26
Development Tools ............................................................................................................................. 26
The asadmin Command .............................................................................................................. 27
The Administration Console ...................................................................................................... 27
The Migration Tool ..................................................................................................................... 27
The NetBeans IDE ........................................................................................................................ 27
The Eclipse IDE ............................................................................................................................ 28
Debugging Tools .......................................................................................................................... 28
Profling Tools .............................................................................................................................. 28
Sample Applications ............................................................................................................................ 28
2 Class Loaders ........................................................................................................................................29
The Class Loader Hierarchy ............................................................................................................... 30
Delegation ............................................................................................................................................ 31
Using the Java Optional Package Mechanism .................................................................................. 31
Using the Endorsed Standards Override Mechanism ..................................................................... 32
Class Loader Universes ....................................................................................................................... 32
Application-Specifc Class Loading .................................................................................................. 32
Circumventing Class Loader Isolation ............................................................................................. 34
Using the Common Class Loader .............................................................................................. 34
Sharing Libraries Across a Cluster ............................................................................................. 34
3
Packaging the Client JARfor One Application in Another Application ............................... 35
To Package the Client JARfor One Application in Another Application ............................. 35
3 DebuggingApplications ....................................................................................................................37
Enabling Debugging ........................................................................................................................... 37
To Set the Server to Automatically Start Up in Debug Mode ................................................. 38
JPDAOptions ...................................................................................................................................... 38
Generating a Stack Trace for Debugging .......................................................................................... 39
Application Client Debugging ........................................................................................................... 39
GlassFish Server Message Queue Debugging ................................................................................... 40
Enabling Verbose Mode ..................................................................................................................... 40
Class Loader Debugging ..................................................................................................................... 40
GlassFish Server Logging .................................................................................................................... 41
Profling Tools ..................................................................................................................................... 41
The NetBeans Profler ................................................................................................................. 41
The HPROF Profler .................................................................................................................... 42
The JProbe Profler ...................................................................................................................... 43
Part II DevelopingApplications andApplicationComponents .............................................................. 45
4 SecuringApplications .........................................................................................................................47
Security Goals ...................................................................................................................................... 48
GlassFish Server Specifc Security Features ...................................................................................... 48
Container Security .............................................................................................................................. 49
Declarative Security ..................................................................................................................... 49
Programmatic Security ................................................................................................................ 50
Roles, Principals, and Principal to Role Mapping ........................................................................... 50
RealmConfguration .......................................................................................................................... 52
Supported Realms ........................................................................................................................ 52
Howto Confgure a Realm .......................................................................................................... 52
Howto Set a Realmfor an Application or Module ................................................................... 53
Creating a CustomRealm ........................................................................................................... 53
JACCSupport ...................................................................................................................................... 56
Pluggable Audit Module Support ...................................................................................................... 56
Contents
Oracle GlassFish Server 3.1 Application Development Guide July 2011 4
Confguring an Audit Module .................................................................................................... 56
The AuditModule Class ............................................................................................................... 57
The server.policy File ..................................................................................................................... 58
Default Permissions ..................................................................................................................... 58
SystemProperties ......................................................................................................................... 59
Changing Permissions for an Application ................................................................................ 59
Enabling and Disabling the Security Manager ......................................................................... 61
Confguring Message Security for Web Services ............................................................................. 62
Message Security Providers ........................................................................................................ 63
Message Security Responsibilities .............................................................................................. 65
Application-Specifc Message Protection ................................................................................. 66
Understanding and Running the Sample Application ............................................................ 69
Programmatic Login ........................................................................................................................... 72
Programmatic Login Precautions .............................................................................................. 72
Granting Programmatic Login Permission .............................................................................. 73
The ProgrammaticLogin Class .................................................................................................. 73
User Authentication for Single Sign-on ............................................................................................ 74
Adding Authentication Mechanisms to the Servlet Container ...................................................... 76
The GlassFish Server and JSR196 .............................................................................................. 76
Writing a Server Authentication Module .................................................................................. 77
Sample Server Authentication Module ..................................................................................... 78
Compiling and Installing a Server Authentication Module .................................................... 82
Confguring a Server Authentication Module .......................................................................... 82
Binding a Server Authentication Module to Your Application .............................................. 83
5 DevelopingWebServices ................................................................................................................... 85
Creating Portable Web Service Artifacts .......................................................................................... 86
Deploying a Web Service .................................................................................................................... 86
The Web Service URI, WSDL File, and Test Page ........................................................................... 87
GlassFish Java EE Service Engine ...................................................................................................... 88
Using the jbi.xml File ................................................................................................................ 88
6 Usingthe Java Persistence API .......................................................................................................... 91
Specifying the Database ...................................................................................................................... 92
Additional Database Properties ......................................................................................................... 94
Contents
5
Confguring the Cache ........................................................................................................................ 94
Setting the Logging Level .................................................................................................................... 94
Using Lazy Loading ............................................................................................................................. 94
Primary Key Generation Defaults ..................................................................................................... 95
Automatic Schema Generation .......................................................................................................... 95
Annotations .................................................................................................................................. 96
Generation Options ..................................................................................................................... 96
Query Hints .......................................................................................................................................... 98
Changing the Persistence Provider ................................................................................................... 98
Restrictions and Optimizations ......................................................................................................... 99
Oracle Database Enhancements ................................................................................................. 99
Extended Persistence Context .................................................................................................... 99
Using @OrderBy with a Shared Session Cache ...................................................................... 100
Using BLOB or CLOB Types with the Inet Oraxo JDBCDriver .......................................... 100
Database Case Sensitivity .......................................................................................................... 100
Sybase Finder Limitation .......................................................................................................... 101
MySQL Database Restrictions .................................................................................................. 102
7 DevelopingWebApplications .........................................................................................................105
Using Servlets ..................................................................................................................................... 105
Caching Servlet Results ............................................................................................................. 106
About the Servlet Engine ........................................................................................................... 109
Using JavaServer Pages ..................................................................................................................... 110
JSP Tag Libraries and Standard Portable Tags ....................................................................... 110
JSP Caching ................................................................................................................................. 111
Options for Compiling JSP Files .............................................................................................. 114
Creating and Managing Sessions ..................................................................................................... 114
Confguring Sessions ................................................................................................................. 115
Session Managers ....................................................................................................................... 118
Using Comet ...................................................................................................................................... 122
Introduction to Comet .............................................................................................................. 122
Grizzly Comet ............................................................................................................................ 124
Bayeux Protocol ......................................................................................................................... 133
Advanced Web Application Features .............................................................................................. 135
Internationalization Issues ........................................................................................................ 136
Contents
Oracle GlassFish Server 3.1 Application Development Guide July 2011 6
Virtual Server Properties ........................................................................................................... 137
Class Loader Delegation ............................................................................................................ 137
Using the default-web.xml File .............................................................................................. 138
Confguring Logging and Monitoring in the Web Container .............................................. 139
Confguring Idempotent URL Requests ................................................................................. 139
Header Management ................................................................................................................. 140
Confguring Valves and Catalina Listeners ............................................................................ 140
Alternate Document Roots ....................................................................................................... 140
Using a context.xml File ............................................................................................................ 142
Enabling WebDav ...................................................................................................................... 143
Using SSI ..................................................................................................................................... 144
Using CGI ................................................................................................................................... 145
8 UsingEnterprise JavaBeans Technology ....................................................................................... 149
Value Added Features ....................................................................................................................... 149
Read-Only Beans ........................................................................................................................ 150
The pass-by-reference Element ........................................................................................... 150
Pooling and Caching .................................................................................................................. 151
Priority Based Scheduling of Remote Bean Invocations ....................................................... 152
Immediate Flushing ................................................................................................................... 152
EJB Timer Service .............................................................................................................................. 153
To Deploy an EJB Timer to a Cluster ....................................................................................... 154
Using Session Beans .......................................................................................................................... 156
About the Session Bean Containers ......................................................................................... 156
Stateful Session Bean Failover .................................................................................................. 157
Session Bean Restrictions and Optimizations ........................................................................ 162
Using Read-Only Beans .................................................................................................................... 163
Read-Only Bean Characteristics and Life Cycle ..................................................................... 164
Read-Only Bean Good Practices .............................................................................................. 165
Refreshing Read-Only Beans .................................................................................................... 165
Deploying Read-Only Beans .................................................................................................... 166
Using Message-Driven Beans .......................................................................................................... 167
Message-Driven Bean Confguration ...................................................................................... 167
Message-Driven Bean Restrictions and Optimizations ........................................................ 168
Contents
7
9 UsingContainer-ManagedPersistence .........................................................................................171
GlassFish Server Support for CMP .................................................................................................. 171
CMP Mapping ................................................................................................................................... 172
Mapping Capabilities ................................................................................................................ 172
The Mapping Deployment Descriptor File ............................................................................. 173
Mapping Considerations .......................................................................................................... 174
Automatic Schema Generation for CMP ....................................................................................... 177
Supported Data Types for CMP ............................................................................................... 177
Generation Options for CMP ................................................................................................... 179
Schema Capture ................................................................................................................................. 182
Automatic Database Schema Capture ..................................................................................... 183
Using the capture-schema Utility ........................................................................................... 183
Confguring the CMP Resource ....................................................................................................... 184
Performance-Related Features ......................................................................................................... 184
Version Column Consistency Checking ................................................................................. 184
Relationship Prefetching ........................................................................................................... 185
Read-Only Beans ........................................................................................................................ 186
Default Fetch Group Flags ................................................................................................................ 186
Confguring Queries for 1.1 Finders ............................................................................................... 187
About JDOQL Queries .............................................................................................................. 187
Query Filter Expression ............................................................................................................. 188
Query Parameters ...................................................................................................................... 189
Query Variables .......................................................................................................................... 189
JDOQL Examples ....................................................................................................................... 189
CMP Restrictions and Optimizations ............................................................................................. 191
Disabling ORDERBYValidation ............................................................................................ 191
Setting the Heap Size on DB2 ................................................................................................... 191
Eager Loading of Field State ..................................................................................................... 192
Restrictions on Remote Interfaces ........................................................................................... 192
PostgreSQL Case Insensitivity .................................................................................................. 192
No Support for lock-when-loaded on Sybase ....................................................................... 192
Sybase Finder Limitation .......................................................................................................... 193
Date and Time Fields ................................................................................................................. 193
Set RECURSIVE_TRIGGERS to false on MSSQL ...................................................................... 193
MySQL Database Restrictions .................................................................................................. 194
Contents
Oracle GlassFish Server 3.1 Application Development Guide July 2011 8
10 DevelopingJava Clients ...................................................................................................................197
Introducing the Application Client Container .............................................................................. 197
ACCSecurity .............................................................................................................................. 198
ACCNaming .............................................................................................................................. 198
Application Client Annotation ................................................................................................ 198
Java Web Start ............................................................................................................................. 199
Application Client JARFile ....................................................................................................... 199
Developing Clients Using the ACC ................................................................................................. 199
To Access an EJB Component Froman Application Client ................................................. 199
To Access a JMS Resource Froman Application Client ........................................................ 201
Using Java Web Start ................................................................................................................. 202
Using the Embeddable ACC ..................................................................................................... 212
Running an Application Client Using the appclient Script ................................................ 213
Using the package-appclient Script ..................................................................................... 214
The client.policy File ............................................................................................................ 214
Using RMI/IIOP Over SSL ........................................................................................................ 214
Connecting to a Remote EJB Module Through a Firewall .................................................... 216
Specifying a Splash Screen ........................................................................................................ 216
Setting Login Retries .................................................................................................................. 217
Using Libraries with Application Clients ................................................................................ 217
Developing Clients Without the ACC ............................................................................................ 217
To access an EJB component froma stand-alone client ........................................................ 218
To access an EJB component froma server-side module ...................................................... 219
To access a JMS resource froma stand-alone client .............................................................. 221
11 DevelopingConnectors ....................................................................................................................223
Connector Support in the GlassFish Server ................................................................................... 224
Connector Architecture for JMS and JDBC ........................................................................... 225
Connector Confguration ......................................................................................................... 225
Advanced Connector Confguration Options ............................................................................... 225
Thread Associations .................................................................................................................. 226
Security Maps ............................................................................................................................. 226
Work Security Maps .................................................................................................................. 227
Overriding Confguration Properties ...................................................................................... 227
Testing a Connector Connection Pool .................................................................................... 228
Contents
9
Flushing a Connector Connection Pool .................................................................................. 228
Handling Invalid Connections ................................................................................................. 229
Setting the Shutdown Timeout ................................................................................................. 229
Specifying the Class Loading Policy ......................................................................................... 230
Using Last Agent Optimization of Transactions ................................................................... 230
Disabling Pooling for a Connection ........................................................................................ 231
Using Application-Scoped Connectors .................................................................................. 231
Inbound Communication Support ................................................................................................. 231
Outbound Communication Support .............................................................................................. 232
Confguring a Message Driven Bean to Use a Resource Adapter ................................................ 232
12 DevelopingLifecycle Listeners ........................................................................................................235
Server Life Cycle Events .................................................................................................................... 236
The LifecycleListener Interface ........................................................................................................ 236
The LifecycleEvent Class .............................................................................................................. 236
The Server Lifecycle Event Context ................................................................................................. 237
Deploying a Lifecycle Module .......................................................................................................... 237
Considerations for Lifecycle Modules ............................................................................................ 238
13 DevelopingOSGi-enabledJava EE Applications .......................................................................... 239
Overviewof OSGi Application and GlassFish Server ................................................................... 239
Benefts of Using OSGi in Enterprise Java Applications ....................................................... 240
Developing OSGi Application Bundles for GlassFish Server ....................................................... 240
Developing Plain OSGi Bundles .............................................................................................. 241
Developing Web Application Bundles .................................................................................... 244
Developing EJB Application Bundles ...................................................................................... 246
Deploying OSGi Bundles in GlassFish Server ................................................................................ 247
Part III UsingServices andAPIs ................................................................................................................... 249
14 Usingthe JDBCAPI for Database Access ....................................................................................... 251
Statements .......................................................................................................................................... 252
Using an Initialization Statement ............................................................................................ 252
Setting a Statement Timeout .................................................................................................... 252
Contents
Oracle GlassFish Server 3.1 Application Development Guide July 2011 10
Statement Leak Detection and Leaked Statement Reclamation ........................................... 253
Statement Caching ..................................................................................................................... 253
Statement Tracing ...................................................................................................................... 254
Connections ....................................................................................................................................... 255
Transparent Pool Reconfguration .......................................................................................... 256
Disabling Pooling ....................................................................................................................... 256
Associating Connections with Threads ................................................................................... 257
CustomConnection Validation ............................................................................................... 258
Sharing Connections ................................................................................................................. 258
Marking Bad Connections ........................................................................................................ 259
Handling Invalid Connections ................................................................................................. 259
Connection Wrapping ...................................................................................................................... 260
Wrapping Connections ............................................................................................................. 260
Obtaining a Physical Connection Froma Wrapped Connection ........................................ 261
Using the Connection.unwrap() Method .............................................................................. 261
Allowing Non-Component Callers ................................................................................................. 262
Using Application-Scoped Resources ............................................................................................. 262
Restrictions and Optimizations ....................................................................................................... 263
Disabling Stored Procedure Creation on Sybase .................................................................... 263
15 UsingtheTransactionService ......................................................................................................... 265
Handling Transactions with Databases .......................................................................................... 265
Using JDBCTransaction Isolation Levels ............................................................................... 266
Using Non-Transactional Connections .................................................................................. 267
Handling Transactions with Enterprise Beans .............................................................................. 268
Flat Transactions ........................................................................................................................ 269
Global and Local Transactions ................................................................................................. 269
Commit Options ........................................................................................................................ 269
Bean-Level Container-Managed Transaction Timeouts ...................................................... 270
Handling Transactions with the Java Message Service ................................................................. 270
Transactions and Non-Persistent Messages ........................................................................... 270
Using the ConfgurableTransactionSupport Interface ......................................................... 270
The Transaction Manager, the Transaction Synchronization Registry, and
UserTransaction .............................................................................................................................. 271
Contents
11
16 Usingthe Java NamingandDirectory Interface .......................................................................... 273
Accessing the Naming Context ........................................................................................................ 273
Global JNDI Names ................................................................................................................... 274
Accessing EJB Components Using the CosNaming Naming Context .................................. 275
Accessing EJB Components in a Remote GlassFish Server ................................................... 275
Naming Environment for Lifecycle Modules ......................................................................... 276
Confguring Resources ..................................................................................................................... 276
External JNDI Resources .......................................................................................................... 277
CustomResources ...................................................................................................................... 277
Built-in Factories for CustomResources ................................................................................ 277
Disabling GlassFish Server V2 Vendor-Specifc JNDI Names ............................................. 279
Using Application-Scoped Resources ..................................................................................... 280
Using a Customjndi.properties File .......................................................................................... 280
Mapping References .......................................................................................................................... 280
17 Usingthe Java Message Service ...................................................................................................... 283
Using Application-Scoped JMS Resources ..................................................................................... 283
Load-Balanced Message Infow ....................................................................................................... 284
Authentication With ConnectionFactory .................................................................................... 284
Delivering SOAP Messages Using the JMS API ............................................................................. 285
To Send SOAP Messages Using the JMS API ......................................................................... 285
To Receive SOAP Messages Using the JMS API ..................................................................... 286
18 Usingthe JavaMail API ..................................................................................................................... 289
Introducing JavaMail ........................................................................................................................ 289
Creating a JavaMail Session .............................................................................................................. 290
JavaMail Session Properties .............................................................................................................. 290
Looking Up a JavaMail Session ........................................................................................................ 290
Sending and Reading Messages Using JavaMail ............................................................................ 291
To Send a Message Using JavaMail .......................................................................................... 291
To Read a Message Using JavaMail .......................................................................................... 292
Using Application-Scoped JavaMail Resources ............................................................................. 292
Index ................................................................................................................................................... 293
Contents
Oracle GlassFish Server 3.1 Application Development Guide July 2011 12
Tables
TABLE 21 Oracle GlassFish Server Class Loaders .................................................................... 30
TABLE 41 PredefnedSystemProperties .................................................................................. 59
TABLE 42 Message Security Provider Properties ..................................................................... 65
TABLE 61 The asadmin deploy and asadmin deploydir Generation Options ................. 97
TABLE 62 The asadmin undeploy Generation Options ........................................................ 97
TABLE 71 The cache Attributes ............................................................................................... 112
TABLE 72 The flush Attributes ............................................................................................... 114
TABLE 73 Object Types Supported for Java EEWeb Application Session State Failover . 117
TABLE 74 SSIServlet init-param Values ............................................................................ 145
TABLE 75 CGIServlet init-param Values ............................................................................ 146
TABLE 81 Object Types Supported for Java EEStateful Session Bean State Failover ........ 158
TABLE 91 Java Type to JDBCType Mappings for CMP ....................................................... 177
TABLE 92 Mappings of JDBCTypes to Database Vendor Specifc Types for CMP .......... 179
TABLE 93 The glassfish-ejb-jar.xml GenerationElements .......................................... 180
TABLE 94 The asadmin deploy and asadmin deploydir Generation Options for CMP
.................................................................................................................................... 181
TABLE 95 The asadmin undeploy Generation Options for CMP ...................................... 182
TABLE 101 OwnedJNLPFile Content ...................................................................................... 211
TABLE 102 DefaultedJNLPFile Content ................................................................................. 211
TABLE 103 MergedJNLPFile Content ..................................................................................... 211
TABLE 151 TransactionIsolationLevels .................................................................................. 266
13
14
Preface
This Application Development Guide describes howto create and run Java Platform, Enterprise
Edition (Java EE platform) applications that followthe open Java standards model for Java EE
components and APIs in the Oracle GlassFish Server environment. Topics include developer
tools, security, and debugging. This book is intended for use by software developers who create,
assemble, and deploy Java EE applications using Oracle servers and software.
This preface contains information about and conventions for the entire Oracle GlassFish Server
(GlassFish Server) documentation set.
GlassFish Server 3.1 is developed through the GlassFish project open-source community at
http://glassfish.java.net/. The GlassFish project provides a structured process for
developing the GlassFish Server platformthat makes the newfeatures of the Java EE platform
available faster, while maintaining the most important feature of Java EE: compatibility. It
enables Java developers to access the GlassFish Server source code and to contribute to the
development of the GlassFish Server. The GlassFish project is designed to encourage
communication between Oracle engineers and the community.
The following topics are addressed here:
The API specifcation for GlassFish Server 3.1, including Java EE 6 platformpackages and
nonplatformpackages that are specifc to the GlassFish Server product, is located at
http://glassfish.java.net/nonav/docs/v3/api/.
Additionally, the Java EE Specifcations (http://www.oracle.com/technetwork/java/
javaee/tech/index.html) might be useful.
For information about creating enterprise applications in the NetBeans Integrated
Development Environment (IDE), see the NetBeans Documentation, Training &Support page
(http://www.netbeans.org/kb/).
For information about the Java DB database for use with the GlassFish Server, see the Java DB
product page (http://www.oracle.com/technetwork/java/javadb/overview/index.html).
The Java EE Samples project is a collection of sample applications that demonstrate a broad
range of Java EE technologies. The Java EE Samples are bundled with the Java EE Software
Development Kit (SDK) and are also available fromthe Java EE Samples project page
(http://java.net/projects/glassfish-samples).
Typographic Conventions
The following table describes the typographic changes that are used in this book.
TABLE P2 Typographic Conventions
Typeface Meaning Example
AaBbCc123 The names of commands, fles, and
directories, and onscreen computer
output
Edit your .login fle.
Use ls -a to list all fles.
machine_name% you have mail.
AaBbCc123 What you type, contrasted with onscreen
computer output
machine_name% su
Password:
AaBbCc123 Aplaceholder to be replaced with a real
name or value
The command to remove a fle is rm flename.
AaBbCc123 Book titles, newterms, and terms to be
emphasized (note that some emphasized
items appear bold online)
Read Chapter 6 in the Users Guide.
Acache is a copy that is stored locally.
Do not save the fle.
Preface
Oracle GlassFish Server 3.1 Application Development Guide July 2011 18
Symbol Conventions
The following table explains symbols that might be used in this book.
TABLE P3 Symbol Conventions
Symbol Description Example Meaning
[ ] Contains optional arguments
and command options.
ls [-l] The -l option is not required.
{ | } Contains a set of choices for a
required command option.
-d {y|n} The -d option requires that you use
either the y argument or the n
argument.
${ } Indicates a variable
reference.
${com.sun.javaRoot} References the value of the
com.sun.javaRoot variable.
- Joins simultaneous multiple
keystrokes.
Control-A Press the Control key while you press
the Akey.
+ Joins consecutive multiple
keystrokes.
Ctrl+A+N Press the Control key, release it, and
then press the subsequent keys.
Indicates menu item
selection in a graphical user
interface.
File NewTemplates Fromthe File menu, choose New.
Fromthe Newsubmenu, choose
Templates.
Default Paths andFile Names
The following table describes the default paths and fle names that are used in this book.
TABLE P4 Default Paths and File Names
Placeholder Description Default Value
as-install Represents the base installation directory for
GlassFish Server.
In confguration fles, as-install is represented
as follows:
${com.sun.aas.installRoot}
Installations on the Oracle Solaris operating system, Linux
operating system, and Mac OS operating system:
users-home-directory/glassfish3/glassfish
Windows, all installations:
SystemDrive:\glassfish3\glassfish
Preface
19
TABLE P4 Default Paths and File Names (Continued)
Placeholder Description Default Value
as-install-parent Represents the parent of the base installation
directory for GlassFish Server.
Installations on the Oracle Solaris operating system, Linux
operating system, and Mac operating system:
users-home-directory/glassfish3
Windows, all installations:
SystemDrive:\glassfish3
domain-root-dir Represents the directory in which a domain is
created by default.
as-install/domains/
domain-dir Represents the directory in which a domain's
confguration is stored.
In confguration fles, domain-dir is
represented as follows:
${com.sun.aas.instanceRoot}
domain-root-dir/domain-name
Documentation, Support, andTraining
The Oracle web site provides information about the following additional resources:
Documentation (http://www.oracle.com/technetwork/indexes/documentation/
index.html)
Support (http://www.oracle.com/us/support/index.html)
Training (http://education.oracle.com/)
SearchingOracle Product Documentation
Besides searching Oracle product documentation fromthe Oracle Documentation
(http://www.oracle.com/technetwork/indexes/documentation/index.html) web site, you
can use a search engine by typing the following syntax in the search feld:
search-term site:oracle.com
For example, to search for broker, type the following:
broker site:oracle.com
Preface
Oracle GlassFish Server 3.1 Application Development Guide July 2011 20
Third-PartyWebSite References
Third-party URLs are referenced in this document and provide additional, related information.
Note Oracle is not responsible for the availability of third-party web sites mentioned in this
document. Oracle does not endorse and is not responsible or liable for any content, advertising,
products, or other materials that are available on or through such sites or resources. Oracle will
not be responsible or liable for any actual or alleged damage or loss caused or alleged to be
caused by or in connection with use of or reliance on any such content, goods, or services that
are available on or through such sites or resources.
Preface
21
22
Development Tasks andTools
P A R T I
23
24
Setting Up a Development Environment
This chapter gives guidelines for setting up an application development environment in the
Oracle GlassFish Server. Setting up an environment for creating, assembling, deploying, and
debugging your code involves installing the mainstreamversion of the GlassFish Server and
making use of development tools. In addition, sample applications are available.
The following topics are addressed here:
JDK
Administration Console
asadmin utility
Locate utility classes and libraries so they can be accessed by the proper class loaders. For
more information, see Using the Common Class Loader on page 34.
Confgure the Virtual Machine for the Java platform(JVMsoftware). For more information,
see Chapter 4, Administering the Virtual Machine for the Java Platform, in Oracle
GlassFish Server 3.1 Administration Guide.
HighAvailability Features
High availability features such as load balancing and session failover are discussed in detail in
the Oracle GlassFish Server 3.1-3.1.1 High Availability Administration Guide. This book
describes the following features in the following sections:
For information about HTTP session persistence, see Distributed Sessions and Persistence
on page 116.
For information about checkpointing of the stateful session bean state, see Stateful Session
Bean Failover on page 157.
For information about failover and load balancing for Java clients, see Chapter 10,
Developing Java Clients.
For information about load balancing for message-driven beans, see Load-Balanced
Message Infow on page 284.
Development Tools
The following general tools are provided with the GlassFish Server:
The docs directory contains instructions for howto use the sample.
The src/java directory under each component contains source code for the sample.
The src/conf directory under each component contains the deployment descriptors.
With a fewexceptions, sample applications followthe standard directory structure described
here: http://java.sun.com/blueprints/code/projectconventions.html.
The samples-install-dir/bp-project/main.xml fle defnes properties common to all sample
applications and implements targets needed to compile, assemble, deploy, and undeploy
sample applications. In most sample applications, the build.xml fle imports main.xml.
In addition to the Java EE 6 sample applications, samples are also available at GlassFish Samples
(https://glassfish-samples.dev.java.net/) and at as-install/glassfish/samples/.
Sample Applications
Oracle GlassFish Server 3.1 Application Development Guide July 2011 28
Class Loaders
Understanding Oracle GlassFish Server class loaders can help you determine where to place
supporting JARand resource fles for your modules and applications. For general information
about J2SE class loaders, see Understanding Network Class Loaders (http://java.sun.com/
developer/technicalArticles/Networking/classloaders/).
In a JVMimplementation, the class loaders dynamically load a specifc Java class fle needed for
resolving a dependency. For example, when an instance of java.util.Enumeration needs to be
created, one of the class loaders loads the relevant class into the environment.
The following topics are addressed here:
Delegation on page 31
Application Universe Each Java EE application has its own class loader universe, which
loads the classes in all the modules in the application.
Individually Deployed Module Universe Each individually deployed EJB JARor web
WARhas its own class loader universe, which loads the classes in the module.
Aresource such as a fle that is accessed by a servlet, JSP, or EJB component must be in one of
the following locations:
Adirectory pointed to by the application or modules classpath; for example, a web modules
classpath includes these directories:
module-name/WEB-INF/classes
module-name/WEB-INF/lib
Application-Specifc Class Loading
You can specify module- or application-specifc library classes during deployment in one of the
following ways:
Use the Administration Console. Open the Applications component, then go to the page for
the type of application or module. Select the Deploy button. Type the comma-separated
paths in the Libraries feld. For details, click the Help button in the Administration Console.
Using the Endorsed Standards Override Mechanism
Oracle GlassFish Server 3.1 Application Development Guide July 2011 32
Use the asadmin deploy command with the ----libraries option and specify
comma-separated paths. For details, see the Oracle GlassFish Server 3.1-3.1.1 Reference
Manual.
Note The Libraries feld in the Administration Console's deployment page and the
----libraries option of the asadmin deploy command do not apply to application clients.
For more information, see Using Libraries with Application Clients on page 217.
You can only specify module- or application-specifc library classes during deployment. You
can update a library JARfle using dynamic reloading or by restarting (disabling and
re-enabling) a module or application. To add or remove library JARfles, you must redeploy the
module or application.
Application libraries are included in the Applib class loader. Paths to libraries can be relative or
absolute. Arelative path is relative to domain-dir/lib/applibs. If the path is absolute, the path
must be accessible to the domain administration server (DAS). The GlassFish Server
automatically synchronizes these libraries to all remote cluster instances when the cluster is
restarted. However, libraries specifed by absolute paths are not guaranteed to be synchronized.
Tip You can use application-specifc class loading to specify a diferent XML parser than the
default GlassFish Server XML parser.
You can also use application-specifc class loading to access diferent versions of a library from
diferent applications.
If multiple applications or modules refer to the same libraries, classes in those libraries are
automatically shared. This can reduce the memory footprint and allowsharing of static
information. However, applications or modules using application-specifc libraries are not
portable. Other ways to make libraries available are described in Circumventing Class Loader
Isolation on page 34.
One library cannot reference classes fromanother library.
For general information about deployment, including dynamic reloading, see the Oracle
GlassFish Server 3.1 Application Deployment Guide.
Note If you see an access control error message when you try to use a library, you may need to
grant permission to the library in the server.policy fle. For more information, see Changing
Permissions for an Application on page 59.
Application-Specifc Class Loading
Chapter 2 Class Loaders 33
CircumventingClass Loader Isolation
Since each application or individually deployed module class loader universe is isolated, an
application or module cannot load classes fromanother application or module. This prevents
two similarly named classes in diferent applications or modules frominterfering with each
other.
To circumvent this limitation for libraries, utility classes, or individually deployed modules
accessed by more than one application, you can include the relevant path to the required classes
in one of these ways:
For a calling EJB component, add the client JARfle at the same level as the EJB component.
Then add a Class-Path entry to the MANIFEST.MF fle of the calling EJB component. The
Class-Path entry has this syntax:
Class-Path: flepath1.jar flepath2.jar ...
Each flepath is relative to the directory or JARfle containing the MANIFEST.MF fle. For
details, see the Java EE specifcation.
For a calling web component, add the client JARfle under the WEB-INF/lib directory.
If youneedtopackage the client JARwithboththe EJBandwebcomponents, set
delegate="true" inthe class-loader element of the glassfish-web.xml fle.
This changes the Web class loader so that it follows the standard class loader delegation model
and delegates to its parent before attempting to load a class itself.
For most applications, packaging the client JARfle with the calling EJB component is sufcient.
You do not need to package the client JARfle with both the EJB and web components unless
the web component is directly calling the EJB component in the dependent application.
Deploy the callingapplication.
The calling EJB or web component must specify in its glassfish-ejb-jar.xml or
glassfish-web.xml fle the JNDI name of the EJB component in the dependent application.
Using an ejb-link mapping does not work when the EJB component being called resides in
another application.
1
2
3
4
Circumventing Class Loader Isolation
Chapter 2 Class Loaders 35
You do not need to restart the server.
Circumventing Class Loader Isolation
Oracle GlassFish Server 3.1 Application Development Guide July 2011 36
Debugging Applications
This chapter gives guidelines for debugging applications in the Oracle GlassFish Server.
The following topics are addressed here:
JPDAOptions on page 38
JVMOption Select Add, type the HPROF JVMoption in the Value feld, then check its
box. The syntax of the HPROF JVMoption is as follows:
-Xrunhprof[:help]|[:param=value,param2=value2, ...]
Here is an example of params you can use:
-Xrunhprof:file=log.txt,thread=y,depth=3
The fle parameter determines where the stack dump is written.
Using help lists parameters that can be passed to HPROF. The output is as follows:
Hprof usage: -Xrunhprof[:help]|[:<option>=<value>, ...]
Option Name and Value Description Default
--------------------- ----------- -------
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)
1
2
ProflingTools
Oracle GlassFish Server 3.1 Application Development Guide July 2011 42
net=<host>:<port> send data over a socket write to file
depth=<size> stack trace depth 4
cutoff=<value> output cutoff point 0.0001
lineno=y|n line number in traces? y
thread=y|n thread in traces? n
doe=y|n dump on exit? y
Note Do not use help in the JVMOption feld. This parameter prints text to the standard
output and then exits.
The help output refers to the parameters as options, but they are not the same thing as JVM
options.
Restart the GlassFishServer.
This writes an HPROF stack dump to the fle you specifed using the fle HPROF parameter.
The JProbe Profler
Information about JProbe fromSitraka is available at http://www.quest.com/jprobe/.
After JProbe is installed using the following instructions, its libraries are loaded into the server
process.
JVMOption For each of these options, select Add, type the option in the Value feld,
then check its box
-Xbootclasspath/p:JProbe-dir/profiler/jpagent.jar
3
1
2
ProflingTools
Chapter 3 Debugging Applications 43
-Xrunjprobeagent
-Xnoclassgc
Note If any of the confguration options are missing or incorrect, the profler might
experience problems that afect the performance of the GlassFish Server.
When the server starts up with this confguration, you can attach the profler.
Set the followingenvironment variable:
JPROBE_ARGS_0=-jp_input=JPL-fle-path
See Step 6 for instructions on howto create the JPL fle.
Start the server instance.
Launchthe jpprofiler andattachtoRemote Session. The default port is 4444.
Create the JPL fle usingthe JProbe LaunchPad. Here are the requiredsettings:
a. Select Server Side for the type of application.
b. Onthe Programtab, provide the followingdetails:
Classpath as-install/lib/appserv-rt.jar
Source File Path source-code-dir (in case you want to get the line level details)
RealmConfguration on page 52
JACCSupport on page 56
Full compliance with the Java EE security model. This includes EJB and servlet role-based
authorization.
Support for single sign-on across all GlassFish Server applications within a single security
domain.
Support for several underlying authentication realms, such as simple fle and Lightweight
Directory Access Protocol (LDAP). Certifcate authentication is also supported for Secure
Socket Layer (SSL) client authentication. For Solaris, OS platformauthentication is
supported in addition to these.
Support for declarative security through GlassFish Server specifc XML-based role mapping.
Support for Java Authorization Contract for Containers (JACC) pluggable authorization as
included in the Java EE specifcation and defned by Java Specifcation Request (JSR) 115
(http://www.jcp.org/en/jsr/detail?id=115).
Support for Java Authentication Service Provider Interface for Containers as included in the
Java EE specifcation and defned by JSR196 (http://www.jcp.org/en/jsr/
detail?id=196).
Message security; see Confguring Message Security for Web Services on page 62
Single sign-on across all GlassFish Server applications within a single security domain; see
User Authentication for Single Sign-on on page 74
In the Administration Console, select the Security component under the relevant
confguration. For details, click the Help button in the Administration Console.
Use the asadmin set command. For details, see the Oracle GlassFish Server 3.1-3.1.1
Reference Manual. For example, you can set the default principal as follows.
asadmin set server-config.security-service.default-principal=dsmith
asadmin set server-config.security-service.default-principal-password=secret
You can set the default principal to role mapping as follows.
asadmin set server-config.security-service.activate-default-principal-to-role-mapping=true
asadmin set server-config.security-service.mapped-principal-class=CustomPrincipalImplClass
Roles, Principals, and Principal to Role Mapping
Chapter 4 Securing Applications 51
RealmConfguration
The following topics are addressed here:
file Stores user information in a fle. This is the default realmwhen you frst install the
GlassFish Server.
certificate Sets up the user identity in the GlassFish Server security context, and
populates it with user data obtained fromcryptographically verifed client certifcates.
solaris Allows authentication using Solaris username+password data. This realmis only
supported on the Solaris operating system, version 9 and above.
For information about confguring realms, see Howto Confgure a Realm on page 52.
HowtoConfgure a Realm
You can confgure a realmin one of these ways:
In the Administration Console, open the Security component under the relevant
confguration and go to the Realms page. For details, click the Help button in the
Administration Console.
Use the asadmin create-auth-realm command to confgure realms on local servers. For
details, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
RealmConfguration
Oracle GlassFish Server 3.1 Application Development Guide July 2011 52
HowtoSet a Realmfor anApplicationor Module
The following deployment descriptor elements have optional realm or realm-name data
subelements or attributes that override the domains default realm:
To specify an audit module using the Administration Console, open the Security
component under the relevant confguration, and select the Audit Modules component. For
details, click the Help button in the Administration Console.
You can use the asadmin create-audit-module command to confgure an audit module.
For details, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
The AuditModule Class
You can create a customaudit module by implementing a class that extends
com.sun.enterprise.security.audit.AuditModule.
For Javadoc tool pages relevant to audit modules, go to http://glassfish.java.net/nonav/
docs/v3/api/ and click on the com.sun.enterprise.security.audit package.
The AuditModule class provides default no-op implementations for each of the following
methods, which your customclass can override.
public void init(Properties props)
The preceding method is invoked during server startup when the audit module is initially
loaded. The props argument contains the properties defned for this module. The module can
do any initialization it needs in this method. If the method returns without throwing an
exception, the GlassFish Server assumes the module realmis ready to service audit requests. If
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 realmfor the
given user. The success fag 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. The
success fag indicates whether the authorization was granted or denied. The req object is the
standard HttpServletRequest object for this request. The type string is one of
hasUserDataPermission or hasResourcePermission (see JSR115 (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. The
success fag indicates whether the authorization was granted or denied. The ejb and method
strings describe the EJB component and its method that is being invoked.
public void webServiceInvocation(String uri, String endpoint, boolean success)
Pluggable Audit Module Support
Chapter 4 Securing Applications 57
This method is invoked during validation of a web service request in which the endpoint is a
servlet. The uri is the URL representation of the web service endpoint. The endpoint is the
name of the endpoint representation. The success fag indicates whether the authorization was
granted or denied.
public void ejbAsWebServiceInvocation(String endpoint, boolean success)
This method is invoked during validation of a web service request in which the endpoint is a
stateless session bean. The endpoint is the name of the endpoint representation. The success
fag indicates whether the authorization was granted or denied.
The server.policy File
Each GlassFish Server domain has its own global J2SE policy fle, located in
domain-dir/config. The fle is named server.policy.
The GlassFish Server is a Java EE compliant application server. As such, it follows the
requirements of the Java EE specifcation, including the presence of the security manager (the
Java component that enforces the policy) and a limited permission set for Java EE application
code.
The following topics are addressed here:
SystemProperties on page 59
Performance is critical
The server.policy File
Chapter 4 Securing Applications 61
To use the Administration Console, open the Security component under the relevant
confguration, and check the Security Manager Enabled box. Then restart the server. For
details, click the Help button in the Administration Console.
Use the following asadmin create-jvm-options command, then restart the server:
asadmin create-jvm-options -Djava.security.manager
To disable the security manager, use the corresponding delete-jvm-options command.
For more information about the create-jvm-options and asadmin delete-jvm-options
commands, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
ConfguringMessage Security for WebServices
In message security, security information is applied at the message layer and travels along with
the web services message. Web Services Security (WSS) is the use of XML Encryption and XML
Digital Signatures to secure messages. WSS profles the use of various security tokens including
X.509 certifcates, Security Assertion Markup Language (SAML) assertions, and
username/password tokens to achieve this.
Message layer security difers fromtransport layer security in that it can be used to decouple
message protection frommessage transport so that messages remain protected after
transmission, regardless of howmany hops they travel.
Note Message security (JSR196) is supported only in the full GlassFish Server, not in the Web
Profle.
Note In this release of the GlassFish Server, message layer annotations are not supported.
For more information about web services, see Chapter 5, Developing Web Services.
For more information about message security, see the following:
Chapter 39, Introduction to Security in the Java EE Platform, in The Java EE 6 Tutorial
The Web Services Interoperability Organization (WS-I) Basic Security Profle (BSP)
specifcation at http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html
To enable the message security providers using the Administration Console, open the
Security component under the relevant confguration, select the Message Security
component, and select SOAP. Then select XWS_ServerProvider fromthe Default Provider
list and XWS_ClientProvider fromthe Default Client Provider list. For details, click the
Help button in the Administration Console.
You can enable the message security providers using the following commands.
asadmin set
server-config.security-service.message-security-config.SOAP.default_provider=XWS_ServerProvider
asadmin set
server-config.security-service.message-security-config.SOAP.default_client_provider=XWS_ClientProvider
For more information about the asadmin set command, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
The example described in Understanding and Running the Sample Application on page 69
uses the ClientProvider and ServerProvider providers, which are enabled when the Ant
targets are run. You dont need to enable these on the GlassFish Server prior to running the
example.
If you install the OpenSSO, you have these additional provider choices:
Confguring Message Security for Web Services
Chapter 4 Securing Applications 63
AMHttpProvider This provider handles the initial end user authentication for securing
web services using Liberty ID-WSF tokens and redirects requests to the OpenSSOfor single
sign-on. To use this provider, specify it in the httpservlet-security-provider attribute
of the glassfish-web-app element in the glassfish-web.xml fle.
Liberty specifcations can be viewed at http://www.projectliberty.org/
resources/specifications.php/?f=resources/specifications.php. The WS-I BSP
specifcation can be viewed at http://www.ws-i.org/Profiles/
BasicSecurityProfile-1.0.html.
For more information about the GlassFish Server deployment descriptor fles, see the Oracle
GlassFish Server 3.1 Application Deployment Guide.
For information about confguring these providers in the GlassFish Server, see the Oracle
GlassFish Server 3.1 Security Guide. For additional information about overriding provider
settings, see Application-Specifc Message Protection on page 66.
You can create newmessage security providers in one of the following ways:
To create a message security provider using the Administration Console, open the Security
component under the relevant confguration, and select the Message Security component.
For details, click the Help button in the Administration Console.
Determining if message security is necessary at the GlassFish Server level. If so, ensuring
that this need is communicated to the systemadministrator, or taking care of implementing
message security at the GlassFish Server level.
ApplicationDeployer Responsibilities
The application deployer is responsible for the following:
Installing the sample. This is only done if the xms sample application is used to demonstrate
the use of message layer web services security.
Asystemadministrator uses the Administration Console to manage server security settings and
uses a command line tool to manage certifcate databases. Certifcates and private keys are
stored in key stores and are managed with keytool. If Network Security Services (NSS) is
installed, certifcates and private keys are stored in an NSS database, where they are managed
using certutil. Systemadministrator tasks are discussed in the Oracle GlassFish Server 3.1
Security Guide.
Application-Specifc Message Protection
When the GlassFish Server provided confguration is insufcient for your security needs, and
you want to override the default protection, you can apply application-specifc message security
to a web service.
Application-specifc security is implemented by adding the message security binding to the web
service endpoint, whether it is an EJB or servlet web service endpoint. Modify GlassFish Server
XML fles to add the message binding information.
Confguring Message Security for Web Services
Oracle GlassFish Server 3.1 Application Development Guide July 2011 66
Message security can also be specifed using a WSITsecurity policy in the WSDL fle. For
details, see the WSITpage at https://wsit.dev.java.net/.
For more information about message security providers, see Message Security Providers on
page 63.
For more details on message security binding for EJB web services, servlet web services, and
clients, see the XML fle descriptions in Appendix C, Elements of the GlassFish Server
Deployment Descriptors, in Oracle GlassFish Server 3.1 Application Deployment Guide.
For glassfish-web.xml, see The glassfsh-web.xml File in Oracle GlassFish Server 3.1
Application Deployment Guide.
Performthe authentication
Single sign-on applies to web applications confgured for the same realmand virtual server.
The realmis defned by the realm-name element in the web.xml fle. For information about
virtual servers, see Chapter 14, Administering Internet Connectivity, in Oracle GlassFish
Server 3.1 Administration Guide.
As long as users access only unprotected resources in any of 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 himself or herself, using the login
method defned for the web application currently being accessed.
After authentication, the roles associated with this user are used for access control decisions
across all associated web applications, without challenging the user to authenticate to each
application individually.
When the user logs out of one web application (for example, by invalidating the
corresponding session), the users sessions in all web applications are invalidated. Any
subsequent attempt to access a protected resource in any application requires the user to
authenticate again.
The single sign-on feature utilizes HTTP cookies to transmit a token that associates each
request with the saved user identity, so it can only be used in client environments that support
cookies.
To confgure single sign-on, set the following virtual server properties:
sso-enabled - If false, single sign-on is disabled for this virtual server, and users must
authenticate separately to every application on the virtual server. The default is false.
sso-max-inactive-seconds - Specifes the time after which a users single sign-on record
becomes eligible for purging if no client activity is received. Since single sign-on applies
across several applications on the same virtual server, access to any of the applications keeps
the single sign-on record active. The default value is 5 minutes (300 seconds). Higher values
provide longer single sign-on persistence for the users at the expense of more memory use
on the server.
The container employs the confgured mechanisms in its enforcement of the declarative
servlet security model (declared in a web.xml fle using security-constraint elements).
The JSR196 specifcation defnes a simple message processing model composed of four
interaction points:
1. secureRequest on the client
2. validateRequest on the server
3. secureResponse on the server
4. validateResponse on the client
Adding Authentication Mechanisms to the Servlet Container
Oracle GlassFish Server 3.1 Application Development Guide July 2011 76
Amessage processing runtime uses the SPI at these interaction points to delegate the
corresponding message security processing to authentication providers, also called
authentication modules, integrated into the runtime by way of the SPI.
Acompatible server-side message processing runtime, such as the GlassFish Server servlet
container, supports the validateRequest and secureResponse interaction points of the
message processing model. The servlet container uses the SPI at these interaction points to
delegate the corresponding message security processing to a server authentication module
(SAM), integrated by the SPI into the container.
Writinga Server AuthenticationModule
Akey step in adding an authentication mechanismto a compatible server-side message
processing runtime such as the GlassFish Server servlet container is acquiring a SAMthat
implements the desired authentication mechanism. One way to do that is to write the SAM
yourself.
ASAMimplements the javax.security.auth.message.module.ServerAuthModule interface as
defned by JSR196. ASAMis invoked indirectly by the message processing runtime at the
validateRequest and secureResponse interaction points. ASAMmust implement the fve
methods of the ServerAuthModule interface:
AuthStatus.SEND_FAILURE indicates that message validation failed and that the SAM
has established an appropriate failure response message in messageInfo. The container
responds to this status value by sending the response to the client.
AuthStatus.SEND_SUCCESS is not typically returned. This status value indicates the end
of a multi-message security dialog originating after the service interaction and during
the processing of the application response. The container responds to this status value by
sending the response to the client.
The validateRequest method may also throwan AuthException to indicate that the
message processing by the SAMfailed without establishing a failure response message in
messageInfo.
In the Administration Console, open the Security component under the relevant
confguration and go to the Message Security page. Set the following options:
Provider IDSpecify a unique name for the SAM, for example MySAM
Class Name Specify the fully qualifed class name, for example tip.sam.MySam
----layer HttpServlet
----classname tip.sam.MySam
----property group-name=user:realm-name=Sam
Provider name operand Specify a unique name for the SAM, for example MySAM
For details, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
Bindinga Server AuthenticationModule toYour
Application
After you install and confgure the SAM, you can bind it for use by the container on behalf of
one or more of your applications. You have two options in howyou bind the SAM, depending
on whether you are willing to repackage and redeploy your application:
If you are willing to repackage and redeploy, you can bind the SAMusing the
glassfish-web.xml fle. Set the value of the httpservlet-security-provider attribute of
the glassfish-web-app element to the SAM's confgured provider ID, for example, MySAM.
For more information about the glassfish-web.xml fle, see the Oracle GlassFish Server 3.1
Application Deployment Guide. This option leverages the native AuthConfigProvider
implementation that ships with the GlassFish Server.
Another approach is to develop your own AuthConfigProvider and register it with the
GlassFish Server AuthConfigFactory for use on behalf of your applications. For example, a
simple AuthConfigProvider can obtain, through its initialization properties, the classname
of a SAMto confgure on behalf of the applications for which the provider is registered. You
can fnd a description of the functionality of an AuthConfigProvider and of the registration
facilities provided by an AuthConfigFactory in the JSR196 specifcation.
Adding Authentication Mechanisms to the Servlet Container
Chapter 4 Securing Applications 83
84
DevelopingWeb Services
This chapter describes Oracle GlassFish Server support for web services. Java API for
XML-Based Web Services (JAX-WS) version 2.2 is supported. Java API for XML-Based Remote
Procedure Calls (JAX-RPC) version 1.1 is supported for backward compatibility.
The following topics are addressed here:
The Web Service URI, WSDL File, and Test Page on page 87
Fast Infoset in Java Web Services Developer Pack, Version 1.6 (http://
download.oracle.com/
docs/cd/E17802_01/webservices/webservices/docs/1.6/jaxrpc/fastinfoset/
manual.html)
The default pkColumnValue is the specifed name, or the default name if no name is specifed.
Automatic Schema Generation
The automatic schema generation feature of the GlassFish Server defnes database tables based
on the felds or properties in entities and the relationships between the felds or properties. This
insulates developers frommany of the database related aspects of development, allowing them
to focus on entity development. The resulting schema is usable as-is or can be given to a
database administrator for tuning with respect to performance, security, and so on.
Automatic Schema Generation
Chapter 6 Using the Java Persistence API 95
The following topics are addressed here:
Annotations on page 96
Using BLOB or CLOB Types with the Inet Oraxo JDBCDriver on page 100
Have the application maintain the order so the List is cached properly.
Refresh the session cache using EntityManager.refresh() if you don't want to maintain
the order during creation or modifcation of the List.
MySQL treats int1 and int2 as reserved words. If you want to defne int1 and int2 as felds
in your table, use int1 and int2 feld names in your SQL fle.
When VARCHAR felds get truncated, a warning is displayed instead of an error. To get an
error message, start the MySQL database in strict SQL mode.
The order of felds in a foreign key index must match the order in the explicitly created
index on the primary table.
The CREATE TABLE syntax in the SQL fle must end with the following line.
) Engine=InnoDB;
InnoDB provides MySQL with a transaction-safe (ACIDcompliant) storage engine having
commit, rollback, and crash recovery capabilities.
For a FLOAT type feld, the correct precision must be defned. By default, MySQL uses four
bytes to store a FLOAT type that does not have an explicit precision defnition. For example,
this causes a number such as 12345.67890123 to be rounded of to 12345.7 during an
INSERT. To prevent this, specify FLOAT(10,2) in the DDL fle, which forces the database to
use an eight-byte double-precision column. For more information, 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 information, see
http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html and
http://dev.mysql.com/doc/mysql/en/ansi-mode.html.
MySQL always starts a newconnection when autoCommit==true is set. This ensures that
each SQL statement forms a single transaction on its own. If you try to rollback or commit
an SQL statement, you get an error message.
javax.transaction.SystemException: java.sql.SQLException:
Cant 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 JDBCURL. For more information,
see http://forums.mysql.com/read.php?39,31326,31404.
MySQL does not allowa DELETE on a rowthat contains a reference to itself. Here is an
example that illustrates the issue.
create table EMPLOYEE (
empId int NOT NULL,
Restrictions and Optimizations
Oracle GlassFish Server 3.1 Application Development Guide July 2011 102
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 fails with the following 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 following:
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 if the foreign key feld is allowed to be null. For more information, see
http://dev.mysql.com/doc/mysql/en/innodb-foreign-key-constraints.html.
Restrictions and Optimizations
Chapter 6 Using the Java Persistence API 103
104
DevelopingWeb Applications
This chapter describes howweb applications are supported in the Oracle GlassFish Server.
The following topics are addressed here:
When caching is based on the URI, this includes user specifed parameters in the query
string. For example, a response from/garden/catalog?category=roses is diferent froma
response from/garden/catalog?category=lilies. These responses are stored under
diferent keys in the cache.
Cache size, entry timeout, and other caching behaviors are confgurable.
Entry timeout is measured fromthe time an entry is created or refreshed. To override this
timeout for an individual cache mapping, specify the cache-mapping subelement timeout.
To determine cache key generation programmatically, write a class that implements the
com.sun.appserv.web.cache.CacheKeyGenerator interface. See The CacheKeyGenerator
Interface on page 109.
All non-ASCII request parameter values specifed in cache key elements must be URL
encoded. The caching subsystemattempts to match the rawparameter 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 of classes.
The default key consists of the Servlet Path (minus pathInfo and the query string).
Aleast recently used list is maintained to evict cache entries if the maximumcache size is
exceeded.
Key generation concatenates the servlet path with key feld values, if any are specifed.
The asadmin deploy command has a ----precompilejsp option. For details, see the
Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
The jspc command line tool allows you to precompile JSP fles at the command line. For
details, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
CreatingandManagingSessions
This section describes howto create and manage HTTP sessions that allows users and
transaction information to persist between interactions.
The following topics are addressed here:
Each server instance has the same distributable web application deployed to it. The web-app
element of the web.xml deployment descriptor fle must have the distributable
subelement specifed.
All objects bound into a distributed session must be of the types listed in Table 73.
The web application must be deployed using the deploy or deploydir command with the
--availabilityenabled option set to true. See the Oracle GlassFish Server 3.1-3.1.1
Reference Manual.
Creating and Managing Sessions
Oracle GlassFish Server 3.1 Application Development Guide July 2011 116
Note Contrary to the Servlet 3.0 specifcation, GlassFish Server does not throwan
IllegalArgumentException if an object type not supported for failover is bound into a
distributed session.
Keep the distributed session size as small as possible. Session size has a direct impact on overall
systemthroughput.
In the event of an instance or hardware failure, another server instance can take over a
distributed session, with the following limitations:
The file Persistence Type on page 119, which uses a fle to store session data
The replicated Persistence Type on page 120, which uses other servers in the cluster for
session persistence
The coherence-web Persistence Type on page 121, which uses Coherence*Web for session
persistence
Note If the session manager confguration contains an error, the error is written to the server
log and the default (memory) confguration is used.
For more information, see session-manager in Oracle GlassFish Server 3.1 Application
Deployment Guide.
The memory PersistenceType
This persistence type is not designed for a production environment that requires session
persistence. It provides no session persistence. However, you can confgure it so that the session
state in memory is written to the fle systemprior to server shutdown.
To specify the memory persistence type for a specifc web application, edit the
glassfish-web.xml fle as in the following example. The persistence-type attribute is
optional, but must be set to memory if included. This overrides the web container availability
settings for the web application.
Creating and Managing Sessions
Oracle GlassFish Server 3.1 Application Development Guide July 2011 118
<glassfish-web-app>
...
<session-config>
<session-manager persistence-type="memory" />
<manager-properties>
<property name="sessionFilename" value="sessionstate" />
</manager-properties>
</session-manager>
...
</session-config>
...
</glassfish-web-app>
The only manager property that the memory persistence type supports is sessionFilename,
which is listed under manager-properties in Oracle GlassFish Server 3.1 Application
Deployment Guide. The sessionFilename property specifes the name of the fle where sessions
are serialized and persisted if the web application or the server is stopped. To disable this
behavior, specify an empty string as the value of sessionFilename. The default value is an
empty string.
For more information about the glassfish-web.xml fle, see Oracle GlassFish Server 3.1
Application Deployment Guide.
The file PersistenceType
This persistence type provides session persistence to the local fle system, and allows a single
server domain to recover the session state after a failure and restart. The session state is
persisted in the background, and the rate at which this occurs is confgurable. The store also
provides passivation and activation of the session state to help control the amount of memory
used. This option is not supported in a production environment. However, it is useful for a
development systemwith a single server instance.
Note Make sure the delete option is set in the server.policy fle, or expired fle-based
sessions might not be deleted properly. For more information about server.policy, see The
server.policy File on page 58.
To specify the file persistence type for a specifc web application, edit the glassfish-web.xml
fle as in the following example. Note that persistence-type must be set to file. This
overrides the web container availability settings for the web application.
<glassfish-web-app>
...
<session-config>
<session-manager persistence-type="file">
<store-properties>
<property name="directory" value="sessiondir" />
</store-properties>
</session-manager>
...
Creating and Managing Sessions
Chapter 7 DevelopingWeb Applications 119
</session-config>
...
</glassfish-web-app>
The file persistence type supports all the manager properties listed under
manager-properties in Oracle GlassFish Server 3.1 Application Deployment Guide except
sessionFilename, and supports the directory store property listed under store-properties
in Oracle GlassFish Server 3.1 Application Deployment Guide.
For more information about the glassfish-web.xml fle, see Oracle GlassFish Server 3.1
Application Deployment Guide.
The replicated PersistenceType
The replicated persistence type uses other servers in the cluster for session persistence.
Clustered server instances replicate session state. Each backup instance stores the replicated
data in memory. This allows sessions to be distributed. For details, see Distributed Sessions
and Persistence on page 116. In addition, you can confgure the frequency and scope of session
persistence. The other servers are also used as the passivation and activation store. Use this
option in a production environment that requires session persistence.
To use the replicated persistence type, you must enable availability. Select the Availability
Service component under the relevant confguration in the Administration Console. Check the
Availability Service box. To enable availability for the web container, select the Web Container
Availability tab, then check the Availability Service box. All instances in an GlassFish Server
cluster should have the same availability settings to ensure consistent behavior. For details, see
the Oracle GlassFish Server 3.1-3.1.1 High Availability Administration Guide.
To change settings such as persistence frequency and persistence scope for the entire web
container, use the Persistence Frequency and Persistence Scope drop-down lists on the Web
Container Availability tab in the Administration Console, or use the asadmin set command.
For example:
asadmin set
server-config.availability-service.web-container-availability.persistence-frequency=time-based
For more information, see the description of the asadmin set command in the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
To specify the replicated persistence type for a specifc web application, edit the
glassfish-web.xml fle as in the following example. Note that persistence-type must be set
to replicated. This overrides the web container availability settings for the web application.
<glassfish-web-app>
...
<session-config>
<session-manager persistence-type="replicated">
<manager-properties>
Creating and Managing Sessions
Oracle GlassFish Server 3.1 Application Development Guide July 2011 120
<property name="persistenceFrequency" value="web-method" />
</manager-properties>
<store-properties>
<property name="persistenceScope" value="session" />
</store-properties>
</session-manager>
...
</session-config>
...
</glassfish-web-app>
The replicated persistence type supports all the manager properties listed under
manager-properties in Oracle GlassFish Server 3.1 Application Deployment Guide except
sessionFilename, and supports the persistenceScope store property listed under
store-properties in Oracle GlassFish Server 3.1 Application Deployment Guide.
For more information about the glassfish-web.xml fle, see Oracle GlassFish Server 3.1
Application Deployment Guide.
To specify that web sessions for which high availability is enabled are frst bufered and then
replicated using a separate asynchronous thread, use the --asyncreplication=true option of
the asadmin deploy command. For example:
asadmin deploy --availabilityenabled=true --asyncreplication=true --name hello.war
If --asyncreplication is set to true (the default), performance is improved but availability is
reduced. If the instance where states are bufered but not yet replicated fails, the states are lost. If
set to false, performance is reduced but availability is guaranteed. States are not bufered but
immediately transmitted to other instances in the cluster.
The coherence-web PersistenceType
Built on top of Oracle Coherence, Coherence*Web is an HTTP session management module
dedicated to managing session state in clustered environments. Starting with Coherence 3.7
and GlassFish Server 3.1, there is a newfeature of Coherence*Web called ActiveCache for
GlassFish. ActiveCache for GlassFish provides Coherence*Web functionality in web
applications deployed on GlassFish Servers. Within GlassFish Server, Coherence*Web
functions as an additional web container persistence type, named coherence-web.
For information about howto confgure and deploy Coherence*Web on GlassFish Server, see
Using Coherence*Web with GlassFish Server (http://download.oracle.com/docs/cd/
E18686_01/coh.37/e18690/glassfish.htm).
Creating and Managing Sessions
Chapter 7 DevelopingWeb Applications 121
UsingComet
This section explains the Comet programming technique and howto create and deploy a
Comet-enabled application with the Oracle GlassFish Server.
The following topics are addressed here:
Grizzly Comet on page 124 Based on ARP, this includes a set of APIs that you use froma
web component to enable Comet functionality in your web application. Grizzly Comet is
specifc to the Oracle GlassFish Server.
Bayeux Protocol on page 133 Often referred to as Cometd, it consists of the JSON-based
Bayeux message protocol, a set of Dojo or Ajax libraries, and an event handler. The Bayeux
protocol uses a publish/subscribe model for server/client communication. The Bayeux
protocol is portable, but it is container dependent if you want to invoke it froman
Enterprise Java Beans (EJB) component. The Grizzly implementation of Cometd consists of
a servlet that you reference fromyour web application.
Client Technologies toUseWithComet
In addition to creating a web component that uses the Comet APIs, you need to enable your
client to accept asynchronous updates fromthe web component. To accomplish this, you can
use JavaScript, IFrames, or a framework, such as Dojo.
An IFrame is an HTML element that allows you to include other content in an HTML page. As
a result, the client can embed updated content in the IFrame without having to reload the page.
The example in this tutorial employs a combination of JavaScript and IFrames to allowthe
client to accept asynchronous updates. Aservlet included in the example writes out JavaScript
code to one of the IFrames. The JavaScript code contains the updated content and invokes a
function in the page that updates the appropriate elements in the page with the newcontent.
The next section explains the two kinds of connections that you can make to the server. While
you can use any of the client technologies listed in this section with either kind of connection, it
is more difcult to use JavaScript with an HTTP-streaming connection.
Types of Comet Connections
When working with Comet, as implemented in Grizzly, you have two diferent ways to handle
client connections to the server:
HTTP Streaming
Long Polling
HTTPStreaming
The HTTP Streaming technique keeps a connection open indefnitely. It never closes, even after
the server pushes data to the client.
Using Comet
Chapter 7 DevelopingWeb Applications 123
In the case of HTTP streaming, the application sends a single request and receives responses as
they come, reusing the same connection forever. This technique signifcantly reduces the
network latency because the client and the server don't need to open and close the connection.
The basic life cycle of an application using HTTP-streaming is:
request --> suspend --> data available --> write response --> data available --> write response
The client makes an initial request and then suspends the request, meaning that it waits for a
response. Whenever data is available, the server writes it to the response.
LongPolling
The long-polling technique is a combination of server-push and client-pull because the client
needs to resume the connection after a certain amount of time or after the server pushes an
update to the client.
The basic life cycle of an application using long-polling is:
request -> suspend --> data available --> write response --> resume
The client makes an initial request and then suspends the request. When an update is available,
the server writes it to the response. The connection closes, and the client optionally resumes the
connection.
HowtoChoose theType of Connection
If you anticipate that your web application will need to send frequent updates to the client, you
should use the HTTP-streaming connection so that the client does not have to frequently
reestablish a connection. If you anticipate less frequent updates, you should use the long-polling
connection so that the web server does not need to keep a connection open when no updates are
occurring. One caveat to using the HTTP-streaming connection is that if you are streaming
through a proxy, the proxy can bufer the response fromthe server. So, be sure to test your
application if you plan to use HTTP-streaming behind a proxy.
Grizzly Comet
The following topics are addressed here:
CometEngine: The entry point to any component using Comet. Components can be servlets,
JavaServer Pages (JSP), JavaServer Faces components, or pure Java classes.
For HTTP-Streaming:
Add the same code as for long-polling, except do not include the following line:
event.getCometContext().resumeCometHandler(this);
You don't include this line because you do not want to resume the request. Instead, you want
the connection to remain open.
Increment the counter andforwardthe response by addingthe followinglines tothe doPost
method:
counter.incrementAndGet();
CometEngine engine = CometEngine.getEngine();
CometContext<?> context =
engine.getCometContext(contextPath);
context.notify(null);
req.getRequestDispatcher("count.html").forward(req, res);
When a user clicks the button, the doPost method is called. The doPost method increments the
counter. It then obtains the current CometContext object and calls its notify method. By calling
context.notify, the doPost method triggers the onEvent method you created in the previous
step. After onEvent executes, doPost forwards the response to the clients.
3
1
2
Using Comet
Chapter 7 DevelopingWeb Applications 129
Creatingthe Client Pages
Developing the HTML pages for the client involves performing these steps:
1. Create a welcome HTML page, called index.html, that contains: one hidden frame for
connecting to the servlet through an HTTP GET; one IFrame that embeds the count.html
page, which contains the updated content; and one IFrame that embeds the button.html
page, which is used for posting updates using HTTP POST.
2. Create the count.html page that contains an HTML element that displays the current count
and the JavaScript for updating the HTML element with the newcount.
3. Create the button.html page that contains a button for the users to submit updates.
For HTTP-Streaming:
Add the same code as for long-polling, except for the following line:
parent.hidden.location.href = hidden_comet
This line invokes the doGet method of CometServlet again, which would reestablish the
connection. In the case of HTTP-Streaming, you want the connection to remain open.
Therefore, you don't include this line of code.
Using Comet
Chapter 7 DevelopingWeb Applications 131
Creatingthe Deployment Descriptor
This section describes howto create a deployment descriptor to specify howyour
Comet-enabled web application should be deployed.
Using Comet
Oracle GlassFish Server 3.1 Application Development Guide July 2011 132
ToRunthe Example
These instructions tell you howto run the Hidden Frame example.
Opentwowebbrowsers, preferably twodiferent brands of webbrowser.
Enter the followingURL inbothbrowsers:
http://localhost:8080/grizzly-comet-hidden/index.html
Whenthe frst page loads inbothbrowsers, click the buttoninone of the browsers andwatch
the count change inthe other browser window.
Bayeux Protocol
The Bayeux protocol, often referred to as Cometd, greatly simplifes the use of Comet. No
server-side coding is needed for servers such as GlassFish Server that support the Bayeux
protocol. Just enable Comet and the Bayeux protocol, then write and deploy the client.
The following topics are addressed here:
You can defne virtual server properties using the asadmin create-virtual-server
command. For example:
asadmin create-virtual-server --hosts localhost --property authRealm=ldap MyVS
For details and a complete list of virtual server properties, see create-virtual-server(1).
You can defne virtual server properties using the asadmin set command. For example:
asadmin set server-config.http-service.virtual-server.MyVS.property.authRealm="ldap"
For details, see set(1).
You can defne virtual server properties using the Administration Console. Select the HTTP
Service component under the relevant confguration, 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 and a complete list of virtual server properties, click
the Help button in the Administration Console.
Some virtual server properties can be set for a specifc web application. For details, see
glassfsh-web-app in Oracle GlassFish Server 3.1 Application Deployment Guide.
Class Loader Delegation
The Servlet specifcation recommends that a web application class loader look in the local class
loader before delegating to its parent. To make the web application class loader followthe
delegation model in the Servlet specifcation, set delegate="false" in the class-loader
element of the glassfish-web.xml fle. Its safe to do this only for a web module that does not
interact with any other modules.
The default value is delegate="true", which causes the web application class loader to delegate
in the same manner as the other class loaders. Use delegate="true" for a web application that
accesses EJB components or that acts as a web service client or endpoint. For details about
glassfish-web.xml, see Oracle GlassFish Server 3.1 Application Deployment Guide.
For a number of packages, including java.* and javax.*, symbol resolution is always
delegated to the parent class loader regardless of the delegate setting. This prevents
applications fromoverriding core Java runtime classes or changing the API versions of
specifcations that are part of the Java EE platform.
For general information about class loaders, see Chapter 2, Class Loaders.
AdvancedWeb Application Features
Chapter 7 DevelopingWeb Applications 137
Usingthe default-web.xml File
You can use the default-web.xml fle to defne features such as flters and security constraints
that apply to all web applications.
For example, directory listings are disabled by default for added security. To enable directory
listings, in your domain's default-web.xml fle, search for the defnition of the servlet whose
servlet-name is equal to default, and set the value of the init-param named listings to
true. Then redeploy your web application if it has already been deployed, or restart the server.
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
If listings is set to true, you can also determine howdirectory listings are sorted. Set the value
of the init-param named sortedBy to NAME, SIZE, or LAST_MODIFIED. Then redeploy your web
application if it has already been deployed, or restart the server.
<init-param>
<param-name>sortedBy</param-name>
<param-value>LAST_MODIFIED</param-value>
</init-param>
The mime-mapping elements in default-web.xml are global and inherited by all web
applications. You can override these mappings or defne your own using mime-mapping
elements in your web application's web.xml fle. For more information about mime-mapping
elements, see the Servlet specifcation.
You can use the Administration Console to edit the default-web.xml fle. For details, click the
Help button in the Administration Console. As an alternative, you can edit the fle directly using
the following steps.
Exact match
Extension match
For example, the following properties specify three glassfish-web.xml docroots. The URI
pattern of the frst alternate docroot uses an exact match, whereas the URI patterns of the
second and third alternate docroots use extension and longest path prefx 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"/>
The value of each alternate docroot has two components: The frst component, from, specifes
the alternate docroot's URI pattern, and the second component, dir, specifes the alternate
docroot's physical location (directory).
Suppose the above examples belong to a web application deployed at
http://company22.com/myapp. The frst alternate docroot maps any requests with this URL:
http://company22.com/myapp/my.jpg
To this resource:
/svr/images/jpg/my.jpg
The second alternate docroot maps any requests with a *.jpg sufx, such as:
http://company22.com/myapp/*.jpg
To this physical location:
/svr/images/jpg
AdvancedWeb Application Features
Chapter 7 DevelopingWeb Applications 141
The third alternate docroot maps any requests whose URI starts with /myapp/jpg/, such as:
http://company22.com/myapp/jpg/*
To the same directory as the second alternate docroot.
For example, the second alternate docroot maps this request:
http://company22.com/myapp/abc/def/my.jpg
To:
/srv/images/jpg/abc/def/my.jpg
The third alternate docroot maps:
http://company22.com/myapp/jpg/abc/resource
To:
/srv/images/jpg/abc/resource
If a request does not match any of the target web application's alternate docroots, or if the target
web application does not specify any alternate docroots, the request is served fromthe web
application's standard docroot, as usual.
Usinga context.xml File
You can defne a context.xml fle for all web applications, for web applications assigned to a
specifc virtual server, or for a specifc web application.
To defne a global context.xml fle, place the fle in the domain-dir/config directory and name
it context.xml.
Use the contextXmlDefault property to specify the name and the location, relative to
domain-dir, of the context.xml fle for a specifc virtual server. Specify this property in one of
the following ways:
In the Administration Console, open the HTTP Service component under the relevant
confguration. Open the Virtual Servers component and scroll down to the bottomof the
page. Enter contextXmlDefault as the property name and the path and fle name relative to
domain-dir as the property value.
Use the asadmin set command for an existing virtual server. For example:
asadmin set server-config.http-service.virtual-server.vs1.property.contextXmlDefault=config/myctx.xml
AdvancedWeb Application Features
Oracle GlassFish Server 3.1 Application Development Guide July 2011 142
To defne a context.xml fle for a specifc web application, place the fle in the META-INF
directory and name it context.xml.
For more information about virtual server properties, see Virtual Server Properties on
page 137. For more information about the context.xml fle, see The Context Container
(http://tomcat.apache.org/tomcat-5.5-doc/config/context.html). Context parameters,
environment entries, and resource defnitions in context.xml are supported in the GlassFish
Server.
EnablingWebDav
To enable WebDav in the GlassFish Server, you edit the web.xml and glassfish-web.xml fles
as follows.
First, enable the WebDav servlet in your web.xml fle:
<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>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
</servlet>
Then defne the servlet mapping associated with your WebDav servlet in your web.xml fle:
<servlet-mapping>
<servlet-name>webdav</servlet-name>
<url-pattern>/webdav/*</url-pattern>
</servlet-mapping>
To protect the WebDav servlet so other users can't modify it, add a security constraint in your
web.xml fle:
<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>
AdvancedWeb Application Features
Chapter 7 DevelopingWeb Applications 143
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
<security-role>
<role-name>Admin</role-name>
</security-role>
</security-constraint>
Then defne a security role mapping in your glassfish-web.xml fle:
<security-role-mapping>
<role-name>Admin</role-name>
<group-name>Admin</group-name>
</security-role-mapping>
If you are using the file realm, create a user and password. For example:
asadmin create-file-user --groups Admin --authrealmname default admin
Enable the security manager as described in Enabling and Disabling the Security Manager on
page 61.
You can nowuse any WebDav client by connecting to the WebDav servlet URL, which has this
format:
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 fle to enable it for all applications,
but you can't set up a security role mapping to protect it.
UsingSSI
To enable SSI (server-side includes) processing for a specifc web module, add the SSIServlet
to your web.xml fle as follows:
<web-app>
<servlet>
<servlet-name>ssi</servlet-name>
<servlet-class>org.apache.catalina.ssi.SSIServlet</servlet-class>
</servlet>
...
<servlet-mapping>
<servlet-name>ssi</servlet-name>
AdvancedWeb Application Features
Oracle GlassFish Server 3.1 Application Development Guide July 2011 144
<url-pattern>*.shtml</url-pattern>
</servlet-mapping>
...
<mime-mapping>
<extension>shtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
</web-app>
To enable SSI processing for all web modules, un-comment the corresponding sections in the
default-web.xml fle.
If the mime-mapping is not specifed in web.xml, GlassFish Server attempts to determine the
MIME type fromdefault-web.xml or the operating systemdefault.
You can confgure the following init-param values for the SSIServlet.
TABLE 74 SSIServlet init-param Values
init-param Type Default Description
bufered boolean false Specifes whether the output should be
bufered.
debug int 0 (for no debugging) Specifes the debugging level.
expires Long Expires header in
HTTP response not
set
Specifes the expiration time in seconds.
inputEncoding String operating system
encoding
Specifes encoding for the SSI input if there is
no URL content encoding specifed.
isVirtualWebappRelative boolean false (relative to the
given SSI fle)
Specifes whether the virtual path of the
#include directive is relative to the
content-root.
outputEncoding String UTF-8 Specifes encoding for the SSI output.
For more information about SSI, see http://httpd.apache.org/docs/2.2/mod/
mod_include.html.
UsingCGI
To enable CGI (common gateway interface) processing for a specifc web module, add the
CGIServlet to your web.xml fle as follows:
<web-app>
<servlet>
<servlet-name>cgi</servlet-name>
AdvancedWeb Application Features
Chapter 7 DevelopingWeb Applications 145
<servlet-class>org.apache.catalina.servlets.CGIServlet</servlet-class>
</servlet>
...
<servlet-mapping>
<servlet-name>cgi</servlet-name>
<url-pattern>/cgi-bin/*</url-pattern>
</servlet-mapping>
</web-app>
To enable CGI processing for all web modules, un-comment the corresponding sections in the
default-web.xml fle.
Package the CGI programunder the cgiPathPrefix. The default cgiPathPrefix is
WEB-INF/cgi. For security, it is highly recommended that the contents and binaries of CGI
programs be prohibited fromdirect viewing or download. For information about hiding
directory listings, see Using the default-web.xml File on page 138.
Invoke the CGI programusing a URL of the following format:
http://host:8080/context-root/cgi-bin/cgi-name
For example:
http://localhost:8080/mycontext/cgi-bin/hello
You can confgure the following init-param values for the CGIServlet.
TABLE 75 CGIServlet init-param Values
init-param Type Default Description
cgiPathPrefx String WEB-INF/cgi Specifes the subdirectory containing the
CGI programs.
debug int 0 (for no debugging) Specifes the debugging level.
executable String perl Specifes the executable for running the
CGI script.
parameterEncoding String System.getProperty
("file.encoding",
"UTF-8")
Specifes the parameter's encoding.
passShellEnvironment boolean false Specifes whether to pass shell environment
properties to the CGI program.
To work with a native executable, do the following:
1. Set the value of the init-param named executable to an empty String in the web.xml fle.
2. Make sure the executable has its executable bits set correctly.
AdvancedWeb Application Features
Oracle GlassFish Server 3.1 Application Development Guide July 2011 146
3. Use directory deployment to deploy the web module. Do not deploy it as a WARfle,
because the executable bit information is lost during the process of jar and unjar. For more
information about directory deployment, see the Oracle GlassFish Server 3.1 Application
Deployment Guide.
AdvancedWeb Application Features
Chapter 7 DevelopingWeb Applications 147
148
Using Enterprise JavaBeans Technology
This chapter describes howEnterprise JavaBeans (EJB) technology is supported in the Oracle
GlassFish Server.
The following topics are addressed here:
Always refreshed
Periodically refreshed
Never refreshed
Programmatically refreshed
Read-only beans are best suited for situations where the underlying data never changes, or
changes infrequently. For further information and usage guidelines, see Using Read-Only
Beans on page 163.
The pass-by-reference Element
The pass-by-reference element in the glassfish-ejb-jar.xml fle allows you to specify the
parameter passing semantics for colocated remote EJB invocations. This is an opportunity to
improve performance. However, use of this feature results in non-portable applications. See
pass-by-reference in Oracle GlassFish Server 3.1 Application Deployment Guide.
Value Added Features
Oracle GlassFish Server 3.1 Application Development Guide July 2011 150
PoolingandCaching
The EJB container of the GlassFish Server pools anonymous instances (message-driven beans,
stateless session beans, and entity beans) to reduce the overhead of creating and destroying
objects. The EJB container maintains the free pool for each bean that is deployed. Bean
instances in the free pool have no identity (that is, no primary key associated) and are used to
serve method calls. The free beans are also used to serve all methods for stateless session beans.
Bean instances in the free pool transition froma Pooled state to a Cached state after ejbCreate
and the business methods run. The size and behavior of each pool is controlled using
pool-related properties in the EJB container or the glassfish-ejb-jar.xml fle.
In addition, the GlassFish Server supports a number of tunable parameters that can control the
number of stateful instances (stateful session beans and entity beans) cached as well as the
duration they are cached. Multiple bean instances that refer to the same database rowin a table
can be cached. The EJB container maintains a cache for each bean that is deployed.
To achieve scalability, the container selectively evicts some bean instances fromthe cache,
usually when cache overfows. These evicted bean instances return to the free bean pool. The
size and behavior of each cache can be controlled using the cache-related properties in the EJB
container or the glassfish-ejb-jar.xml fle.
Pooling and caching parameters for the glassfish-ejb-jar.xml fle are described in
bean-cache in Oracle GlassFish Server 3.1 Application Deployment Guide.
PoolingParameters
One of the most important parameters for GlassFish Server pooling is steady-pool-size.
When steady-pool-size is set to a value greater than 0, the container not only pre-populates
the bean pool with the specifed number of beans, but also attempts to ensure that this number
of beans is always available in the free pool. This ensures that there are enough beans in the
ready-to-serve state to process user requests.
Note that the steady-pool-size and max-pool-size parameters only govern the number of
instances that are pooled over a long period of time. They do not necessarily guarantee that the
number of instances that may exist in the JVMat a given time will not exceed the value specifed
by max-pool-size. For example, suppose an idle stateless session container has a
fully-populated pool with a steady-pool-size of 10. If 20 concurrent requests arrive for the
EJB component, the container creates 10 additional instances to satisfy the burst of requests.
The advantage of this is that it prevents the container fromblocking any of the incoming
requests. However, if the activity dies down to 10 or fewer concurrent requests, the additional
10 instances are discarded.
Another parameter, pool-idle-timeout-in-seconds, allows the administrator to specify the
amount of 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 for this
specifed duration.
Value Added Features
Chapter 8 Using Enterprise JavaBeans Technology 151
CachingParameters
GlassFish Server provides a way that completely avoids caching of entity beans, using commit
option C. Commit option Cis particularly useful if beans are accessed in large number but very
rarely reused. For additional information, refer to Commit Options on page 269.
The GlassFish Server caches can be either bounded or unbounded. Bounded caches have limits
on the number of beans that they can hold beyond which beans are passivated. For stateful
session beans, there are three ways (LRU, NRUand FIFO) of picking victimbeans when cache
overfowoccurs. Caches can also passivate beans that are idle (not accessed for a specifed
duration).
Priority BasedSchedulingof Remote BeanInvocations
You can create multiple thread pools, each having its own work queues. An optional element in
the glassfish-ejb-jar.xml fle, use-thread-pool-id, specifes the thread pool that processes
the requests for the bean. The bean must have a remote interface, or use-thread-pool-id is
ignored. You can create diferent thread pools and specify the appropriate thread pool IDfor a
bean that requires a quick response time. If there is no such thread pool confgured or if the
element is absent, the default thread pool is used.
Immediate Flushing
Normally, all entity bean updates within a transaction are batched and executed at the end of
the transaction. The only exception is the database fush that precedes execution of a fnder or
select query.
Since a transaction often spans many method calls, you might want to fnd out if the updates
made by a method succeeded or failed immediately after method execution. To force a fush at
the end of a methods execution, use the flush-at-end-of-method element in the
glassfish-ejb-jar.xml fle. Only non-fnder methods in an entity bean can be fush-enabled.
(For an EJB 2.1 bean, these methods must be in the Local, Local Home, Remote, or Remote
Home interface.) See fush-at-end-of-method in Oracle GlassFish Server 3.1 Application
Deployment Guide.
Upon completion of the method, the EJB container updates the database. Any exception
thrown by the underlying data store is wrapped as follows:
If the method that triggered the fush is a create method, the exception is wrapped with
CreateException.
If the method that triggered the fush is a remove method, the exception is wrapped with
RemoveException.
steady-pool-size
resize-quantity
max-pool-size
pool-idle-timeout-in-seconds
For more information about glassfish-ejb-jar.xml, see The glassfsh-ejb-jar.xml File in
Oracle GlassFish Server 3.1 Application Deployment Guide.
The GlassFish Server provides the wscompile and wsdeploy tools to help you implement a web
service endpoint as a stateless session bean. For more information about these tools, see the
Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
Using Session Beans
Oracle GlassFish Server 3.1 Application Development Guide July 2011 156
Stateful Container
The stateful container manages the stateful session beans, which, by defnition, carry the
client-specifc state. There is a one-to-one relationship between the client and the stateful
session beans. At creation, each stateful session bean (SFSB) is given a unique session IDthat is
used to access the session bean so that an instance of a stateful session bean is accessed by a
single client only.
Stateful session beans are managed using cache. The size and behavior of stateful session beans
cache are controlled by specifying the following glassfish-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 specifes the maximumnumber of session beans that are held in
cache. If the cache overfows (when the number of beans exceeds max-cache-size), the
container then passivates some beans or writes out the serialized state of the bean into a fle. The
directory in which the fle is created is obtained fromthe EJB container using the confguration
APIs.
For more information about glassfish-ejb-jar.xml, see The glassfsh-ejb-jar.xml File in
Oracle GlassFish Server 3.1 Application Deployment Guide.
The passivated beans are stored on the fle system. The Session Store Location setting in the EJB
container allows the administrator to specify the directory where passivated beans are stored.
By default, passivated stateful session beans are stored in application-specifc subdirectories
created under domain-dir/session-store.
Note Make sure the delete option is set in the server.policy fle, or expired fle-based
sessions might not be deleted properly. For more information about server.policy, see The
server.policy File on page 58.
The Session Store Location setting also determines where the session state is persisted if it is not
highly available; see Choosing a Persistence Store on page 159.
Stateful SessionBeanFailover
An SFSBs state can be saved in a persistent store in case a server instance fails. The state of an
SFSB is saved to the persistent store at predefned points in its life cycle. This is called
checkpointing. If SFSB checkpointing is enabled, checkpointing generally occurs after any
transaction involving the SFSB is completed, even if the transaction rolls back.
Using Session Beans
Chapter 8 Using Enterprise JavaBeans Technology 157
However, if an SFSB participates in a bean-managed transaction, the transaction might be
committed in the middle of the execution of a bean method. Since the beans state might be
undergoing transition as a result of the method invocation, this is not an appropriate instant to
checkpoint the beans state. In this case, the EJB container checkpoints the beans state at the end
of the corresponding method, provided the bean is not in the scope of another transaction when
that method ends. If a bean-managed transaction spans across multiple methods,
checkpointing is delayed until there is no active transaction at the end of a subsequent method.
The state of an SFSB is not necessarily transactional and might be signifcantly modifed as a
result of non-transactional business methods. If this is the case for an SFSB, you can specify a list
of checkpointed methods. If SFSB checkpointing is enabled, checkpointing occurs after any
checkpointed methods are completed.
The following table lists the types of references that SFSB failover supports. All objects bound
into an SFSB must be one of the supported types. In the table, No indicates that failover for the
object type might not work in all cases and that no failover support is provided. However,
failover might work in some cases for that object type. For example, failover might work
because the class implementing that type is serializable.
TABLE 81 Object Types Supported for Java EE Stateful Session Bean State Failover
Java Object Type Failover Support
Colocated or distributed stateless session, stateful
session, or entity bean reference
Yes
JNDI context Yes, InitialContext and java:comp/env
UserTransaction Yes, but if the instance that fails is never restarted, any
prepared global transactions are lost and might not be
correctly rolled back or committed.
JDBCDataSource No
Java Message Service (JMS) ConnectionFactory,
Destination
No
JavaMail Session No
Connection Factory No
Administered Object No
Web service reference No
Serializable Java types Yes
Extended persistence context No
Using Session Beans
Oracle GlassFish Server 3.1 Application Development Guide July 2011 158
For more information about the InitialContext, see Accessing the Naming Context on
page 273. For more information about transaction recovery, see Chapter 15, Using the
Transaction Service. For more information about Administered Objects, see Administering
JMS Physical Destinations in Oracle GlassFish Server 3.1 Administration Guide.
Note Idempotent URLs are supported along the HTTP path, but not the RMI-IIOP path. For
more information, see Confguring Idempotent URL Requests on page 139.
If a server instance to which an RMI-IIOP client request is sent crashes during the request
processing (before the response is prepared and sent back to the client), an error is sent to the
client. The client must retry the request explicitly. When the client retries the request, the
request is sent to another server instance in the cluster, which retrieves session state
information for this client.
HTTP sessions can also be saved in a persistent store in case a server instance fails. In addition,
if a distributable web application references an SFSB, and the web applications session fails
over, the EJB reference is also failed over. For more information, see Distributed Sessions and
Persistence on page 116.
If an SFSB that uses session persistence is undeployed while the GlassFish Server instance is
stopped, the session data in the persistence store might not be cleared. To prevent this,
undeploy the SFSB while the GlassFish Server instance is running.
Confgure SFSB failover by:
The local fle system- Allows a single server instance to recover the SFSB state after a failure
and restart. This store also provides passivation and activation of the state to help control
the amount of memory used. This option is not supported in a production environment that
requires SFSB state persistence. This is the default storage mechanismif availability is not
enabled.
Other servers - Uses other server instances in the cluster for session persistence. Clustered
server instances replicate session state. Each backup instance stores the replicated data in
memory. This is the default storage mechanismif availability is enabled.
Using Session Beans
Chapter 8 Using Enterprise JavaBeans Technology 159
Choose the persistence store in one of the following ways:
To use the local fle system, frst disable availability. Select the Availability Service
component under the relevant confguration in the Administration Console. Uncheck the
Availability Service box. Then select the EJB Container component and edit the Session
Store Location value. The default is domain-dir/session-store.
To use other servers, select the Availability Service component under the relevant
confguration in the Administration Console. Check the Availability Service box. To enable
availability for the EJB container, select the EJB Container Availability tab, then check the
Availability Service box. All instances in an GlassFish Server cluster should have the same
availability settings to ensure consistent behavior.
For more information about SFSB state persistence, see the Oracle GlassFish Server 3.1-3.1.1
High Availability Administration Guide.
Usingthe --keepstate Option
If you are using the fle systemfor persistence, you can use the --keepstate option of the
asadmin redeploy command to retain the SFSB state between redeployments.
The default for --keepstate is false. This option is supported only on the default server
instance, named server. It is not supported and ignored for any other target.
Some changes to an application between redeployments prevent this feature fromworking
properly. For example, do not change the set of instance variables in the SFSB bean class.
If any active SFSB instance fails to be preserved or restored, none of the SFSB instances will be
available when the redeployment is complete. However, the redeployment continues and a
warning is logged.
To preserve active state data, GlassFish Server serializes the data and saves it in memory. To
restore the data, the class loader of the newly redeployed application deserializes the data that
was previously saved.
For more information about the asadmin redeploy command, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
Usingthe --asyncreplicationOption
If you are using replication on other servers for persistence, you can use the
--asyncreplication option of the asadmin deploy command to specify that SFSB states are
frst bufered and then replicated using a separate asynchronous thread. If
--asyncreplication is set to true (default), performance is improved but availability is
reduced. If the instance where states are bufered but not yet replicated fails, the states are lost. If
set to false, performance is reduced but availability is guaranteed. States are not bufered but
immediately transmitted to other instances in the cluster.
Using Session Beans
Oracle GlassFish Server 3.1 Application Development Guide July 2011 160
For more information about the asadmin deploy command, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
EnablingCheckpointing
The following sections describe howto enable SFSB checkpointing:
create methods defned in the home or business interface of the SFSB, if you want to
checkpoint the initial state of the SFSB immediately after creation
For SFSBs using container managed transactions only, methods in the remote interface of
the bean marked with the transaction attribute TX_NOT_SUPPORTEDor TX_NEVER
For SFSBs using bean managed transactions only, methods in which a bean managed
transaction is neither started nor committed
Any other methods mentioned in this list are ignored. At the end of invocation of each of these
methods, the EJB container saves the state of the SFSB to persistent store.
Note If an SFSB does not participate in any transaction, and if none of its methods are explicitly
specifed in the checkpoint-at-end-of-method element, the beans state is not checkpointed at
all even if availability-enabled="true" for this bean.
For better performance, specify a small subset of methods. The methods chosen should
accomplish a signifcant amount of work in the context of the Java EE application or should
result in some important modifcation to the beans state.
SessionBeanRestrictions andOptimizations
This section discusses restrictions on developing session beans and provides some optimization
guidelines.
If a session bean instance is participating in a transaction, a client cannot invoke the remove
method on the session objects home or business interface object, or an exception is thrown.
EJBSingletons
EJB Singletons are created for each server instance in a cluster, and not once per cluster.
UsingRead-Only Beans
Aread-only bean is an EJB 2.1 entity bean that is never modifed by an EJB client. The data that a
read-only bean represents can be updated externally by other enterprise beans, or by other
means, such as direct database updates.
Note Read-only beans are specifc to the GlassFish Server and are not part of the Enterprise
JavaBeans Specifcation, v2.1. Use of this feature for an EJB 2.1 bean results in a non-portable
application.
To make an EJB 3.0 entity bean read-only, use @Column annotations to mark its columns
insertable=false and updatable=false.
Read-only beans are best suited for situations where the underlying data never changes, or
changes infrequently.
The following topics are addressed here:
Only container-managed transactions are allowed; read-only beans cannot start their own
transactions.
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 beans
refresh-period-in-seconds element in the glassfish-ejb-jar.xml fle.
The home interface can have any number of fnd methods. The return type of the fnd
methods must be the primary key for the same bean type (or a collection of primary keys).
If the data that the bean represents can change, then refresh-period-in-seconds must be
set to refresh the beans at regular intervals. ejbLoad is called at this regular interval.
Aread-only bean comes into existence using the appropriate fnd methods.
Read-only beans are cached and have the same cache properties as entity beans. When a
read-only bean is selected as a victimto make roomin the cache, ejbPassivate is called and the
bean is returned to the free pool. When in the free pool, the bean has no identity and is used
only to serve any fnder requests.
Read-only beans are bound to the naming service like regular read-write entity beans, and
clients can look up read-only beans the same way read-write entity beans are looked up.
Using Read-Only Beans
Oracle GlassFish Server 3.1 Application Development Guide July 2011 164
Read-Only BeanGoodPractices
For best results, followthese guidelines when developing read-only beans:
Use any of the valid EJB 2.1 transaction attributes for the trans-attribute element.
The reason for having TX_SUPPORTED is to allowreading uncommitted data in the same
transaction. Also, the transaction attributes can be used to force ejbLoad.
RefreshingRead-Only Beans
There are several ways of refreshing read-only beans, as addressed in the following sections:
If the value is greater than zero, the bean is refreshed at the rate specifed.
Note This is the only way to refresh the bean state if the data can be modifed external to the
GlassFish Server.
By default, a single timer is used for all instances of a read-only bean. When that timer fres, all
bean instances are marked as expired and are refreshed fromthe database the next time they are
used.
Use the -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true fag to refresh
each bean instance independently upon access if its refresh period has expired. The default is
false. Note that each instance still has the same refresh period. This additional level of
granularity can improve the performance of read-only beans that do not need to be refreshed at
the same time.
To set this fag, use the asadmin create-jvm-options command. For example:
Using Read-Only Beans
Chapter 8 Using Enterprise JavaBeans Technology 165
asadmin create-jvm-options -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true
RefreshingProgrammatically
Typically, beans that update any data that is cached by read-only beans need to notify the
read-only beans to refresh their state. Use ReadOnlyBeanNotifer to force the refresh of
read-only beans.
To do this, invoke the following methods on the ReadOnlyBeanNotifer bean:
public interface ReadOnlyBeanNotifier extends java.rmi.Remote {
refresh(Object PrimaryKey) throws RemoteException;
}
The implementation of the ReadOnlyBeanNotifer interface is provided by the container. The
bean looks up ReadOnlyBeanNotifer using a fragment of code such as the following 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 notifer, the lookup has this modifcation:
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.java.net/nonav/
docs/v3/api/ and click on the com.sun.appserv.ejb package.
DeployingRead-Only Beans
Read-only beans are deployed in the same manner as other entity beans. However, in the entry
for the bean in the glassfish-ejb-jar.xml fle, 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 glassfish-ejb-jar.xml fle can be set
to some value that specifes the rate at which the bean is refreshed. If this element is missing, no
refresh occurs.
All requests in the same transaction context are routed to the same read-only bean instance. Set
the allow-concurrent-access element to either true (to allowconcurrent accesses) or false
(to serialize concurrent access to the same read-only bean). The default is false.
Using Read-Only Beans
Oracle GlassFish Server 3.1 Application Development Guide July 2011 166
For further information on these elements, refer to The glassfsh-ejb-jar.xml File in Oracle
GlassFish Server 3.1 Application Deployment Guide.
UsingMessage-DrivenBeans
This section describes message-driven beans and explains the requirements for creating themin
the GlassFish Server environment.
The following topics are addressed here:
steady-pool-size
resize-quantity
max-pool-size
pool-idle-timeout-in-seconds
For more information about glassfish-ejb-jar.xml, see The glassfsh-ejb-jar.xml File in
Oracle GlassFish Server 3.1 Application Deployment Guide.
Domain-Level Settings
You can control the following domain-level message-driven bean settings in the EJB container:
Initial and MinimumPool Size
Specifes the initial and minimumnumber of beans maintained in the pool. The default is 0.
MaximumPool Size
Specifes the maximumnumber of beans that can be created to satisfy client requests. The
default is 32.
Pool Resize Quantity
Specifes the number of beans to be created if a request arrives when the pool is empty
(subject to the Initial and MinimumPool Size), or the number of beans to remove if idle for
more than the Idle Timeout. The default is 8.
Idle Timeout
Specifes the maximumtime in seconds that a bean can remain idle in the pool. After this
amount of time, the bean is destroyed. The default is 600 (10 minutes). Avalue of 0 means a
bean can remain idle indefnitely.
For information on monitoring message-driven beans, click the Help button in the
Administration Console. Select the Stand-Alone Instances component, select the instance from
the table, and select the Monitor tab. Or select the Clusters component, select the cluster from
the table, select the Instances tab, select the instance fromthe table, and select the Monitor tab.
Note Running monitoring when it is not needed might impact performance, so you might
choose to turn monitoring of when it is not in use. For details, see Chapter 8, Administering
the Monitoring Service, in Oracle GlassFish Server 3.1 Administration Guide.
Message-DrivenBeanRestrictions andOptimizations
This section discusses the following restrictions and performance optimizations that pertain to
developing message-driven beans:
If the bean method encounters a runtime exception or error, it should simply propagate the
error fromthe bean method to the container.
If the bean method performs an operation that results in a checked exception that the bean
method cannot recover, the bean method should throwthe javax.ejb.EJBException that
wraps the original exception.
Full support for the J2EE v1.4 specifcations CMP model. Extensive information on CMP is
contained in chapters 10, 11, and 14 of the Enterprise JavaBeans Specifcation, v2.1. This
includes the following:
Support for commit options B and Cfor transactions. See Commit Options on
page 269.
9
C H A P T E R 9
171
The primary key class must be a subclass of java.lang.Object. This ensures portability,
and is noted because some vendors allowprimitive types (such as int) to be used as the
primary key class.
An Object/Relational (O/R) mapping tool that creates XML deployment descriptors for
EJB JARfles that contain beans that use CMP.
CMP runtime support. See Confguring the CMP Resource on page 184.
Relationship prefetching
Read-Only Beans
For details, see Performance-Related Features on page 184.
CMPMapping
Implementation for entity beans that use CMP is mostly a matter of mapping CMP felds and
CMRfelds (relationships) to the database.
The following topics are addressed here:
ejb-jar.xml The J2EE standard fle for assembling enterprise beans. For a detailed
description, see the Enterprise JavaBeans Specifcation, v2.1.
The name of a .dbschema fle must be unique across all deployed modules in a domain.
If more than one schema is accessible for the schema user, more than one table with the
same name might be captured if the -schemaname option of capture-schema is not set.
Table names in databases are case-sensitive. Make sure that the table name matches the
name in the database.
PostgreSQL databases internally convert all names to lower case. Before running the
capture-schema command on a PostgreSQL database, make sure table and column names
are lower case in the sun-cmp-mappings.xml fle.
An Oracle database user running the capture-schema command needs ANALYZE ANY
TABLE privileges if that user does not own the schema. These privileges are granted to the
user by the database administrator.
Schema Capture
Chapter 9 Using Container-Managed Persistence 183
Confguringthe CMPResource
An EJB module that contains CMP beans requires the JNDI name of a JDBCresource in the
jndi-name subelement of the cmp-resource element in the glassfish-ejb-jar.xml fle. Set
PersistenceManagerFactory properties as properties of the cmp-resource element in the
glassfish-ejb-jar.xml fle. See cmp-resource in Oracle GlassFish Server 3.1 Application
Deployment Guide.
In the Administration Console, open the Resources component, then select JDBC. Click the
Help button in the Administration Console for information on creating a newJDBCresource.
For a list of the JDBCdrivers currently supported by the GlassFish Server, see the Oracle
GlassFish Server 3.1-3.1.1 Release Notes. For confgurations of supported and other drivers, see
Confguration Specifcs for JDBCDrivers in Oracle GlassFish Server 3.1 Administration
Guide.
For example, if the JDBCresource has the JNDI name jdbc/MyDatabase, set the CMP resource
in the glassfish-ejb-jar.xml fle as follows:
<cmp-resource>
<jndi-name>jdbc/MyDatabase</jndi-name>
</cmp-resource>
Performance-RelatedFeatures
The GlassFish Server provides the following features to enhance performance or allowmore
fne-grained data checking. These features are supported only for entity beans with container
managed persistence.
The following topics are addressed here:
ToUseVersionConsistency
Create the versioncolumninthe primary table.
Give the versioncolumna numeric data type.
Provide appropriate update triggers onthe versioncolumn.
These triggers must increment the version column on each update of the specifed row.
Specify the versioncolumn.
This is specifed in the check-version-of-accessed-instances subelement of the
consistency element in the sun-cmp-mappings.xml fle. See consistency in Oracle GlassFish
Server 3.1 Application Deployment Guide.
Mapthe CMPbeantoanexistingschema.
Automatic schema generation is not supported for beans with version column consistency
checking. Instead, work with your database administrator to create the schema and add the
required triggers.
RelationshipPrefetching
In many cases when an entity beans state is fetched fromthe database, its relationship felds are
always accessed in the same transaction. Relationship prefetching saves database round trips by
fetching data for an entity bean and those beans referenced by its CMRfelds in a single
database round trip.
To enable relationship prefetching for a CMRfeld, use the default subelement of the
fetched-with element in the sun-cmp-mappings.xml fle. By default, these CMRfelds are
prefetched whenever findByPrimaryKey or a customfnder is executed for the entity, or when
the entity is navigated to froma relationship. (Recursive prefetching is not supported, because it
does not usually enhance performance.) See fetched-with in Oracle GlassFish Server 3.1
Application Deployment Guide.
To disable prefetching for specifc customfnders, use the prefetch-disabled element in the
glassfish-ejb-jar.xml fle. See prefetch-disabled in Oracle GlassFish Server 3.1 Application
Deployment Guide.
Multilevel relationship prefetching is supported for CMP 2.1 entity beans. To enable multilevel
relationship prefetching, set the following property using the asadmin create-jvm-options
command:
asadmin create-jvm-options -Dcom.sun.jdo.spi.persistence.support.sqlstore.MULTILEVEL_PREFETCH=true
1
2
3
4
5
Performance-Related Features
Chapter 9 Using Container-Managed Persistence 185
Read-Only Beans
Another feature that the GlassFish Server provides is the read-only bean, an entity bean that is
never modifed by an EJB client. Read-only beans avoid database updates completely.
Note Read-only beans are specifc to the GlassFish Server and are not part of the Enterprise
JavaBeans Specifcation, v2.1. Use of this feature for an EJB 2.1 bean results in a non-portable
application.
Aread-only bean can be used to cache a database entry that is frequently accessed but rarely
updated (externally by other beans). When the data that is cached by a read-only bean is
updated by another bean, the read-only bean can be notifed to refresh its cached data.
The GlassFish Server provides a number of ways by which a read-only beans state can be
refreshed. By setting the refresh-period-in-seconds element in the glassfish-ejb-jar.xml
fle and the trans-attribute element (or @TransactionAttribute annotation) in the
ejb-jar.xml fle, it is easy to confgure a read-only bean that is one of the following:
Always refreshed
Periodically refreshed
Never refreshed
Programmatically refreshed
Access to CMRfelds of read-only beans is not supported. Deployment will succeed, but an
exception will be thrown at runtime if a get or set method is invoked.
Read-only beans are best suited for situations where the underlying data never changes, or
changes infrequently. For further information and usage guidelines, see Using Read-Only
Beans on page 163.
Default FetchGroupFlags
Using the following fags can improve performance.
Setting -DAllowManagedFieldsInDefaultFetchGroup=true allows CMP felds that by default
cannot be placed into the default fetch group to be loaded along with all other felds that are
fetched when the CMP state is loaded into memory. These could be multiple felds mapped to
the same column in the database table, for example, an instance feld and a CMR. By default this
fag is set to false.
For additional information, see level in Oracle GlassFish Server 3.1 Application Deployment
Guide.
Default Fetch Group Flags
Oracle GlassFish Server 3.1 Application Development Guide July 2011 186
Setting -DAllowMediatedWriteInDefaultFetchGroup specifes howupdated CMP felds are
written back to the database. If the fag is false, all felds in the CMP bean are written back to
the database if at least one feld in the default fetch group has been changed in a transaction. If
the fag is true, only felds modifed by the bean are written back to the database. Specifying
true can improve performance, particularly on database tables with many columns that have
not been updated. By default this fag is set to false.
To set one of these fags, use the asadmin create-jvm-options command. For example:
asadmin create-jvm-options -DAllowManagedFieldsInDefaultFetchGroup=true
ConfguringQueries for 1.1Finders
The following topics are addressed here:
Filter expression - AJava-like expression that specifes a condition that each object
returned by the query must satisfy. Corresponds to the WHERE clause in EJB QL.
Query parameter declaration - Specifes the name and the type of one or more query input
parameters. Follows the syntax for formal parameters in the Java language.
Query variable declaration - Specifes the name and type of one or more query variables.
Follows the syntax for local variables in the Java language. Aquery flter might use query
variables to implement joins.
Query ordering declaration - Specifes the ordering expression of the query. Corresponds
to the ORDERBYclause of EJB QL.
The GlassFish Server specifc deployment descriptor (glassfish-ejb-jar.xml) provides the
following elements to store the EJB 1.1 fnder method settings:
query-filter
query-params
query-variables
query-ordering
Confguring Queries for 1.1 Finders
Chapter 9 Using Container-Managed Persistence 187
The bean developer uses these elements to construct a query. When the fnder method that uses
these elements executes, the values of these elements are used to execute a query in the database.
The objects fromthe JDOQL query result set are converted into primary key instances to be
returned by the EJB 1.1 ejbFind method.
The JDOspecifcation, JSR12 (http://jcp.org/en/jsr/detail?id=12), provides a
comprehensive description of JDOQL. The following information summarizes the elements
used to defne EJB 1.1 fnders.
Query Filter Expression
The flter expression is a String containing a Boolean expression evaluated for each instance of
the candidate class. If the flter is not specifed, it defaults to true. Rules for constructing valid
expressions followthe Java language, with the following diferences:
Equality and ordering comparisons between primitives and instances of wrapper classes are
valid.
Equality and ordering comparisons of Date felds and Date parameters are valid.
Equality and ordering comparisons of String felds and String parameters are valid.
White space (non-printing characters space, tab, carriage return, and line feed) is a
separator and is otherwise ignored.
Methods, including object construction, are not supported, except for these methods.
Collection.contains(Object o)
Collection.isEmpty()
String.startsWith(String s)
String.endsWith(String e)
In addition, the GlassFish Server supports the following nonstandard JDOQL methods.
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)
Cast operator
Do not expose the get and set methods for CMRfelds or the persistence collection classes
that are used in container-managed relationships through the remote interface of the bean.
However, you are free to expose the get and set methods that correspond to the CMP felds
of the entity bean through the beans remote interface.
Do not expose the container-managed collection classes that are used for relationships
through the remote interface of the bean.
Do not expose local interface types or local home interface types through the remote
interface or remote home interface of the bean.
Dependent value classes can be exposed in the remote interface or remote home interface, and
can be included in the client EJB JARfle.
PostgreSQL Case Insensitivity
Case-sensitive behavior cannot be achieved for PostgreSQL databases. PostgreSQL databases
internally convert all names to lower case, which makes the following workarounds necessary:
In the CMP 2.1 runtime, PostgreSQL table and column names are not quoted, which makes
these names case insensitive.
Before running the capture-schema command on a PostgreSQL database, make sure table
and column names are lower case in the sun-cmp-mappings.xml fle.
NoSupport for lock-when-loaded onSybase
For EJB 2.1 beans, the lock-when-loaded consistency level is implemented by placing update
locks on the data corresponding to a bean when the data is loaded fromthe database. There is
no suitable mechanismavailable on Sybase databases to implement this feature. Therefore, the
lock-when-loaded consistency level is not supported on Sybase databases. See consistency in
Oracle GlassFish Server 3.1 Application Deployment Guide.
CMP Restrictions and Optimizations
Oracle GlassFish Server 3.1 Application Development Guide July 2011 192
Sybase Finder Limitation
If a fnder method with an input greater than 255 characters is executed and the primary key
column is mapped to a VARCHARcolumn, Sybase attempts to convert type VARCHARto type
TEXTand generates the following 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 fnder method input is less than 255 characters.
Date andTime Fields
If a feld type is a Java date or time type (java.util.Date, java.sql.Date, java.sql.Time,
java.sql.Timestamp), make sure that the feld value exactly matches the value in the database.
For example, the following code uses a java.sql.Date type as a primary key feld:
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 of the feld value
being stored in the database. Later if the client tries to fnd this bean by primary key as follows,
the bean is not found in the database because the value does not match the one that is stored in
the database.
myBean = BeanA.findByPrimaryKey(myDate);
Similar problems can happen if the database truncates the timestamp value while storing it, or if
a customquery has a date or time value comparison in its WHERE clause.
For automatic mapping to an Oracle database, felds of type java.util.Date, java.sql.Date,
and java.sql.Time are mapped to Oracles DATE data type. Fields of type
java.sql.Timestamp are mapped to Oracles TIMESTAMP(9) data type.
Set RECURSIVE_TRIGGERS tofalse onMSSQL
For version consistency triggers on MSSQL, the property RECURSIVE_TRIGGERS must be set to
false, which is the default. If set to true, triggers throwa java.sql.SQLException.
Set this property as follows:
EXEC sp_dboption database-name, recursive triggers, FALSE
go
CMP Restrictions and Optimizations
Chapter 9 Using Container-Managed Persistence 193
You can test this property as follows:
SELECT DATABASEPROPERTYEX(database-name, IsRecursiveTriggersEnabled)
go
MySQL Database Restrictions
The following restrictions apply when you use a MySQL database with the GlassFish Server for
persistence.
MySQL treats int1 and int2 as reserved words. If you want to defne int1 and int2 as felds
in your table, use int1 and int2 feld names in your SQL fle.
When VARCHAR felds get truncated, a warning is displayed instead of an error. To get an
error message, start the MySQL database in strict SQL mode.
The order of felds in a foreign key index must match the order in the explicitly created
index on the primary table.
The CREATE TABLE syntax in the SQL fle must end with the following line.
) Engine=InnoDB;
InnoDB provides MySQL with a transaction-safe (ACIDcompliant) storage engine having
commit, rollback, and crash recovery capabilities.
For a FLOAT type feld, the correct precision must be defned. By default, MySQL uses four
bytes to store a FLOAT type that does not have an explicit precision defnition. For example,
this causes a number such as 12345.67890123 to be rounded of to 12345.7 during an
INSERT. To prevent this, specify FLOAT(10,2) in the DDL fle, which forces the database to
use an eight-byte double-precision column. For more information, 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 information, see
http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html and
http://dev.mysql.com/doc/mysql/en/ansi-mode.html.
MySQL always starts a newconnection when autoCommit==true is set. This ensures that
each SQL statement forms a single transaction on its own. If you try to rollback or commit
an SQL statement, you get an error message.
javax.transaction.SystemException: java.sql.SQLException:
Cant 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 JDBCURL. For more information,
see http://forums.mysql.com/read.php?39,31326,31404.
MySQL does not allowa DELETE on a rowthat contains a reference to itself. 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 fails with the following 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 following:
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 if the foreign key feld is allowed to be null. For more information, see
http://dev.mysql.com/doc/mysql/en/innodb-foreign-key-constraints.html.
CMP Restrictions and Optimizations
Chapter 9 Using Container-Managed Persistence 195
When an SQL script has foreign key constraints defned, capture-schema fails to capture
the table information correctly. To work around the problem, remove the constraints and
then 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 following:
CREATE TABLE ADDRESSBOOKBEANTABLE (ADDRESSBOOKNAME VARCHAR(255)
NOT NULL PRIMARY KEY,
CONNECTEDUSERS BLOB NULL,
OWNER VARCHAR(256),
FK_FOR_ACCESSPRIVILEGES VARCHAR(256)
) ENGINE=InnoDB;
CMP Restrictions and Optimizations
Oracle GlassFish Server 3.1 Application Development Guide July 2011 196
Developing Java Clients
This chapter describes howto develop, assemble, and deploy Java clients.
The following topics are addressed here:
The MANIFEST.MF fle. This fle contains a reference to the main class, which states the
complete package prefx and class name of the Java client.
Prepare the client machine.
This step is not needed for Java Web Start. This step is not needed if the client and server
machines are the same.
If you are using the appclient script, package the GlassFish Server systemfles required to
launch application clients on remote systems using the package-appclient script, then retrieve
the application client itself using the asadmin get-client-stubs command.
For more information, see Using the package-appclient Script on page 214 and the Oracle
GlassFish Server 3.1-3.1.1 Reference Manual.
Toaccess EJBcomponents that are residingina remote system, make the followingchanges to
the sun-acc.xml fle or the appclient script. This stepis not neededfor JavaWebStart.
2
3
4
5
6
Developing Clients Using the ACC
Oracle GlassFish Server 3.1 Application Development Guide July 2011 200
Defne the target-server elements address and port attributes to reference the remote
server machine and its ORB port. See target-server in Oracle GlassFish Server 3.1
Application Deployment Guide.
Use the -targetserver option of the appclient script to reference the remote server
machine and its ORB port. For more information, see Running an Application Client
Using the appclient Script on page 213.
To determine the ORB port on the remote server, use the asadmin get command. For example:
asadmin --host rmtsrv get server-config.iiop-service.iiop-listener.iiop-listener1.port
For more information about the asadmin get command, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
Toset uploadbalancingandfailover of remote EJBreferences, defne at least two
target-server elements inthe sun-acc.xml fle or the appclient script. This stepis not
neededfor JavaWebStart.
If the GlassFish Server instance on which the application client is deployed participates in a
cluster, the ACCfnds all currently active IIOP endpoints in the cluster automatically. However,
a client should have at least two endpoints specifed for bootstrapping purposes, in case one of
the endpoints has failed.
The target-server elements in the sun-acc.xml fle specify one or more IIOP endpoints used
for load balancing. The address attribute is an IPv4 address or host name, and the port
attribute specifes the port number. See client-container in Oracle GlassFish Server 3.1
Application Deployment Guide.
The --targetserver option of the appclient script specifes one or more IIOP endpoints used
for load balancing. For more information, see Running an Application Client Using the
appclient Script on page 213.
For instructions on running the application client, see Using Java Web Start on page 202 or
Running an Application Client Using the appclient Script on page 213.
For more information about RMI-IIOP load balancing and failover, see Chapter 12,
RMI-IIOP Load Balancing and Failover, in Oracle GlassFish Server 3.1-3.1.1 High
Availability Administration Guide.
The MANIFEST.MF fle. This fle contains a reference to the main class, which states the
complete package prefx and class name of the Java client.
Prepare the client machine.
This step is not needed for Java Web Start. This step is not needed if the client and server
machines are the same.
If you are using the appclient script, package the GlassFish Server systemfles required to
launch application clients on remote systems using the package-appclient script, then retrieve
the application client itself using the asadmin get-client-stubs command.
For more information, see Using the package-appclient Script on page 214 and the Oracle
GlassFish Server 3.1-3.1.1 Reference Manual.
Runthe applicationclient.
See Using Java Web Start on page 202 or Running an Application Client Using the appclient
Script on page 213.
UsingJavaWebStart
Java Web Start allows your application client to be easily launched and automatically
downloaded and updated. General information about Java Web Start is available at
http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136112.html.
2
3
4
5
6
Developing Clients Using the ACC
Oracle GlassFish Server 3.1 Application Development Guide July 2011 202
The following topics are addressed here:
Using a web browser, directly enter the URL for the application client. See The Application
Client URL on page 204.
Use the Java Web Start command javaws, specifying the URL of the application client as a
command line argument.
If the application has previously been downloaded using Java Web Start, you have
additional alternatives.
Use the desktop icon that Java Web Start created for the application client. When Java
Web Start downloads an application client for the frst time it asks you if such an icon
should be created.
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 if a newer
client version is available. This means you can redeploy an application client without having to
worry about whether client machines have the latest version.
The ApplicationClient URL
The default URL for an application or module generally is as follows:
http://host:port/context-root
The default URL for a stand-alone application client module is as follows:
http://host:port/appclient-module-id
The default URL for an application client module embedded within an application is as follows.
Note that the relative path to the application client JARfle is included.
http://host:port/application-id/appclient-path
If the context-root, appclient-module-id, or application-id is not specifed during deployment,
the name of the JARor EARfle without the extension is used. If the application client module
or application is not in JARor EARfle format, an appclient-module-id or application-id is
generated.
Regardless of howthe context-root or id is determined, it is written to the server log when you
deploy the application. For details about naming, see Naming Standards in Oracle GlassFish
Server 3.1 Application Deployment Guide.
To set a diferent URL for an application client, use the context-root subelement of the
java-web-start-access element in the glassfish-application-client.xml fle. This
overrides the appclient-module-id or application-id. See Oracle GlassFish Server 3.1 Application
Deployment Guide.
You can also pass arguments to the ACCor to the application client's main method as query
parameters in the URL. If multiple application client arguments are specifed, they are passed in
the order specifed.
Developing Clients Using the ACC
Oracle GlassFish Server 3.1 Application Development Guide July 2011 204
Aquestion mark separates the context root fromthe arguments. Ampersands (&) separate the
arguments and their values. Each argument and each value must begin with arg=. Here is an
example URL with a -color argument for 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
Note If you are using the javaws URL command to launch Java Web Start with a URL that
contains arguments, enclose the URL in double quotes (") to avoid breaking the URL at the
ampersand (&) symbol.
Ideally, you should build your production application clients with user-friendly interfaces that
collect information which might otherwise be gathered as command-line arguments. This
minimizes the degree to which users must customize the URLs that launch application clients
using Java Web Start. Command-line argument support is useful in a development
environment and for existing application clients that depend on it.
SigningJARFiles UsedinJavaWebStart
Java Web Start enforces a security sandbox. By default it grants any application, including
application clients, only minimal privileges. Because Java Web Start applications can be so
easily downloaded, Java Web Start provides protection frompotentially harmful programs that
might be accessible over the network. If an application requires a higher privilege level than the
sandbox permits, the code that needs privileges must be in a JARfle that was signed.
When Java Web Start downloads such a signed JARfle, it displays information about the
certifcate that was used to sign the JARif that certifcate is not trusted. It then asks you whether
you want to trust that signed code. If you agree, the code receives elevated permissions and
runs. If you reject the signed code, Java Web Start does not start the downloaded application.
Your frst Java Web Start launch of an application client is likely to involve this prompting
because by default GlassFish Server uses a self-signed certifcate that is not linked to a trusted
authority.
The GlassFish Server serves two types of signed JARfles in response to Java Web Start requests.
One type is a JARfle installed as part of the GlassFish Server, which starts an application client
during a Java Web Start launch: as-install/lib/gf-client.jar.
The other type is a generated application client JARfle. As part of deployment, the GlassFish
Server generates a newapplication client JARfle that contains classes, resources, and
descriptors needed to run the application client on end-user systems. When you deploy an
application with the asadmin deploy command's --retrieve option, use the asadmin
get-client-stubs command, or select the Generate RMIStubs option fromthe EJB Modules
deployment page in the Administration Console, this is one of the JARfles retrieved to your
system. Because application clients need access beyond the minimal sandbox permissions to
Developing Clients Using the ACC
Chapter 10 Developing Java Clients 205
work in the Java Web Start environment, the generated application client JARfle must be
signed before it can be downloaded to and executed on an end-user system.
AJARfle can be signed automatically or manually.
The following topics are addressed here:
Owned GlassFish Server owns the content and ignores any customcontent
Override the GlassFish Server defaults for the child elements of <information> elements
that have no attribute settings for os, arch, platform, and locale. Among these child
elements are <title>, <vendor>, <description>, <icon>, and so on.
Add <information> elements with os, arch, platform, or locale settings. You can also add
child elements.
Add child elements of <resources> elements that have no attribute settings for os, arch, or
locale. Among these child elements are <jar>, <property>, <nativelib>, and so on. You
can also customize attributes of the <java> child element.
Add <resources> elements that specify at least one of os, arch, or locale. You can also add
child elements.
This fexibility allows you to add JARfles to the application (including platform-specifc native
libraries) and set properties to control the behavior of your application clients.
The following tables provide more detail about what parts of the JNLP fle you can add to and
modify.
Developing Clients Using the ACC
Oracle GlassFish Server 3.1 Application Development Guide July 2011 210
TABLE 101 OwnedJNLPFile Content
JNLPFile Fragment Description
<jnlp codebase="xxx" ...> GlassFish Server controls this content for application clients
packaged in EARfles. The developer controls this content for
application clients packaged in WARfles.
<jnlp href="xxx" ...> GlassFish Server controls this content for application clients
packaged in EARfles. The developer controls this content for
application clients packaged in WARfles.
<jnlp>
<security>
GlassFish Server must control the permissions requested for
each JNLP fle. All permissions are needed for the main fle,
which launches the ACC. The permissions requested for other
JNLP documents depend on whether the JARfles referenced in
those documents are signed.
<jnlp>
<application-desc>
<argument> ...
GlassFish Server sets the main-class and the arguments to be
passed to the client.
TABLE 102 DefaultedJNLPFile Content
JNLPFile Fragment Description
<jnlp spec="xxx" ...> Specifes the JNLP specifcation version.
<jnlp>
<information [no-attributes]>
Specifes the application title, vendor, home page, various
description text values, icon images, and whether ofine
execution is allowed.
<jnlp>
<resources [no-attributes]>
<java version="xxx"
java-vm-args="yyy" ...>
Specifes the Java SE version or selected VMparameter settings.
TABLE 103 MergedJNLPFile Content
JNLPFile Fragment Description
<jnlp>
<information [attributes]>
You can specify one or more of the os, arch, platform, and
locale attributes for the <information> element. You can also
specify child elements; GlassFish Server provides no default
children.
<jnlp>
<resources [attributes]>
You can specify one or more of the os, arch, platform, and
locale attributes for the <resources> element. You can also
specify child elements; GlassFish Server provides no default
children.
Developing Clients Using the ACC
Chapter 10 Developing Java Clients 211
TABLE 103 Merged JNLPFile Content (Continued)
JNLPFile Fragment Description
<jnlp>
<resources [no-attributes]>
<jar ...>
Adds JARfles to be included in the application to the JARfles
provided by GlassFish Server.
<jnlp>
<resources [no-attributes]>
<nativelib ...>
Adds native libraries to be included in the application. Each
entry in a JARlisted in a <nativelib> element must be a native
library for the correct platform. The full syntax of the
<nativelib> element lets the developer specify the platformfor
that native library.
<jnlp>
<resources [no-attributes]>
<property ...>
Adds systemproperties to be included in the application to the
systemproperties defned by GlassFish Server.
<jnlp>
<resources [no-attributes]>
<extension ...>
Specifes another customJNLP fle.
<jnlp>
<component-desc ...>
Includes another customJNLP fle that specifes a component
extension.
<jnlp>
<installer-desc ...>
Includes another customJNLP fle that specifes an installer
extension.
Usingthe Embeddable ACC
You can embed the ACCinto your application client. If you place the
as-install/lib/gf-client.jar fle in your runtime classpath, your application creates the ACC
after your application code has started, then requests that the ACCstart the application client
portion. The basic model for coding is as follows:
1. Create a builder object.
2. Operate on the builder to confgure the ACC.
3. Obtain a newACCinstance fromthe builder.
4. Present a client archive or class to the ACCinstance.
5. Start the client running within the newly created ACCinstance.
Your code should followthis general pattern:
// one TargetServer for each ORB endpoint for bootstrapping
TargetServer[] servers = ...;
// Get a builder to set up the ACC
AppClientContainer.Builder builder = AppClientContainer.newBuilder(servers);
// Fine-tune the ACCs configuration. Note ability to "chain" invocations.
builder.callbackHandler("com.acme.MyHandler").authRealm("myRealm"); // Modify config
Developing Clients Using the ACC
Oracle GlassFish Server 3.1 Application Development Guide July 2011 212
// Get a container for a client.
URI clientURI = ...; // URI to the client JAR
AppClientContainer acc = builder.newContainer(clientURI);
or
Class mainClass = ...;
AppClientContainer acc = builder.newContainer(mainClass);
// In either case, start the client running.
String[] appArgs = ...;
acc.startClient(appArgs); // Start the client
...
acc.close(); // close the ACC(optional)
The ACCloads the application client's main class, performs any required injection, and
transfers control to the static main method. The ACC's run method returns to the calling
application as soon as the client's main method returns to the ACC.
If the application client's main method starts any asynchronous activity, that work continues
after the ACCreturns. The ACChas no knowledge of whether the client's main method triggers
asynchronous work. Therefore, if the client causes work on threads other than the calling
thread, and if the embedding application needs to knowwhen the client's asynchronous work
completes, the embedding application and the client must agree on howthis happens.
The ACC's shutdown handling is invoked fromthe ACC's close method. The calling
application can invoke acc.close() to close down any services started by the ACC. If the
application client code started any asynchronous activity that might still depend on ACC
services, invoking close before that asynchronous activity completes could cause unpredictable
and undesirable results. The shutdown handling is also run automatically at VMshutdown if
the code has not invoked close before then.
The ACCdoes not prevent the calling application fromcreating or running more than one ACC
instance during a single execution of the application either serially or concurrently. However,
other services used by the ACC(transaction manager, security, ORB, and so on) might or might
not support such serial or concurrent reuse.
RunninganApplicationClient Usingthe appclient
Script
To run an application client, you can launch the ACCusing the appclient script, whether or
not Java Web Start is enabled. This is optional. This script is located in the as-install/bin
directory. For details, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
Developing Clients Using the ACC
Chapter 10 Developing Java Clients 213
Usingthe package-appclient Script
You can package the GlassFish Server systemfles required to launch application clients on
remote systems into a single JARfle using the package-appclient script. This is optional. This
script is located in the as-install/bin directory. For details, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
The client.policy File
The client.policy fle is the J2SE policy fle used by the application client. Each application
client has a client.policy fle. The default policy fle limits the permissions of Java EE
deployed application clients to the minimal set of permissions required for these applications to
operate correctly. If an application client requires more than this default set of permissions, edit
the client.policy fle to add the custompermissions that your application client needs. Use
the J2SE standard policy tool or any text editor to edit this fle.
For more information on using the J2SE policy tool, see http://download.oracle.com/
javase/tutorial/security/tour2/index.html.
For more information about the permissions you can set in the client.policy fle, see
http://download.oracle.com/
javase/6/docs/technotes/guides/security/permissions.html.
UsingRMI/IIOPOver SSL
You can confgure RMI/IIOP over SSL in two ways: using a username and password, or using a
client certifcate.
To use a username and password, confgure the ior-security-config element in the
glassfish-ejb-jar.xml fle. The following confguration establishes SSL between an
application client and an EJB component using a username and password. The user has to login
to the ACCusing either the sun-acc.xml mechanismor the Programmatic Login on page 72
mechanism.
<ior-security-config>
<transport-config>
<integrity>required</integrity>
<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>
Developing Clients Using the ACC
Oracle GlassFish Server 3.1 Application Development Guide July 2011 214
</as-context>
<sas-context>
<caller-propagation>none</caller-propagation>
</sas-context>
</ior-security-config>
For more information about the glassfish-ejb-jar.xml and sun-acc.xml fles, see the Oracle
GlassFish Server 3.1 Application Deployment Guide.
To use a client certifcate, confgure the ior-security-config element in the
glassfish-ejb-jar.xml fle. The following confguration establishes SSL between an
application client and an EJB component using a client certifcate.
<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>
<realm>default</realm>
<required>false</required>
</as-context>
<sas-context>
<caller-propagation>none</caller-propagation>
</sas-context>
</ior-security-config>
To use a client certifcate, you must also specify the systemproperties for the keystore and
truststore to be used in establishing SSL. To use SSL with the Application Client Container
(ACC), you need to set these systemproperties in one of the following ways:
Use the newsyntax of the appclient script and specify the systemproperties as JVM
options. See Running an Application Client Using the appclient Script on page 213.
Set the environment variable VMARGS in the shell. For example, in the ksh or bash shell, the
command to set this environment variable would be as follows:
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}"
Optionally, you can set the env element using Ant. 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>
Developing Clients Using the ACC
Chapter 10 Developing Java Clients 215
Connectingtoa Remote EJBModuleThrougha
Firewall
To deploy and run an application client that connects to an EJB module on a GlassFish Server
instance that is behind a frewall, you must set ORB Virtual Address Agent Implementation
(ORBVAA) options. Use the asadmin create-jvm-options command as follows:
asadmin create-jvm-options -Dcom.sun.corba.ee.ORBVAAHost=public-IP-adress
asadmin create-jvm-options -Dcom.sun.corba.ee.ORBVAAPort=public-port
asadmin create-jvm-options
-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 of the public address. The
ORBUserConfigurators option tells the ORB to create an instance of the
VirtualAddressAgentImpl class and invoke the configure method on the resulting object,
which must implement the com.sun.corba.ee.spi.orb.ORBConfgurator interface. The
ORBUserConfigurators value doesn't matter. Together, these options create an ORB that in
turn creates Object references (the underlying implementation of remote EJB references)
containing the public address, while the ORB listens on the private address specifed for the
IIOP port in the GlassFish Server confguration.
Specifyinga SplashScreen
Java SE 6 ofers splash screen support, either through a Java command-line option or a manifest
entry in the application's JARfle. To take advantage of this Java SE feature in your application
client, you can do one of the following:
Create the appclient JARfle so that its manifest contains a SplashScreen-Image entry that
specifes the path to the image in the client. The java command displays the splash screen
before starting the ACCor your client, just as with any Java application.
Use the new appclient ... -jar launch format, using the -splash command-line option
at runtime or the SplashScreen-Image manifest entry at development time. See Running
an Application Client Using the appclient Script on page 213.
In the environment that runs the appclient script, set the VMOPTS environment variable to
include the -splash option before invoking the appclient script to launch the client.
Build an application client that uses the embeddable ACCfeature and specify the splash
screen image using one of the following:
SplashScreen-Image in the manifest for your program(not the manifest for the
application client)
See Using the Embeddable ACC on page 212.
Developing Clients Using the ACC
Oracle GlassFish Server 3.1 Application Development Guide July 2011 216
During application (EARfle) deployment, the GlassFish Server generates faade JARfles, one
for the application and one for each application client in the application. During application
client module deployment, the GlassFish Server generates a single facade JARfor the
application client. The appclient script supports splash screens inside the application client
JARonly if you launch an application client facade or appclient client JAR. If you launch the
facade for an application or the undeployed application itself, the appclient script cannot take
advantage of the Java SE 6 splash screen feature.
SettingLoginRetries
You can set a JVMoption using the appclient script that determines the number of login
retries allowed. This option is -Dorg.glassfish.appclient.acc.maxLoginRetries=n where
n is a positive integer. The default number of retries is 3.
This retry loop happens when the ACCattempts to performinjection if you annotated the
client's main class (for example, using @Resource). If instead of annotations your client uses the
InitialContext explicitly to look up remote resources, the retry loop does not apply. In this
case, you could write logic to catch an exception around the lookup and retry explicitly.
For details about the appclient script syntax, see the Oracle GlassFish Server 3.1-3.1.1 Reference
Manual.
UsingLibraries withApplicationClients
The Libraries feld in the Administration Console's deployment page and the --libraries
option of the asadmin deploy command do not apply to application clients. Neither do the
as-install/lib, domain-dir/lib, and domain-dir/lib/classes directories comprising the
Common Class Loader. These apply only to applications and modules deployed to the server.
For more information, see Chapter 2, Class Loaders.
To use libraries with an application client, package the application client in an application (EAR
fle). Then, either place the libraries in the /lib directory of the EARfle or specify their location
in the application client JARfle's manifest Class-Path.
DevelopingClients Without the ACC
This section describes the procedure to create, assemble, and deploy a Java-based client that is
not packaged using the Application Client Container (ACC).
Developing Clients Without the ACC
Chapter 10 Developing Java Clients 217
The following topics are addressed here:
Generic work context contract Ageneric contract that enables a resource adapter to
control the execution context of a Work instance that it has submitted to the GlassFish Server
for execution. The Generic work contract provides the mechanismfor a resource adapter to
augment the runtime context of a Work instance with additional contextual information
fown-in fromthe EIS. This contract enables a resource adapter to control, in a more fexible
manner, the contexts in which the Work instances submitted by it are executed by the
application server's WorkManager.
Security work context Astandard contract that enables a resource adapter to establish
security information while submitting a Work instance for execution to a WorkManager and
while delivering messages-to-message endpoints residing in the GlassFish Server. This
contract provides a mechanismto support the execution of a Work instance in the context of
an established identity. It also supports the propagation of user information or Principal
information froman EIS to a MessageEndpoint during message infow.
Transaction context The transaction context contract between the resource adapter and
the application server leverages the Generic Work Context mechanismby describing a
standard WorkContext, the TransactionContext. It represents the standard interface a
resource adapter can use to propagate transaction context information fromthe EIS to the
application server.
Connector Support in the GlassFish Server
Oracle GlassFish Server 3.1 Application Development Guide July 2011 224
Connector Architecture for JMS andJDBC
In the Administration Console, connector, JMS, and JDBCresources are handled diferently,
but they use the same underlying Connector architecture. In the GlassFish Server, all
communication to an EIS, whether to a message provider or an RDBMS, happens through the
Connector architecture. To provide JMS infrastructure to clients, the GlassFish Server uses the
GlassFish Server Message Queue software. To provide JDBCinfrastructure to clients, the
GlassFish Server uses its own JDBCsystemresource adapters. The GlassFish Server
automatically makes these systemresource adapters available to any client that requires them.
For more information about JMS in the GlassFish Server, see Chapter 17, Using the Java
Message Service. For more information about JDBCin the GlassFish Server, see Chapter 14,
Using the JDBCAPI for Database Access.
Connector Confguration
The GlassFish Server does not need to use sun-ra.xml, which previous GlassFish Server
versions used, to store server-specifc deployment information inside a Resource Adapter
Archive (RAR) fle. (However, the sun-ra.xml fle is still supported for backward
compatibility.) Instead, the information is stored in the server confguration. As a result, you
can create multiple connector connection pools for a connection defnition in a functional
resource adapter instance, and you can create multiple user-accessible connector resources
(that is, registering a resource with a JNDI name) for a connector connection pool. In addition,
dynamic changes can be made to connector connection pools and the connector resource
properties without restarting the GlassFish Server.
AdvancedConnector ConfgurationOptions
The following topics are addressed here:
In the Administration Console, select Thread Pools under the relevant confguration. For
details, click the Help button in the Administration Console.
Use the asadmin create-threadpool command. For details, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
To associate a connector with a thread pool:
In the Administration Console, open the Applications component and select Resource
Adapter Confgs. Specify the name of the thread pool in the Thread Pool IDfeld. For details,
click the Help button in the Administration Console.
In the Administration Console, open the Resources component, select Connectors, select
Connector Connection Pools, and select the Security Maps tab. For details, click the Help
button in the Administration Console.
Use the asadmin create-connector-security-map command. For details, see the Oracle
GlassFish Server 3.1-3.1.1 Reference Manual.
If a security map already exists for a connector connection pool, the newsecurity map is
appended to the previous one. The connector security map confguration supports the use of
the wildcard asterisk (*) to indicate all users or all user groups.
When an application principal initiates a request to an EIS, the GlassFish Server frst checks for
an exact match to a mapped back end EIS principal using the security map defned for the
Advanced Connector Confguration Options
Oracle GlassFish Server 3.1 Application Development Guide July 2011 226
connector connection pool. If there is no exact match, the GlassFish Server uses the wild card
character specifcation, if any, to determined the mapped back end EIS principal.
WorkSecurity Maps
Awork security map for a resource adapter maps an EIS principal or group to a application
principal or group. Awork security map is useful in situations where one or more application
principals execute operations initiated by principals or user groups in the EIS. Aresource
adapter can have multiple work security maps. Awork security map can map either principals
or groups, but not both.
To create a work security map, use the asadmin create-connector-work-security-map
command. For details, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
The work security map confguration supports the wildcard asterisk (*) character to indicate all
users or all user groups. When an EIS principal sends a request to the GlassFish Server, the
GlassFish Server frst checks for an exact match to a mapped application principal using the
work security map defned for the resource adapter. If there is no exact match, the GlassFish
Server uses the wild card character specifcation, if any, to determine the application principal.
OverridingConfgurationProperties
You can override the properties (config-property elements) specifed in the ra.xml fle of a
resource adapter:
In the Administration Console, open the Resources component and select Resource
Adapter Confgs. Create a newresource adapter confguration or select an existing one to
edit. Then enter property names and values in the Additional Properties table. For details,
click the Help button in the Administration Console.
In the Administration Console, open the Resources component, open the Connector
component, select Connection Pools, and select the connection pool you want to test. Then
select the Ping button in the top right corner of the page. For details, click the Help button in
the Administration Console.
Use the asadmin ping-connection-pool command. For details, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
Both these commands fail and display an error message unless they successfully connect to the
connection pool.
You can also specify that a connection pool is automatically tested when created or
reconfgured by setting the Ping attribute to true (the default is false) in one of the following
ways:
Enter a Ping value in the Connector Connection Pools page in the Administration Console.
For more information, click the Help button in the Administration Console.
In the Administration Console, open the Resources component, open the Connector
component, select Connection Pools, and select the connection pool you want to fush.
Then select the Flush button in the top right corner of the page. For details, click the Help
button in the Administration Console.
Use the asadmin flush-connection-pool command. For details, see the Oracle GlassFish
Server 3.1-3.1.1 Reference Manual.
Advanced Connector Confguration Options
Oracle GlassFish Server 3.1 Application Development Guide July 2011 228
HandlingInvalidConnections
If a resource adapter generates a ConnectionErrorOccured event, the GlassFish Server
considers the connection invalid and removes the connection fromthe connection pool.
Typically, a resource adapter generates a ConnectionErrorOccured event when it fnds a
ManagedConnection object unusable. Reasons can be network failure with the EIS, EIS failure,
fatal problems with the resource adapter, and so on.
If the fail-all-connections setting in the connection pool confguration is set to true, and a
single connection fails, all connections are closed and recreated. If this setting is false,
individual connections are recreated only when they are used. The default is false.
The is-connection-validation-required setting specifes whether connections have to be
validated before being given to the application. If a resources validation fails, it is destroyed,
and a newresource is created and returned. The default is false.
The prefer-validate-over-recreate property specifes that validating idle connections is
preferable to closing them. This property has no efect on non-idle connections. If set to true,
idle connections are validated during pool resizing, and only those found to be invalid are
destroyed and recreated. If false, all idle connections are destroyed and recreated during pool
resizing. The default is false.
You can set the fail-all-connections, is-connection-validation-required, and
prefer-validate-over-recreate confguration settings during creation of a connector
connection pool. Or, you can use the asadmin set command to dynamically reconfgure a
setting. For example:
asadmin set server.resources.connector-connection-pool.CCP1.fail-all-connections="true"
asadmin set server.resources.connector-connection-pool.CCP1.is-connection-validation-required="true"
asadmin set server.resources.connector-connection-pool.CCP1.property.prefer-validate-over-recreate="true"
For details, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
The interface ValidatingManagedConnectionFactory exposes the method
getInvalidConnections to allowretrieval of the invalid connections. The GlassFish Server
checks if the resource adapter implements this interface, and if it does, invalid connections are
removed when the connection pool is resized.
Settingthe ShutdownTimeout
According to the Connector specifcation, while an application server shuts down, all resource
adapters should be stopped. Aresource adapter might hang during shutdown, since shutdown
is typically a resource intensive operation. To avoid such a situation, you can set a timeout that
aborts resource adapter shutdown if exceeded. The default timeout is 30 seconds per resource
adapter module. To confgure this timeout:
Advanced Connector Confguration Options
Chapter 11 Developing Connectors 229
In the Administration Console, select Connector Service under the relevant confguration
and edit the shutdown Timeout feld. For details, click the Help button in the
Administration Console.
Enter a Pooling value in the Connector Connection Pools page in the Administration
Console. For more information, click the Help button in the Administration Console.
After the INIT_EVENT, the server reads the confguration, initializes built-in subsystems
(such as security and logging services), and creates the containers.
After the STARTUP_EVENT, the server loads and initializes deployed applications.
After the SHUTDOWN_EVENT, the server destroys loaded applications and stops.
After the TERMINATION_EVENT, the server closes the containers, the built-in subsystems, and
the server runtime environment.
These events are defned in the LifecycleEvent class.
The lifecycle modules that listen for these events implement the LifecycleListener interface.
The LifecycleListener Interface
To create a lifecycle module is to confgure a customized class that implements the
com.sun.appserv.server.LifecycleListener interface. You can create and simultaneously execute
multiple lifecycle modules.
The LifecycleListener interface defnes this method:
public void handleEvent(com.sun.appserv.server.LifecycleEvent event)
throws ServerLifecycleException
This method responds to a lifecycle event and throws a
com.sun.appserv.server.ServerLifecycleException if an error occurs.
Asample implementation of the LifecycleListener interface is the
LifecycleListenerImpl.java fle, which you can use for testing lifecycle events.
The LifecycleEvent Class
The com.sun.appserv.server.LifecycleEvent class defnes a server life cycle event. The
following methods are associated with the event:
public java.lang.Object.getData()
This method returns an instance of java.util.Properties that contains the properties
defned for the lifecycle module.
public
com.sun.appserv.server.LifecycleEventContext.getLifecycleEventContext()
This method returns the lifecycle event context, described next.
ALifecycleEvent instance is passed to the LifecycleListener.handleEvent method.
The Server Lifecycle Event Context
The com.sun.appserv.server.LifecycleEventContext interface exposes runtime information
about the server. The lifecycle event context is created when the LifecycleEvent class is
instantiated at server initialization. The LifecycleEventContext interface defnes these methods:
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 for lifecycle
modules is installed after the STARTUP_EVENT. Alifecycle module can look up any resource
by its jndi-name attribute after the READY_EVENT.
If a lifecycle module needs to look up resources, it can do so after the READY_EVENT. It can use
the getInitialContext method to get the initial context to which all the resources are bound.
Deployinga Lifecycle Module
For instructions on howto deploy a lifecycle module, see the Oracle GlassFish Server 3.1
Application Deployment Guide, or see the asadmin create-lifecycle-module command in
the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
You do not need to specify a classpath for the lifecycle module if you place it in the
domain-dir/lib or domain-dir/lib/classes directory for the Domain Administration Server.
Do not place it in the lib directory for a particular instance, or it will be deleted when that
instance synchronizes with the Domain Administration Server.
Deploying a Lifecycle Module
Chapter 12 Developing Lifecycle Listeners 237
Considerations for Lifecycle Modules
The resources allocated at initialization or startup should be freed at shutdown or termination.
The lifecycle module classes are called synchronously fromthe main server thread, therefore it
is important to ensure that these classes dont block the server. Lifecycle modules can create
threads if appropriate, but these threads must be stopped in the shutdown and termination
phases.
The LifeCycleModule class loader is the parent class loader for lifecycle modules. Each lifecycle
modules classpath is used to construct its class loader. All the support classes needed by a
lifecycle module must be available to the LifeCycleModule class loader or its parent, the
Connector class loader.
You must ensure that the server.policy fle is appropriately set up, or a lifecycle module
trying to performa System.exec() might cause a security access violation. For details, see The
server.policy File on page 58.
The confgured properties for a lifecycle module are passed as properties after the INIT_EVENT.
The JNDI naming context is not available before the STARTUP_EVENT. If a lifecycle module
requires the naming context, it can get this after the STARTUP_EVENT, READY_EVENT, or
SHUTDOWN_EVENT.
Considerations for Lifecycle Modules
Oracle GlassFish Server 3.1 Application Development Guide July 2011 238
Developing OSGi-enabled Java EE Applications
This chapter describes the features and interfaces that GlassFish Server provides to develop
OSGi-enabled enterprise applications. This chapter includes the following sections:
Plain OSGi Application Bundles bundles that do not contain any Java EE components.
See Developing Plain OSGi Bundles on page 241.
13
C H A P T E R 1 3
239
Hybrid Application Bundles bundles that are an OSGi bundle as wells as a Java EE
module. At runtime, such modules have both an OSGi bundle context and a Java EE context.
GlassFish Server supports the following hybrid application bundles:
Web Application Bundles (or WABs) , see Developing Web Application Bundles on
page 244.
EJB Application Bundles, see Developing EJB Application Bundles on page 246.
Benefts of UsingOSGi inEnterprise Java Applications
Enterprise applications typically need transactional, secured access to data stores, messaging
systems and other such enterprise information systems, and have to cater to a wide variety of
clients such as web browsers and desktop applications, and so on. Java EE makes development
of such applications easier with a rich set of APIs and frameworks. It also provides a scalable,
reliable and easy to administer runtime to host such applications.
The OSGi platformcomplements these features with modularity. It enables applications to be
separated into smaller, reusable modules with a well defned and robust dependency
specifcation. Amodule explicitly specifes its capabilities and requirements. This explicit
dependency specifcation encourages developers to visualize dependencies among their
modules and help themmake their modules highly cohesive and less coupled. The OSGi
module systemis dynamic: it allows modules to be added and removed at runtime. OSGi has
very good support for versioning: it supports package versioning as well module versioning. In
fact, it allows multiple versions of the same package to coexist in the same runtime, thus
allowing greater fexibility to deployers. The service layer of the OSGi platformencourages a
more service-oriented approach to build a system. The service-oriented approach and dynamic
module systemused together allowa systemto be more agile during development as well as in
production. It makes thembetter suited to run in an Platform-as-a-Service (PaaS) environment.
With GlassFish Server, you do not have to chose one of the two platforms. Ahybrid approach
like OSGi enabling your Java EE applications allows newcapabilities to applications hitherto
unavailable to applications built using just one of the two platforms.
DevelopingOSGi ApplicationBundles for GlassFishServer
GlassFish Server enables interaction between OSGi components and Java EE components.
OSGi services managed by the OSGi framework can invoke Java EE components managed by
the Java EE container and vice versa. For example, developers can declaratively export EJBs as
OSGi services without having to write any OSGi code. This allows any plain OSGi component,
which is running without the Java EE context, to discover the EJB and invoke it. Similarly, Java
EE components can locate OSGi services provided by plain OSGi bundles and use themas well.
GlassFish Server extends the Java EE Context and Dependency Injection (CDI) framework to
make it easier for Java EE components to consume dynamic OSGi services in a type-safe
manner.
Developing OSGi Application Bundles for GlassFish Server
Oracle GlassFish Server 3.1 Application Development Guide July 2011 240
javax.transaction.UserTransaction
javax.transaction.TransactionManager
javax.transaction.TransactionSynchronisationRegistry
There is no additional service property associated with them. Although UserTransaction
appears to be a singleton, in reality any call to it gets rerouted to the actual transaction
associated with the calling thread. Code that runs in the context of a Java EE component
typically gets a handle on UserTransaction by doing a JNDI lookup in the component naming
context or by using injection, as shown here:
(UserTransaction)(new InitialContext().lookup("java:comp/UserTransaction"));
or
@Resource UserTransaction utx;
When certain code (such as an OSGi Bundle Activator), which does not have a Java EE
component context, wants to get hold of UserTransaction, or any of the other JTAartifacts,
then they can look it up in the service registry. Here is an example of such code:
Developing OSGi Application Bundles for GlassFish Server
Oracle GlassFish Server 3.1 Application Development Guide July 2011 242
BundleContext context;
ServiceReference txRef =
context.getServiceReference(UserTransaction.class.getName());
UserTransaction utx = (UserTransaction);
context.getService(txRef);
JDBCData Source Service
Any JDBCdata source created in GlassFish Server is automatically made available as an OSGi
Service; therefore, OSGi bundles can track availability of JDBCdata sources using the
ServiceTracking facility of the OSGi platform. The life of the OSGi service matches that of the
underlying data source created in GlassFish Server. For instructions on administering JDBC
resources in GlassFish Server, see the Oracle GlassFish Server 3.1 Administration Guide.
GlassFish Server registers each JDBCdata source as an OSGi service with objectClass =
javax.sql.DataSource and a service property called jndi-name, which is set to the JNDI
name of the data source. Here is a code sample that looks up a data source service:
@Inject
@OSGiService(true,
"(jndi-name=jdbc/MyDS)")
private DataSource ds;
JMS Resource Service
Like JDBCdata sources, JMS administered objects, such as destinations and connection
factories, are also automatically made available as OSGi services. Their service mappings are as
follows.
JMS Object Service Interface Service Properties Comments
JMS Queue destination javax.jms.Queue jndi-name jndi-name is set to the
JNDI name of the queue
JMS Topic destination javax.jms.Topic jndi-name jndi-name is set to the
JNDI name of the topic
JMS connection factory javax.jms.QueueConnectionFactory
or
javax.jms.TopicConnectionFactory
or
javax.jms.ConnectionFactory
jndi-name jndi-name is set to the
JNDI name of the topic.
The actual service
interface depends on
which type of connection
factory was created.
Developing OSGi Application Bundles for GlassFish Server
Chapter 13 Developing OSGi-enabled Java EE Applications 243
DevelopingWebApplicationBundles
When a web application is packaged and deployed as an OSGi bundle, it is called a Web
Application Bundle (WAB). WAB support is based on the OSGi Web Application specifcation ,
which is part of the OSGi Service Platform, Enterprise Specifcation, Release 4, Version 4.2. A
WAB is packaged as an OSGi bundle, so all the OSGi packaging rules apply to WAB packaging.
When a WAB is not packaged like a WAR, the OSGi Web Container of GlassFish Server maps
the WAB to the hierarchical structure of web application using the following rules:
The root of the WAB corresponds to the docroot of the web application.
Every JARin the Bundle-ClassPath of the WAB is treated like a JARin WEB-INF/lib/.
serviceCriteria An LDAP flter query used for service selection in the OSGi service
registry.
waitTimeout Waits the specifed duration for a service that matches the criteria specifed
to appear in the OSGi service registry.
waitTimeout Waits for specifed duration for a service to appear in the OSGi service
registry.
Enter an Init SQL value in the Edit Connection Pool Advanced Attributes page in the
Administration Console. For more information, click the Help button in the
Administration Console.
Specify the init-sql option in the asadmin set command. For example:
asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.init-sql="sql-string"
For more information, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
Settinga Statement Timeout
An abnormally long running JDBCquery executed by an application may leave it in a hanging
state unless a timeout is explicitly set on the statement. Setting a statement timeout guarantees
that all queries automatically time out if not completed within the specifed period. When
statements are created, the queryTimeout is set according to the statement timeout setting. This
works only when the underlying JDBCdriver supports queryTimeout for Statement,
PreparedStatement, CallableStatement, and ResultSet.
You can specify a statement timeout in the following ways:
Enter a Statement Timeout value in the Edit Connection Pool Advanced Attributes page in
the Administration Console. For more information, click the Help button in the
Administration Console.
Statements
Oracle GlassFish Server 3.1 Application Development Guide July 2011 252
It is less than the Connection Leak Timeout; otherwise, the connection could be closed
before the statement leak is recognized.
It is greater than the Statement Timeout; otherwise, a long running query could be mistaken
as a statement leak.
After enabling statement leak detection, enable leaked statement reclamation by setting
ReclaimLeaked Statements for the JDBCconnection pool to a true value in one of the
following ways:
Enter a Statement Cache Size value in the Edit Connection Pool Advanced Attributes page
in the Administration Console. For more information, click the Help button in the
Administration Console.
Specify the statement-cache-size option in the asadmin set command. For example:
asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.statement-cache-size=10
For more information, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
By default, this attribute is set to zero and the statement caching is turned of. To enable
statement caching, you can set any positive nonzero value. The built-in cache eviction strategy
is LRU-based (Least Recently Used). When a connection pool is fushed, the connections in the
statement cache are recreated.
Statement Tracing
You can trace the SQL statements executed by applications that use a JDBCconnection pool.
Set the SQL Trace Listeners attribute to a comma-separated list of trace listener implementation
classes in one of the following ways:
Enter an SQL Trace Listeners value in the Edit Connection Pool Advanced Attributes page
in the Administration Console. For more information, click the Help button in the
Administration Console.
Specify the sql-trace-listeners option in the asadmin set command. For example:
asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.sql-trace-listeners=listeners
For more information, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
The GlassFish Server provides a public interface, org.glassfsh.api.jdbc.SQLTraceListener, that
implements a means of recording SQLTraceRecord objects. To make customimplementations
of this interface available to the GlassFish Server, place the implementation classes in
as-install/lib.
The GlassFish Server provides an SQL tracing logger to log the SQL operations in the formof
SQLTraceRecord objects in the server.log fle. The module name under which the SQL
Statements
Oracle GlassFish Server 3.1 Application Development Guide July 2011 254
operation is logged is javax.enterprise.resource.sqltrace. SQL traces are logged as FINE
messages along with the module name to enable easy fltering of the SQL logs. Asample SQL
trace record looks like this:
[#|2009-11-27T15:46:52.202+0530|FINE|glassfishv3.0|javax.enterprise.resource.sqltrace.com.sun.gjc.util
|_ThreadID=29;_ThreadName=Thread-1;ClassName=com.sun.gjc.util.SQLTraceLogger;MethodName=sqlTrace;
|ThreadID=77 | ThreadName=p: thread-pool-1; w: 6 | TimeStamp=1259317012202
| ClassName=com.sun.gjc.spi.jdbc40.PreparedStatementWrapper40 | MethodName=executeUpdate
| arg[0]=insert into table1(colName) values(100) | arg[1]=columnNames | |#]
This trace shows that an executeUpdate(String sql, String columnNames) operation is
being done.
When SQL statement tracing is enabled and JDBCconnection pool monitoring is enabled,
GlassFish Server maintains a tracing cache of recent queries and their frequency of use. The
following JDBCconnection pool properties can be confgured to control this cache and the
monitoring statistics available fromit:
time-to-keep-queries-in-minutes
Specifes howlong in minutes to keep a query in the tracing cache, tracking its frequency of
use. The default value is 5 minutes.
number-of-top-queries-to-report
Specifes howmany of the most used queries, in frequency order, are listed the monitoring
report. The default value is 10 queries.
Set these parameters in one of the following ways:
Add themas properties in the Edit JDBCConnection Pool Properties page in the
Administration Console. For more information, click the Help button in the
Administration Console.
Enter a Pooling value in the Edit Connection Pool Advanced Attributes page in the
Administration Console. For more information, click the Help button in the
Administration Console.
Specify the pooling option in the asadmin set command. For example:
asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.pooling=false
Connections
Oracle GlassFish Server 3.1 Application Development Guide July 2011 256
For more information, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
The pooling option and the systemproperty com.sun.enterprise.connectors.
SwitchoffACCConnectionPooling, which turns of connection pooling in the Application
Client Container, do not afect each other.
An exception is thrown if associate-with-thread is set to true and pooling is disabled. An
exception is thrown if you attempt to fush a connection pool when pooling is disabled. A
warning is logged if the following attributes are used, because they are useful only in a pooled
environment:
connection-validation
validate-atmost-once-period
match-connections
max-connection-usage
idle-timeout
AssociatingConnections withThreads
To associate connections with a thread, set the Associate With Thread attribute to true. The
default is false. Atrue setting allows connections to be saved as ThreadLocal in the calling
thread. Connections get reclaimed only when the calling thread dies or when the calling thread
is not in use and the pool has run out of connections. If the setting is false, the thread must
obtain a connection fromthe pool each time the thread requires a connection.
The Associate With Thread attribute associates connections with a thread such that when the
same thread is in need of connections, it can reuse the connections already associated with that
thread. In this case, the overhead of getting connections fromthe pool is avoided. However,
when this value is set to true, you should verify that the value of the Max Pool Size attribute is
comparable to the Max Thread Pool Size attribute of the thread pool. If the Max Thread Pool
Size value is much higher than the Max Pool Size value, a lot of time is spent associating
connections with a newthread after dissociating themfroman older one. Use this attribute in
cases where the thread pool should reuse connections to avoid this overhead.
You can set the Associate With Thread attribute in the following ways:
Enter an Associate With Thread value in the Edit Connection Pool Advanced Attributes
page in the Administration Console. For more information, click the Help button in the
Administration Console.
Specify the associate-with-thread option in the asadmin set command. For example:
asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.associate-with-thread=true
Connections
Chapter 14 Using the JDBC API for Database Access 257
For more information, see the Oracle GlassFish Server 3.1-3.1.1 Reference Manual.
CustomConnectionValidation
You can specify a customimplementation for Connection Validation that is faster or optimized
for a specifc database. Set the Validation Method attribute to the value custom-validation.
(Other validation methods available are table (the default), auto-commit, and meta-data.)
The GlassFish Server provides a public interface, org.glassfsh.api.jdbc.ConnectionValidation,
which you can implement to plug in your implementation. Anewattribute, Validation
Classname, specifes the fully qualifed name of the class that implements the
ConnectionValidation interface. The Validation Classname attribute is required if Connection
Validation is enabled and Validation Method is set to CustomValidation.
To enable this feature, set Connection Validation, Validation Method, and Validation
Classname for the JDBCconnection pool in one of the following ways:
Enter Connection Validation, Validation Method, and Validation Classname values in the
Edit Connection Pool Advanced Attributes page in the Administration Console. You can
select fromamong validation class names for common databases in the Validation
Classname feld. For more information, click the Help button in the Administration
Console.
Check or uncheck the Wrap JDBCObjects box on the Edit Connection Pool Advanced
Attributes page in the Administration Console. For more information, click the Help button
in the Administration Console.
Check the AllowNon Component Callers box on the Edit Connection Pool Advanced
Attributes page in the Administration Console. The default is false. For more information,
click the Help button in the Administration Console.
Select the value fromthe Transaction Isolation drop-down list on the NewJDBC
Connection Pool or Edit Connection Pool page in the Administration Console. For more
information, click the Help button in the Administration Console.
Check the Isolation Level Guaranteed box on the NewJDBCConnection Pool or Edit
Connection Pool page in the Administration Console. For more information, click the Help
button in the Administration Console.
Create a resource with the JNDI name ending in __nontx. This forces all connections looked
up using this resource to be non transactional.
Typically, a connection is enlisted in the context of the transaction in which a getConnection
call is invoked. However, a non-transactional connection is not enlisted in a transaction context
even if a transaction is in progress.
The main advantage of using non-transactional connections is that the overhead incurred in
enlisting and delisting connections in transaction contexts is avoided. However, use such
connections carefully. For example, if a non-transactional connection is used to query the
database while a transaction is in progress that modifes the database, the query retrieves the
unmodifed data in the database. This is because the in-progress transaction hasnt committed.
For another example, if a non-transactional connection modifes the database and a transaction
that is running simultaneously rolls back, the changes made by the non-transactional
connection are not rolled back.
Here is a typical use case for a non-transactional connection: a component that is updating a
database in a transaction context spanning over several iterations of a loop can refresh cached
data by using a non-transactional connection to read data before the transaction commits.
HandlingTransactions withEnterprise Beans
This section describes the transaction support built into the Enterprise JavaBeans programming
model for the GlassFish Server.
As a developer, you can write an application that updates data in multiple databases distributed
across multiple sites. The site might use EJB servers fromdiferent vendors.
The following topics are addressed here:
Option A The container caches a ready instance between transactions. The container
ensures that the instance has exclusive access to the state of the object in persistent storage.
In this case, the container does not have to synchronize the instances state fromthe
persistent storage at the beginning of the next transaction.
Note Commit option Ais not supported for this GlassFish Server release.
Option B The container caches a ready instance between transactions, but the container
does not ensure that the instance has exclusive access to the state of the object in persistent
storage. This is the default.
In this case, the container must synchronize the instances state by invoking ejbLoad from
persistent storage at the beginning of the next transaction.
Option C The container does not cache a ready instance between transactions, but instead
returns the instance to the pool of available instances after a transaction has completed.
The life cycle for every business method invocation under commit option Clooks like this.
HandlingTransactions with Enterprise Beans
Chapter 15 Using theTransaction Service 269
ejbActivate ejbLoad business method ejbStore ejbPassivate
If there is more than one transactional client concurrently accessing the same entity, the frst
client gets the ready instance and subsequent concurrent clients get newinstances fromthe
pool.
The glassfish-ejb-jar.xml deployment descriptor has an element, commit-option, that
specifes the commit option to be used. Based on the specifed commit option, the appropriate
handler is instantiated.
Bean-Level Container-ManagedTransactionTimeouts
The transaction timeout for the domain is specifed using the Transaction Timeout setting of
the Transaction Service. Atransaction started by the container must commit (or rollback)
within this time, regardless of whether the transaction is suspended (and resumed), or the
transaction is marked for rollback. The default value, 0, specifes that the server waits
indefnitely for a transaction to complete.
To override this timeout for an individual bean, use the optional cmt-timeout-in-seconds
element in glassfish-ejb-jar.xml. The default value, 0, specifes that the Transaction Service
timeout is used. The value of cmt-timeout-in-seconds is used for all methods in the bean that
start a newcontainer-managed transaction. This value is not used if the bean joins a client
transaction.
HandlingTransactions withthe Java Message Service
The following topics are addressed here:
Accessing EJB Components Using the CosNaming Naming Context on page 275
For an EJB 2.x dependency or a session or entity bean with a remote interface, the default
is the fully qualifed name of the home interface.
For an EJB 3.0 dependency or a session bean with a remote interface, the default is the
fully qualifed name of the remote business interface.
If both EJB 2.x and EJB 3.0 remote interfaces are specifed, or if more than one 3.0
remote interface is specifed, there is no default, and the global JNDI name must be
specifed.
For all other component dependencies that must be mapped to global JNDI names, the
default is the name of 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.
Accessing the Naming Context
Oracle GlassFish Server 3.1 Application Development Guide July 2011 274
AccessingEJBComponents Usingthe CosNaming
NamingContext
The preferred way of accessing the naming service, even in code that runs outside of a Java EE
container, is to use the no-argument InitialContext constructor. However, if EJB client code
explicitly instantiates an InitialContext that points to the CosNaming naming service, it is
necessary to set the java.naming.factory.initial property to
com.sun.jndi.cosnaming.CNCtxFactory in the client JVMsoftware when accessing EJB
components. You can set this property as a command-line argument, as follows:
-Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
Or you can set this property in the code, as follows:
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. The property is not
cluster-aware.
AccessingEJBComponents ina Remote GlassFish
Server
The recommended approach for looking up an EJB component in a remote GlassFish Server
froma client that is a servlet or EJB component is to use the Interoperable Naming Service
syntax. Host and port information is prepended to any global JNDI names and is automatically
resolved during the lookup. The syntax for an interoperable global name is as follows:
corbaname:iiop:host:port#a/b/name
This makes the programming model for accessing EJB components in another GlassFish Server
exactly the same as accessing themin the same server. The deployer can change the way the EJB
components are physically distributed without having to change the code.
For Java EE components, the code still performs a java:comp/env lookup on an EJB reference.
The only diference is that the deployer maps the ejb-reference element to an interoperable
name in a GlassFish Server deployment descriptor fle instead of to a simple global JNDI name.
For example, suppose a servlet looks up an EJB reference using java:comp/env/ejb/Foo, and
the target EJB component has a global JNDI name of a/b/Foo.
The ejb-ref element in glassfish-web.xml looks like this:
Accessing the Naming Context
Chapter 16 Using the Java Naming and Directory Interface 275
<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 doesnt run within a Java EE container, the code just uses the interoperable
global name instead of 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-specifc (java:comp/env)
naming contexts are transient. On each server startup or application reloading, all relevant
objects are re-bound to the namespace.
NamingEnvironment for Lifecycle Modules
Lifecycle listener modules provide a means of running short or long duration tasks based on
Java technology within the GlassFish Server environment, such as instantiation of singletons or
RMI servers. These modules are automatically initiated at server startup and are notifed at
various phases of the server life cycle. For details about lifecycle modules, see Chapter 12,
Developing Lifecycle Listeners.
The confgured properties for a lifecycle module are passed as properties during server
initialization (the INIT_EVENT). The initial JNDI naming context is not available until server
initialization is complete. Alifecycle module can get the InitialContext for lookups using the
method LifecycleEventContext.getInitialContext() during, and only during, the
STARTUP_EVENT, READY_EVENT, or SHUTDOWN_EVENT server life cycle events.
ConfguringResources
The GlassFish Server exposes special resources in the naming environment.
To create an external JNDI resource using the Administration Console, open the Resources
component, open the JNDI component, and select External Resources. For details, click the
Help button in the Administration Console.
int
long
double
float
char
short
byte
Confguring Resources
Oracle GlassFish Server 3.1 Application Development Guide July 2011 278
boolean
String
3. Create a property in the customresource named value and give it the value needed by the
application.
For example, If the application requires a double of value 22.1, create a property with the
name value and the value 22.1.
URLFactory
To create a customresource that provides URL instances to applications, followthese steps:
1. Set the customresource's factory class to
org.glassfish.resources.custom.factory.URLObjectFactory.
2. Choose which of the following constructors to use:
URL(spec)
3. Defne properties according to the chosen constructor.
For example, for the frst constructor, defne properties named protocol, host, port, and
file. Example values might be http, localhost, 8085, and index.html, respectively.
For the third constructor, defne a property named spec and assign it the value of the entire
URL.
DisablingGlassFishServer V2Vendor-Specifc JNDI
Names
The EJB 3.1 specifcation supported by GlassFish Server 3.1 defnes portable EJB JNDI names.
Because of this, there is less need to continue to use older vendor-specifc JNDI names.
By default, GlassFish Server V2specifc JNDI names are applied automatically by GlassFish
Server 3.1 for backward compatibility. However, this can lead to some ease-of-use issues. For
example, deploying two diferent applications containing a remote EJB component that exposes
the same remote interface causes a confict between the default JNDI names.
The default handling of V2specifc JNDI names in GlassFish Server 3.1 can be managed by
using the asadmin command:
asadmin> set server.ejb-container.property.disable-nonportable-jndi-names="true"
disable-nonportable-jndi-names is a boolean property that can take the following values:
false
Enables the automatic use of GlassFish Server V2specifc JNDI names. This is the default
setting.
Confguring Resources
Chapter 16 Using the Java Naming and Directory Interface 279
true
Disables the automatic use of V2specifc JNDI names. In all cases, 3.1-compatible JNDI
names are used.
Note that this setting applies to all EJB components deployed to the server.
UsingApplication-ScopedResources
You can defne an application-scoped JNDI or other resource for an enterprise application, web
module, EJB module, connector module, or application client module by supplying a
glassfish-resources.xml deployment descriptor fle. For details, see Application-Scoped
Resources in Oracle GlassFish Server 3.1 Application Deployment Guide.
Usinga Customjndi.properties File
To use a customjndi.properties fle, place the fle in the domain-dir/lib/classes directory
or JARit and place it in the domain-dir/lib directory. This adds the customjndi.properties
fle to the Common class loader. For more information about class loading, see Chapter 2,
Class Loaders.
For each property found in more than one jndi.properties fle, the Java EE naming service
either uses the frst value found or concatenates all of the values, whichever makes sense.
MappingReferences
The following XML elements in the GlassFish Server deployment descriptors map resource
references in application client, EJB, and web application components to JNDI names
confgured in the GlassFish Server:
ejb-ref - Maps the @EJB annotation (or the ejb-ref element in the corresponding Java EE
XML fle) to the absolute JNDI name confgured in the GlassFish Server.
JNDI names for EJB components must be unique. For example, appending the application
name and the module name to the EJB name is one way to guarantee unique names. In this
case, mycompany.pkging.pkgingEJB.MyEJB would be the JNDI name for an EJB in the
module pkgingEJB.jar, which is packaged in the pkging.ear application.
Using a Customjndi.properties File
Oracle GlassFish Server 3.1 Application Development Guide July 2011 280
These elements are part of the glassfish-web.xml, glassfish-application-client.xml,
glassfish-ejb-jar.xml, and glassfish-application.xml deployment descriptor fles. For
more information about howthese elements behave in each of the deployment descriptor fles,
see Appendix C, Elements of the GlassFish Server Deployment Descriptors, in Oracle
GlassFish Server 3.1 Application Deployment Guide.
The rest of this section uses an example of a JDBCresource lookup to describe howto reference
resource factories. The same principle is applicable to all resources (such as JMS destinations,
JavaMail sessions, and so on).
The @Resource annotation in the application code looks like this:
@Resource(name="jdbc/helloDbDs") javax.sql.DataSource ds;
This references a resource with the JNDI name of java:jdbc/helloDbDs. If this is the JNDI
name of the JDBCresource confgured in the GlassFish Server, the annotation alone is enough
to reference the resource.
However, you can use a GlassFish Server specifc deployment descriptor to override the
annotation. For example, the resource-ref element in the glassfish-web.xml fle maps the
res-ref-name (the name specifed in the annotation) to the JNDI name of another JDBC
resource confgured in the GlassFish Server.
<resource-ref>
<res-ref-name>jdbc/helloDbDs</res-ref-name>
<jndi-name>jdbc/helloDbDataSource</jndi-name>
</resource-ref>
Mapping References
Chapter 16 Using the Java Naming and Directory Interface 281
282
Using the Java Message Service
This chapter describes howto use the Java Message Service (JMS) API. The Oracle GlassFish
Server has a fully integrated JMS provider: the GlassFish Server Message Queue software.
Note JMS resources are supported only in the full GlassFish Server, not in the Web Profle.
For general information about the JMS API, see Chapter 31: The Java Message Service API in
the The Java EE 6 Tutorial (http://download.oracle.com/javaee/6/tutorial/doc/).
For detailed information about JMS concepts and JMS support in the GlassFish Server, see
Chapter 17, Administering the Java Message Service (JMS), in Oracle GlassFish Server 3.1
Administration Guide.
For more information about Message Queue software, see the Oracle GlassFish Server Message
Queue 4.5 Administration Guide.
The following topics are addressed here:
The abstract layer declares classes, interfaces, and abstract methods intended to support
mail handling functions that all mail systems support.
The internet implementation layer implements part of the abstract layer using the RFC822
and MIME internet standards.
18
C H A P T E R 1 8
289
JavaMail uses the JavaBeans Activation Framework (JAF) to encapsulate message data and to
handle commands intended to interact with that data.
For more information, see Chapter 16, Administering the JavaMail Service, in Oracle
GlassFish Server 3.1 Administration Guide and the JavaMail specifcation at
http://www.oracle.com/technetwork/java/javamail/index.html. Auseful JavaMail
tutorial is located at http://java.sun.com/developer/onlineTraining/JavaMail/.
Creatinga JavaMail Session
You can create a JavaMail session in the following ways:
In the Administration Console, open the Resources component and select JavaMail
Sessions. For details, click the Help button in the Administration Console.
Use the asadmin create-javamail-resource command. For details, see the Oracle
GlassFish Server 3.1-3.1.1 Reference Manual.
JavaMail SessionProperties
You can set properties for a JavaMail Session object. Every property name must start with a
mail- prefx. The GlassFish Server changes the dash (-) character to a period (.) in the name of
the property and saves the property to the MailConfiguration and JavaMail Session objects. If
the name of the property doesnt start with mail-, the property is ignored.
For example, if you want to defne the property mail.from in a JavaMail Session object, frst
defne the property as follows:
Name mail-from
Value [email protected]
LookingUpa JavaMail Session
The standard Java Naming and Directory Interface (JNDI) subcontext for JavaMail sessions is
java:comp/env/mail.
Registering JavaMail sessions in the mail naming subcontext of a JNDI namespace, or in one of
its child subcontexts, is standard. The JNDI namespace is hierarchical, like a fle systems
directory structure, so it is easy to fnd and nest references. AJavaMail session is bound to a
logical JNDI name. The name identifes a subcontext, mail, of the root context, and a logical
name. To change the JavaMail session, you can change its entry in the JNDI namespace without
having to modify the application.
The resource lookup in the application code looks like this:
Creating a JavaMail Session
Oracle GlassFish Server 3.1 Application Development Guide July 2011 290
InitialContext ic = new InitialContext();
String snName = "java:comp/env/mail/MyMailSession";
Session session = (Session)ic.lookup(snName);
For more information about the JNDI API, see Chapter 16, Using the Java Naming and
Directory Interface.
SendingandReadingMessages UsingJavaMail
The following topics are addressed here: