Application Development Guide PDF
Application Development Guide PDF
Application Development Guide PDF
May 2013
This Application Development Guide describes how to
create and run Java Platform, Enterprise Edition (Java EE
platform) applications that follow the open Java standards
model for Java EE components and APIs in the GlassFish
Server Open Source Edition 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.
GlassFish Server Open Source Edition Application Development Guide, Release 4.0
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 law for interoperability, is
prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If
you find any errors, please report them to 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. GOVERNMENT RIGHTS 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-specific supplemental regulations. As
such, the use, duplication, disclosure, modification, 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 FAR 52.227-19, Commercial Computer Software
License (December 2007). Oracle America, Inc., 500 Oracle Parkway, Redwood City, CA 94065.
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 affiliates disclaim any 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 affiliates. Other names may be trademarks of
their respective owners.
Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks
are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD,
Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced
Micro Devices. UNIX is a registered trademark of The Open Group.
This software or hardware and documentation may provide access to or information on content, products,
and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly
disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle
Corporation and its affiliates 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.
Contents
Preface ............................................................................................................................................................... xv
2 Class Loaders
The Class Loader Hierarchy ................................................................................................................... 2-1
Delegation.................................................................................................................................................. 2-2
Using the Java Optional Package Mechanism.................................................................................... 2-3
Using the Endorsed Standards Override Mechanism....................................................................... 2-3
Class Loader Universes ........................................................................................................................... 2-3
Application-Specific Class Loading ..................................................................................................... 2-4
Circumventing Class Loader Isolation................................................................................................. 2-5
Using the Common Class Loader .................................................................................................... 2-5
Sharing Libraries Across a Cluster .................................................................................................. 2-5
Packaging the Client JAR for One Application in Another Application ................................... 2-5
To Package the Client JAR for One Application in Another Application ................................. 2-6
3 Debugging Applications
Enabling Debugging................................................................................................................................ 3-1
To Set the Server to Automatically Start Up in Debug Mode...................................................... 3-2
JPDA Options............................................................................................................................................ 3-2
Generating a Stack Trace for Debugging............................................................................................. 3-2
iii
Application Client Debugging .............................................................................................................. 3-2
Open Message Queue Debugging ........................................................................................................ 3-3
Enabling Verbose Mode.......................................................................................................................... 3-3
Class Loader Debugging......................................................................................................................... 3-3
GlassFish Server Logging ....................................................................................................................... 3-4
Profiling Tools........................................................................................................................................... 3-4
The NetBeans Profiler........................................................................................................................ 3-4
The HPROF Profiler........................................................................................................................... 3-4
The JProbe Profiler ............................................................................................................................. 3-6
4 Securing Applications
Security Goals ........................................................................................................................................... 4-1
GlassFish Server Specific Security Features ....................................................................................... 4-2
Container Security.................................................................................................................................... 4-2
Declarative Security ........................................................................................................................... 4-2
Programmatic Security ...................................................................................................................... 4-3
Roles, Principals, and Principal to Role Mapping............................................................................. 4-4
Realm Configuration ............................................................................................................................... 4-5
Supported Realms .............................................................................................................................. 4-5
How to Configure a Realm ............................................................................................................... 4-5
How to Set a Realm for an Application or Module....................................................................... 4-6
Creating a Custom Realm ................................................................................................................. 4-6
JACC Support............................................................................................................................................ 4-8
Pluggable Audit Module Support ........................................................................................................ 4-9
Configuring an Audit Module ......................................................................................................... 4-9
The AuditModule Class ...................................................................................................................... 4-9
The server.policy File ........................................................................................................................ 4-10
Default Permissions ........................................................................................................................ 4-10
System Properties............................................................................................................................ 4-11
Changing Permissions for an Application .................................................................................. 4-11
Enabling and Disabling the Security Manager ........................................................................... 4-13
Configuring Message Security for Web Services............................................................................ 4-14
Message Security Providers........................................................................................................... 4-15
Message Security Responsibilities ................................................................................................ 4-16
Application-Specific Message Protection .................................................................................... 4-17
Understanding and Running the Sample Application .............................................................. 4-20
Programmatic Login.............................................................................................................................. 4-22
Programmatic Login Precautions ................................................................................................. 4-22
Granting Programmatic Login Permission ................................................................................. 4-23
The ProgrammaticLogin Class....................................................................................................... 4-23
User Authentication for Single Sign-on ........................................................................................... 4-24
Adding Authentication Mechanisms to the Servlet Container.................................................... 4-25
The GlassFish Server and JSR 196................................................................................................. 4-26
Writing a Server Authentication Module .................................................................................... 4-26
Sample Server Authentication Module........................................................................................ 4-28
iv
Compiling and Installing a Server Authentication Module ..................................................... 4-31
Configuring a Server Authentication Module ............................................................................ 4-31
Binding a Server Authentication Module to Your Application ............................................... 4-32
v
Internationalization Issues............................................................................................................. 7-27
Virtual Server Properties................................................................................................................ 7-28
Class Loader Delegation ................................................................................................................ 7-28
Using the default-web.xml File ................................................................................................... 7-29
Configuring Logging and Monitoring in the Web Container .................................................. 7-29
Configuring Idempotent URL Requests ...................................................................................... 7-30
Header Management ...................................................................................................................... 7-31
Configuring Valves and Catalina Listeners ................................................................................ 7-31
Alternate Document Roots ............................................................................................................ 7-31
Using a context.xml File ................................................................................................................. 7-32
Enabling WebDav ........................................................................................................................... 7-33
Using SSI........................................................................................................................................... 7-34
Using CGI ......................................................................................................................................... 7-35
vi
Using the capture-schema Utility ................................................................................................ 9-11
Configuring the CMP Resource ......................................................................................................... 9-11
Performance-Related Features ............................................................................................................ 9-12
Version Column Consistency Checking ...................................................................................... 9-12
Relationship Prefetching ................................................................................................................ 9-13
Read-Only Beans ............................................................................................................................. 9-13
Default Fetch Group Flags................................................................................................................... 9-14
Configuring Queries for 1.1 Finders.................................................................................................. 9-14
About JDOQL Queries ................................................................................................................... 9-14
Query Filter Expression.................................................................................................................. 9-15
Query Parameters ........................................................................................................................... 9-16
Query Variables............................................................................................................................... 9-16
JDOQL Examples ............................................................................................................................ 9-16
CMP Restrictions and Optimizations ............................................................................................... 9-17
Disabling ORDER BY Validation.................................................................................................. 9-18
Setting the Heap Size on DB2 ........................................................................................................ 9-18
Eager Loading of Field State.......................................................................................................... 9-18
Restrictions on Remote Interfaces................................................................................................. 9-18
PostgreSQL Case Insensitivity ...................................................................................................... 9-19
No Support for lock-when-loaded on Sybase ............................................................................ 9-19
Sybase Finder Limitation ............................................................................................................... 9-19
Date and Time Fields ...................................................................................................................... 9-19
Set RECURSIVE_TRIGGERS to false on MSSQL ............................................................................ 9-20
MySQL Database Restrictions ....................................................................................................... 9-20
vii
To access an EJB component from a server-side module ........................................................ 10-20
To access a JMS resource from a stand-alone client ................................................................. 10-22
11 Developing Connectors
Connector Support in the GlassFish Server..................................................................................... 11-2
Connector Architecture for JMS and JDBC ................................................................................. 11-2
Connector Configuration ............................................................................................................... 11-2
Advanced Connector Configuration Options.................................................................................. 11-3
Thread Associations........................................................................................................................ 11-3
Security Maps .................................................................................................................................. 11-4
Work Security Maps ....................................................................................................................... 11-4
Overriding Configuration Properties........................................................................................... 11-4
Testing a Connector Connection Pool.......................................................................................... 11-5
Flushing a Connector Connection Pool ....................................................................................... 11-5
Handling Invalid Connections ...................................................................................................... 11-5
Setting the Shutdown Timeout ..................................................................................................... 11-6
Specifying the Class Loading Policy ............................................................................................ 11-7
Using Last Agent Optimization of Transactions ........................................................................ 11-7
Disabling Pooling for a Connection.............................................................................................. 11-7
Using Application-Scoped Connectors........................................................................................ 11-7
Inbound Communication Support .................................................................................................... 11-8
Outbound Communication Support ................................................................................................. 11-8
Configuring a Message Driven Bean to Use a Resource Adapter ............................................... 11-8
viii
Setting a Statement Timeout.......................................................................................................... 14-2
Statement Leak Detection and Leaked Statement Reclamation ............................................... 14-2
Statement Caching .......................................................................................................................... 14-3
Statement Tracing ........................................................................................................................... 14-3
Connections ............................................................................................................................................ 14-5
Transparent Pool Reconfiguration................................................................................................ 14-5
Disabling Pooling ............................................................................................................................ 14-6
Associating Connections with Threads ....................................................................................... 14-6
Custom Connection Validation..................................................................................................... 14-7
Sharing Connections ....................................................................................................................... 14-8
Marking Bad Connections ............................................................................................................. 14-8
Handling Invalid Connections ...................................................................................................... 14-8
Connection Wrapping........................................................................................................................... 14-9
Wrapping Connections................................................................................................................... 14-9
Obtaining a Physical Connection From a Wrapped Connection ........................................... 14-10
Using the Connection.unwrap() Method ................................................................................. 14-10
Allowing Non-Component Callers.................................................................................................. 14-10
Using Application-Scoped Resources ............................................................................................. 14-11
Restrictions and Optimizations........................................................................................................ 14-11
Disabling Stored Procedure Creation on Sybase...................................................................... 14-11
ix
Built-in Factories for Custom Resources...................................................................................... 16-6
Using Application-Scoped Resources .......................................................................................... 16-7
Using a Custom jndi.properties File .............................................................................................. 16-8
Mapping References ............................................................................................................................. 16-8
x
xi
List of Examples
13–1 Example of a WAB Using CDI ............................................................................................... 13-7
xii
List of Figures
xiii
List of Tables
2–1 Oracle GlassFish Server Class Loaders................................................................................... 2-2
4–1 Predefined System Properties ............................................................................................... 4-11
4–2 Message Security Provider Properties ................................................................................. 4-16
6–1 The asadmin deploy and asadmin deploydir Generation Options .................................. 6-7
6–2 The asadmin undeploy Generation Options.......................................................................... 6-7
7–1 The cache Attributes ................................................................................................................. 7-7
7–2 The flush Attributes ................................................................................................................. 7-8
7–3 Object Types Supported for Java EE Web Application Session State Failover.............. 7-11
7–4 SSIServlet init-param Values ............................................................................................ 7-35
7–5 CGIServlet init-param Values ............................................................................................ 7-36
8–1 Object Types Supported for Java EE Stateful Session Bean State Failover........................ 8-9
9–1 Java Type to JDBC Type Mappings for CMP......................................................................... 9-6
9–2 Mappings of JDBC Types to Database Vendor Specific Types for CMP ........................... 9-7
9–3 The glassfish-ejb-jar.xml Generation Elements ............................................................. 9-8
9–4 The asadmin deploy and asadmin deploydir Generation Options for CMP .................. 9-9
9–5 The asadmin undeploy Generation Options for CMP....................................................... 9-10
10–1 Owned JNLP File Content ................................................................................................... 10-13
10–2 Defaulted JNLP File Content............................................................................................... 10-13
10–3 Merged JNLP File Content .................................................................................................. 10-14
15–1 Transaction Isolation Levels.................................................................................................. 15-2
xiv
Preface
This Application Development Guide describes how to create and run Java Platform,
Enterprise Edition (Java EE platform) applications that follow the 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 GlassFish
Server Open Source Edition (GlassFish Server) documentation set.
GlassFish Server 4.0 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 platform that makes the new
features 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:
■ GlassFish Server Documentation Set
■ Related Documentation
■ Typographic Conventions
■ Symbol Conventions
■ Default Paths and File Names
■ Documentation, Support, and Training
■ Searching Oracle Product Documentation
■ Documentation Accessibility
xv
Book Title Description
Release Notes Provides late-breaking information about the software and the
documentation and includes a comprehensive, table-based
summary of the supported hardware, operating system, Java
Development Kit (JDK), and database drivers.
Quick Start Guide Explains how to get started with the GlassFish Server product.
Installation Guide Explains how to install the software and its components.
Upgrade Guide Explains how to upgrade to the latest version of GlassFish Server.
This guide also describes differences between adjacent product
releases and configuration options that can result in
incompatibility with the product specifications.
Deployment Planning Guide Explains how to build a production deployment of GlassFish
Server that meets the requirements of your system and enterprise.
Administration Guide Explains how to configure, monitor, and manage GlassFish Server
subsystems and components from the command line by using the
asadmin utility. Instructions for performing these tasks from the
Administration Console are provided in the Administration
Console online help.
Security Guide Provides instructions for configuring and administering GlassFish
Server security.
Application Deployment Explains how to assemble and deploy applications to the
Guide GlassFish Server and provides information about deployment
descriptors.
Application Development Explains how to create and implement Java Platform, Enterprise
Guide Edition (Java EE platform) applications that are intended to run
on the GlassFish Server. These applications follow the open Java
standards model for Java EE components and application
programmer interfaces (APIs). This guide provides information
about developer tools, security, and debugging.
Embedded Server Guide Explains how to run applications in embedded GlassFish Server
and to develop applications in which GlassFish Server is
embedded.
High Availability Explains how to configure GlassFish Server to provide higher
Administration Guide availability and scalability through failover and load balancing.
Performance Tuning Guide Explains how to optimize the performance of GlassFish Server.
Troubleshooting Guide Describes common problems that you might encounter when
using GlassFish Server and explains how to solve them.
Error Message Reference Describes error messages that you might encounter when using
GlassFish Server.
Reference Manual Provides reference information in man page format for GlassFish
Server administration commands, utility commands, and related
concepts.
Message Queue Release Describes new features, compatibility issues, and existing bugs for
Notes Open Message Queue.
Message Queue Technical Provides an introduction to the technology, concepts, architecture,
Overview capabilities, and features of the Message Queue messaging
service.
Message Queue Explains how to set up and manage a Message Queue messaging
Administration Guide system.
xvi
Book Title Description
Message Queue Developer's Describes the application programming interface in Message
Guide for JMX Clients Queue for programmatically configuring and monitoring Message
Queue resources in conformance with the Java Management
Extensions (JMX).
Message Queue Developer's Provides information about concepts and procedures for
Guide for Java Clients developing Java messaging applications (Java clients) that work
with GlassFish Server.
Message Queue Developer's Provides programming and reference information for developers
Guide for C Clients working with Message Queue who want to use the C language
binding to the Message Queue messaging service to send, receive,
and process Message Queue messages.
Related Documentation
The following tutorials explain how to develop Java EE applications:
■ Your First Cup: An Introduction to the Java EE Platform
(http://docs.oracle.com/javaee/7/firstcup/doc/). For beginning Java
EE programmers, this short tutorial explains the entire process for developing a
simple enterprise application. The sample application is a web application that
consists of a component that is based on the Enterprise JavaBeans specification, a
JAX-RS web service, and a JavaServer Faces component for the web front end.
■ The Java EE 7 Tutorial
(http://docs.oracle.com/javaee/7/tutorial/doc/). This
comprehensive tutorial explains how to use Java EE 7 platform technologies and
APIs to develop Java EE applications.
Javadoc tool reference documentation for packages that are provided with GlassFish
Server is available as follows.
■ The API specification for version 7 of Java EE is located at
http://docs.oracle.com/javaee/7/api/.
■ The API specification for GlassFish Server 4.0, including Java EE 7 platform
packages and nonplatform packages that are specific to the GlassFish Server
product, is located at http://glassfish.java.net/nonav/docs/v3/api/.
Additionally, the Java EE Specifications
(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.ht
ml).
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 from the Java EE Samples
project page (http://glassfish-samples.java.net/).
xvii
Typographic Conventions
The following table describes the typographic changes that are used in this book.
Symbol Conventions
The following table explains symbols that might be used in this book.
xviii
Placeholder Description Default Value
as-install-parent Represents the parent of the base Installations on the Oracle Solaris operating system, Linux
installation directory for GlassFish operating system, and Mac operating system:
Server.
user's-home-directory/glassfish3
Installations on the Windows operating system:
SystemDrive:\glassfish3
domain-root-dir Represents the directory in which a as-install/domains/
domain is created by default.
domain-dir Represents the directory in which a domain-root-dir/domain-name
domain's configuration is stored.
In configuration files, domain-dir is
represented as follows:
${com.sun.aas.instanceRoot}
instance-dir Represents the directory for a server domain-dir/instance-name
instance.
Documentation Accessibility
For information about Oracle's commitment to accessibility, visit the Oracle
Accessibility Program website at
http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc.
xix
xx
Part I
Part I Development Tasks and Tools
1
1Setting Up a Development Environment
■ Locate utility classes and libraries so they can be accessed by the proper class
loaders. For more information, see Using the Common Class Loader.
■ Set up debugging. For more information, see Debugging Applications.
■ Configure the Virtual Machine for the Java platform (JVM software). For more
information, see "Administering the Virtual Machine for the Java Platform" in
GlassFish Server Open Source Edition Administration Guide.
Development Tools
The following general tools are provided with the GlassFish Server:
■ The asadmin Command
■ The Administration Console
The following development tools are provided with the GlassFish Server or
downloadable from Oracle:
■ The Migration Tool
■ The NetBeans IDE
The following third-party tools might also be useful:
■ The Eclipse IDE
■ Debugging Tools
■ Profiling Tools
1-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Sample Applications
Debugging Tools
You can use several debugging tools with the GlassFish Server. For more information,
see Debugging Applications.
Profiling Tools
You can use several profilers with the GlassFish Server. For more information, see
Profiling Tools.
Sample Applications
Sample applications that you can examine and deploy to the GlassFish Server are
available. If you installed the GlassFish Server as part of installing the Java EE 7 SDK
bundle from Java EE 7 Downloads
(http://www.oracle.com/technetwork/java/javaee/downloads/index.h
tml), the samples may already be installed. You can download these samples
separately from the Code Samples
(http://www.oracle.com/technetwork/java/javaee/documentation/ind
ex.html) page if you installed the GlassFish Server without them initially.
Most GlassFish Server samples have the following directory structure:
■ The docs directory contains instructions for how to use the sample.
■ The build.xml file defines Ant targets for 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 few exceptions, sample applications follow the standard directory structure
described here:
http://java.sun.com/blueprints/code/projectconventions.html.
The samples-install-dir/bp-project/main.xml file defines 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 file imports
main.xml.
In addition to the Java EE 7 sample applications, samples are also available at
GlassFish Samples (https://glassfish-samples.dev.java.net/) and at
as-install/samples/.
1-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
2
2Class Loaders
Understanding Oracle GlassFish Server class loaders can help you determine where to
place supporting JAR and resource files for your modules and applications. For
general information about J2SE class loaders, see Understanding Network Class
Loaders
(http://java.sun.com/developer/technicalArticles/Networking/clas
sloaders/).
In a JVM implementation, the class loaders dynamically load a specific Java class file
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:
■ The Class Loader Hierarchy
■ Delegation
■ Using the Java Optional Package Mechanism
■ Using the Endorsed Standards Override Mechanism
■ Class Loader Universes
■ Application-Specific Class Loading
■ Circumventing Class Loader Isolation
Note: The Web Profile of the GlassFish Server supports the EJB 3.1
Lite specification, which allows enterprise beans within web
applications, among other features. The full GlassFish Server
supports the entire EJB 3.1 specification. For details, see JSR 318
(http://jcp.org/en/jsr/detail?id=318).
For information about class loader debugging, see Class Loader Debugging.
Delegation
Note that the class loader hierarchy is not a Java inheritance hierarchy, but a delegation
hierarchy. In the delegation design, a class loader delegates class loading to its parent
before attempting to load a class itself. If the parent class loader cannot load a class, the
class loader attempts to load the class itself. In effect, a class loader is responsible for
loading only the classes not available to the parent. Classes loaded by a class loader
higher in the hierarchy cannot refer to classes available lower in the hierarchy.
The Java Servlet specification recommends that a web module's class loader look in the
local class loader before delegating to its parent. You can make this class loader follow
the delegation inversion model in the Servlet specification by setting
delegate="false" in the class-loader element of the glassfish-web.xml file. It is
safe to do this only for a web module that does not interact with any other modules.
For details, see "class-loader" in GlassFish Server Open Source Edition Application
Deployment Guide.
The default value is delegate="true", which causes a web module's class loader to
delegate in the same manner as the other class loaders. You must use delegate="true"
2-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Class Loader Universes
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 the GlassFish Server Open Source
Edition 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 from overriding core Java runtime classes or changing the API versions of
specifications that are part of the Java EE platform.
You can update a library JAR file using dynamic reloading or by restarting (disabling
and re-enabling) a module or application. To add or remove library JAR files, you can
redeploy the module or application.
Application libraries are included in the Applib class loader. Paths to libraries can be
relative or absolute. A relative 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 specified by absolute paths
are not guaranteed to be synchronized.
If multiple applications or modules refer to the same libraries, classes in those libraries
are automatically shared. This can reduce the memory footprint and allow sharing of
static information. However, applications or modules using application-specific
libraries are not portable. Other ways to make libraries available are described in
Circumventing Class Loader Isolation.
One library cannot reference classes from another library.
For general information about deployment, including dynamic reloading, see the
GlassFish Server Open Source Edition Application Deployment Guide.
2-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Circumventing Class Loader Isolation
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 file. For more information, see Changing
Permissions for an Application.
accessible to all applications or modules deployed on servers that share the same
configuration.
Each filepath is relative to the directory or JAR file containing the MANIFEST.MF
file. For details, see the Java EE specification.
■ For a calling web component, add the client JAR file under the WEB-INF/lib
directory.
3. If you need to package the client JAR with both the EJB and web components, set
delegate="true" in the class-loader element of the glassfish-web.xml file.
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 JAR file with the calling EJB
component is sufficient. You do not need to package the client JAR file with both
the EJB and web components unless the web component is directly calling the EJB
component in the dependent application.
4. Deploy the calling application.
The calling EJB or web component must specify in its glassfish-ejb-jar.xml or
glassfish-web.xml file 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.
You do not need to restart the server.
2-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
3
Debugging Applications
3
This chapter gives guidelines for debugging applications in the Oracle GlassFish
Server.
The following topics are addressed here:
■ Enabling Debugging
■ JPDA Options
■ Generating a Stack Trace for Debugging
■ Application Client Debugging
■ Open Message Queue Debugging
■ Enabling Verbose Mode
■ Class Loader Debugging
■ GlassFish Server Logging
■ Profiling Tools
Enabling Debugging
When you enable debugging, you enable both local and remote debugging. To start
the server in debug mode, use the --debug option as follows:
asadmin start-domain --debug [domain-name]
You can then attach to the server from the Java Debugger (jdb) at its default Java
Platform Debugger Architecture (JPDA) port, which is 9009. For example, for UNIX
systems:
jdb -attach 9009
For Windows:
jdb -connect com.sun.jdi.SocketAttach:port=9009
For more information about the jdb debugger, see the following links:
■ Java Platform Debugger Architecture - The Java Debugger:
http://java.sun.com/javase/technologies/core/toolsapis/jpda/
■ Java Platform Debugger Architecture - Connecting with JDB:
http://java.sun.com/javase/technologies/core/toolsapis/jpda/
GlassFish Server debugging is based on the JPDA. For more information, see JPDA
Options.
You can attach to the GlassFish Server using any JPDA compliant debugger, including
that of NetBeans (http://www.netbeans.org), Java Studio Enterprise, JBuilder,
Eclipse, and so on.
You can enable debugging even when the GlassFish Server is started without the
--debug option. This is useful if you start the GlassFish Server from the Windows Start
Menu, or if you want to make sure that debugging is always turned on.
See Also
For details, click the Help button in the Administration Console from the JVM Settings
page.
JPDA Options
The default JPDA options in GlassFish Server are as follows:
-Xdebug -agentlib:transport=dt_socket,server=y,suspend=n,address=9009
3-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Class Loader Debugging
For debugging an application client, you should set suspend to y so you can connect
the debugger to the client before any code has actually executed. Otherwise, the client
may start running and execute past the point you want to examine.
You should use different ports for the server and client if you are debugging both
concurrently. For details about setting the port, see JPDA Options.
You can also include JVM options in the appclient script directly. For information
about the appclient script, see the GlassFish Server Open Source Edition Reference
Manual.
When the server is in verbose mode, messages are logged to the console or terminal
window in addition to the log file. In addition, pressing Ctrl-C stops the server and
pressing Ctrl-\ (on UNIX platforms) or Ctrl-Break (on Windows platforms) prints a
thread dump. On UNIX platforms, you can also print a thread dump using the jstack
command (see
http://download.oracle.com/javase/6/docs/technotes/tools/share/j
stack.html) or the command kill -QUIT process_id.
To send the JVM messages to a special JVM log file instead of stdout, use the
following asadmin create-jvm-options commands:
Note: These -XX options are specific to the OpenJDK (or Hotspot)
JVM and do not work with the JRockit JVM.
Profiling Tools
You can use a profiler to perform remote profiling on the GlassFish Server to discover
bottlenecks in server-side performance. This section describes how to configure
profilers for use with GlassFish Server.
The following topics are addressed here:
■ The NetBeans Profiler
■ The HPROF Profiler
■ The JProbe Profiler
Information about comprehensive monitoring and management support in the Java 2
Platform, Standard Edition ( J2SE platform) is available at
http://download.oracle.com/javase/6/docs/technotes/guides/manage
ment/index.html.
3-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Profiling Tools
http://java.sun.com/developer/technicalArticles/Programming/HPRO
F.html.
After HPROF is enabled using the following instructions, its libraries are loaded into
the server process.
Note: Do not use help in the JVM Option field. 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.
When the server starts up with this configuration, you can attach the profiler.
3. Set the following environment variable:
JPROBE_ARGS_0=-jp_input=JPL-file-path
3-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Profiling Tools
Classpath - as-install/lib/appserv-rt.jar
Source File Path - source-code-dir (in case you want to get the line level details)
Server class arguments - (optional)
Main Package - com.sun.enterprise.server
You must also set VM, Attach, and Coverage tabs appropriately. For further
details, see the JProbe documentation. After you have created the JPL file, use
this an input to JPROBE_ARGS_0.
3-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Part II
Part II Developing Applications and Application
Components
4
Securing Applications
4
This chapter describes how to write secure Java EE applications, which contain
components that perform user authentication and access authorization for the business
logic of Java EE components.
For information about administrative security for the Oracle GlassFish Server, see the
GlassFish Server Open Source Edition Security Guide.
For general information about Java EE security, see "Security" in The Java EE 7 Tutorial.
The following topics are addressed here:
■ Security Goals
■ GlassFish Server Specific Security Features
■ Container Security
■ Roles, Principals, and Principal to Role Mapping
■ Realm Configuration
■ JACC Support
■ Pluggable Audit Module Support
■ The server.policy File
■ Configuring Message Security for Web Services
■ Programmatic Login
■ User Authentication for Single Sign-on
■ Adding Authentication Mechanisms to the Servlet Container
Note: The Web Profile of the GlassFish Server supports the EJB 3.1
Lite specification, which allows enterprise beans within web
applications, among other features. The full GlassFish Server
supports the entire EJB 3.1 specification. For details, see JSR 318
(http://jcp.org/en/jsr/detail?id=318).
Security Goals
In an enterprise computing environment, there are many security risks. The goal of the
GlassFish Server is to provide highly secure, interoperable, and distributed component
computing based on the Java EE security model. Security goals include:
■ 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 web services message security.
■ Security support for application clients.
■ Support for several underlying authentication realms, such as simple file and
Lightweight Directory Access Protocol (LDAP). Certificate authentication is also
supported for Secure Socket Layer (SSL) client authentication. For Solaris, OS
platform authentication is supported in addition to these.
■ Support for declarative security through GlassFish Server specific XML-based role
mapping.
■ Support for Java Authorization Contract for Containers (JACC) pluggable
authorization as included in the Java EE specification and defined by Java
Specification 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 specification and defined by JSR 196
(http://www.jcp.org/en/jsr/detail?id=196).
■ Support for Web Services Interoperability Technologies (WSIT) as described in
Metro Users Guide (https://metro.dev.java.net/guide/).
Container Security
The component containers are responsible for providing Java EE application security.
The container provides two security forms:
■ Declarative Security
■ Programmatic Security
Annotations (also called metadata) enable a declarative style of programming, and so
encompass both the declarative and programmatic security concepts. Users can specify
information about security within a class file using annotations. When the application
is deployed, this information can either be used by or overridden by the application or
module deployment descriptor.
Declarative Security
Declarative security means that the security mechanism for an application is declared
and handled externally to the application. Deployment descriptors describe the Java
EE application's security structure, including security roles, access control, and
authentication requirements.
4-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Container Security
The GlassFish Server supports the deployment descriptors specified by Java EE and
has additional security elements included in its own deployment descriptors.
Declarative security is the application deployer's responsibility. For more information
about GlassFish Server deployment descriptors, see the GlassFish Server Open Source
Edition Application Deployment Guide.
There are two levels of declarative security, as follows:
■ Application Level Security
■ Component Level Security
Programmatic Security
Programmatic security involves an EJB component or servlet using method calls to the
security API, as specified by the Java EE security model, to make business logic
decisions based on the caller or remote user's security role. Programmatic security
should only be used when declarative security alone is insufficient to meet the
application's security model.
The Java EE specification defines programmatic security as consisting of two methods
of the EJB EJBContext interface and two methods of the servlet HttpServletRequest
interface. The GlassFish Server supports these interfaces as specified in the
specification.
For more information on programmatic security, see the following:
■ The Java EE Specification
■ Programmatic Login
A role can be mapped to either specific principals or to groups (or both). The principal
or group names used must be valid principals or groups in the realm for the
application or module. Note that the role-name in this example must match the
@DeclareRoles annotations or the role-name in the security-role element of the
corresponding web.xml file.
You can also specify a custom principal implementation class. This provides more
flexibility in how principals can be assigned to roles. A user's JAAS login module now
can authenticate its custom principal, and the authenticated custom principal can
further participate in the GlassFish Server authorization process. For example:
<security-role-mapping>
<role-name>administrator</role-name>
<principal-name class-name="CustomPrincipalImplClass">
dsmith
</principal-name>
</security-role-mapping>
You can specify a default principal and a default principal to role mapping, each of
which applies to the entire GlassFish Server instance. The default principal to role
mapping maps group principals to the same named roles. Web modules that omit the
run-as element in web.xml use the default principal. Applications and modules that
omit the security-role-mapping element use the default principal to role mapping.
These defaults are part of the Security Service, which you can access in the following
ways:
4-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Realm Configuration
■ In the Administration Console, select the Security component under the relevant
configuration. For details, click the Help button in the Administration Console.
■ Use the asadmin set command. For details, see the GlassFish Server Open Source
Edition 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
Realm Configuration
The following topics are addressed here:
■ Supported Realms
■ How to Configure a Realm
■ How to Set a Realm for an Application or Module
■ Creating a Custom Realm
Supported Realms
The following realms are supported in the current release of the GlassFish Server:
■ file - Stores user information in a file. This is the default realm when you first
install the GlassFish Server.
■ ldap - Stores user information in an LDAP directory.
■ jdbc - Stores user information in a database.
In the JDBC realm, the server gets user credentials from a database. The GlassFish
Server uses the database information and the enabled JDBC realm option in the
configuration file. For digest authentication, a JDBC realm should be created with
jdbcDigestRealm as the JAAS context.
■ certificate - Sets up the user identity in the GlassFish Server security context,
and populates it with user data obtained from cryptographically verified client
certificates.
■ solaris - Allows authentication using Solaris username+password data. This realm
is only supported on the Solaris operating system, version 9 and above.
For information about configuring realms, see How to Configure a Realm.
For more information about the deployment descriptor files and elements, see
"Elements of the GlassFish Server Deployment Descriptors" in GlassFish Server Open
Source Edition Application Deployment Guide.
4-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Realm Configuration
This method performs the actual authentication. The custom login module must not
implement any of the other methods, such as login, logout, abort, commit, or
initialize. Default implementations are provided in AppservPasswordLoginModule
which hook into the GlassFish Server infrastructure.
The custom login module can access the following protected object fields, which it
inherits from AppservPasswordLoginModule. These contain the user name and
password of the user to be authenticated:
protected String _username;
protected String _password;
This method is invoked during server startup when the realm is initially loaded. The
props argument contains the properties defined for this realm. The realm can do any
initialization it needs in this method. If the method returns without throwing an
exception, the GlassFish Server assumes that the realm is ready to service
authentication requests. If an exception is thrown, the realm is disabled.
public String getAuthType()
This method returns a descriptive string representing the type of authentication done
by this realm.
public abstract Enumeration getGroupNames(String username) throws
InvalidOperationException, NoSuchUserException
This method returns an Enumeration (of String objects) enumerating the groups (if
any) to which the given username belongs in this realm.
Custom realms that manage users must implement the following additional methods:
public abstract boolean supportsUserManagement();
This method refreshes the realm data so that new users and groups are visible.
public abstract void persist() throws BadRealmException;
This method returns the information recorded about a particular named user.
public abstract void addUser(String name, String password, String[] groupList)
throws
BadRealmException, IASSecurityException;
JACC Support
JACC (Java Authorization Contract for Containers) is part of the Java EE specification
and defined by JSR 115 (http://www.jcp.org/en/jsr/detail?id=115). JACC
defines an interface for pluggable authorization providers. Specifically, JACC is used
to plug in the Java policy provider used by the container to perform Java EE caller
access decisions. The Java policy provider performs Java policy decisions during
application execution. This provides third parties with a mechanism to develop and
plug in modules that are responsible for answering authorization decisions during
Java EE application execution. The interfaces and rules used for developing JACC
providers are defined in the JACC 1.0 specification.
The GlassFish Server provides a simple file-based JACC-compliant authorization
engine as a default JACC provider, named default. An alternate provider named
simple is also provided. To configure an alternate provider using the Administration
Console, open the Security component under the relevant configuration, and select the
JACC Providers component. For details, click the Help button in the Administration
Console.
4-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Pluggable Audit Module Support
The preceding method is invoked during server startup when the audit module is
initially loaded. The props argument contains the properties defined 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 realm is
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 realm
for the given user. The success flag 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 flag 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 JSR 115
(http://www.jcp.org/en/jsr/detail?id=115)).
public void ejbInvocation(String user, String ejb, String method, boolean success)
This method is invoked when an EJB container call has been processed by
authorization. The success flag 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)
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 flag 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 flag indicates whether the authorization was granted or
denied.
Default Permissions
Internal server code is granted all permissions. These are covered by the
AllPermission grant blocks to various parts of the server infrastructure code. Do not
modify these entries.
Application permissions are granted in the default grant block. These permissions
apply to all code not part of the internal server code listed previously. The GlassFish
Server does not distinguish between EJB and web module permissions. All code is
granted the minimal set of web component permissions (which is a superset of the EJB
minimal set). Do not modify these entries.
A few permissions above the minimal set are also granted in the default
server.policy file. These are necessary due to various internal dependencies of the
server implementation. Java EE application developers must not rely on these
additional permissions. In some cases, deleting these permissions might be
appropriate. For example, one additional permission is granted specifically for using
connectors. If connectors are not used in a particular domain, you should remove this
permission, because it is not otherwise necessary.
4-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
The server.policy File
System Properties
The following predefined system properties, also called variables, are available for use
in the server.policy file. The system property most frequently used in
server.policy is ${com.sun.aas.instanceRoot}. For more information about system
properties, see the asadmin create-system-properties command in the GlassFish
Server Open Source Edition Reference Manual.
You can add permissions to stub code with the following grant block:
grant codeBase "file:${com.sun.aas.instanceRoot}/generated/-" {
...
}
In general, you should add extra permissions only to the applications or modules that
require them, not to all applications deployed to a domain. For example:
grant codeBase "file:${com.sun.aas.instanceRoot}/applications/MyApp/-" {
...
}
For a module:
grant codeBase "file:${com.sun.aas.instanceRoot}/applications/MyModule/-" {
...
}
4-12 GlassFish Server Open Source Edition 4.0 Application Development Guide
The server.policy File
For more information about the asadmin create-jvm-options command, see the
GlassFish Server Open Source Edition Reference Manual.
You can use the J2SE standard policytool or any text editor to edit the server.policy
file. For more information, see
http://download.oracle.com/javase/tutorial/security/tour2/index.
html.
For detailed information about policy file syntax, see
http://download.oracle.com/javase/6/docs/technotes/guides/securi
ty/PolicyFiles.html.
For information about using system properties in the server.policy file, see
http://download.oracle.com/javase/6/docs/technotes/guides/securi
ty/PolicyFiles.html.
For detailed information about the permissions you can set in the server.policy file,
see
http://download.oracle.com/javase/6/docs/technotes/guides/securi
ty/permissions.html.
The Javadoc for the Permission class is at
http://download.oracle.com/javase/6/docs/api/java/security/Permi
ssion.html.
To disable the security manager, uncheck the Security Manager Enabled box or use the
corresponding asadmin delete-jvm-options command. For more information about
create-jvm-options and delete-jvm-options, see the GlassFish Server Open Source
Edition Reference Manual.
If the security manager is enabled and you are using the Java Persistence API by
calling Persistence.createEMF(), the EclipseLink persistence provider requires that
you set the eclipselink.security.usedoprivileged JVM option to true as follows:
If the security manager is enabled and you are using the Java Persistence API by
injecting or looking up an entity manager or entity manager factory, the EJB container
sets this JVM option for you.
For more information about web services, see Developing Web Services.
For more information about message security, see the following:
■ "Introduction to Security in the Java EE Platform" in The Java EE 7 Tutorial
■ GlassFish Server Open Source Edition Security Guide
■ JSR 196 (http://www.jcp.org/en/jsr/detail?id=196), Java
Authentication Service Provider Interface for Containers
■ The Liberty Alliance Project specifications at
http://www.projectliberty.org/resources/specifications.php/?f
=resources/specifications.php
■ The Oasis Web Services Security (WSS) specification at
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-
message-security-1.0.pdf
■ The Web Services Interoperability Organization (WS-I) Basic Security Profile (BSP)
specification at
http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html
■ The XML and Web Services Security page at http://xwss.java.net/
■ The WSIT page at http://wsit.java.net/
The following topics are addressed here:
■ Message Security Providers
■ Message Security Responsibilities
■ Application-Specific Message Protection
■ Understanding and Running the Sample Application
4-14 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring Message Security for Web Services
For more information about the asadmin set command, see the GlassFish Server
Open Source Edition Reference Manual.
The example described in Understanding and Running the Sample Application uses
the ClientProvider and ServerProvider providers, which are enabled when the Ant
targets are run. You don't need to enable these on the GlassFish Server prior to running
the example.
If you install the OpenSSO, you have these additional provider choices:
■ AMClientProvider and AMServerProvider - These providers secure web services
and Simple Object Access Protocol (SOAP) messages using either WS-I BSP or
Liberty ID-WSF tokens. These providers are used automatically if they are
configured as the default providers. If you wish to override any provider settings,
you can configure these providers in message-security-binding elements in the
glassfish-web.xml, glassfish-ejb-jar.xml, and
glassfish-application-client.xml deployment descriptor files.
■ AMHttpProvider - This provider handles the initial end user authentication for
securing web services using Liberty ID-WSF tokens and redirects requests to the
OpenSSO for 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 file.
Liberty specifications can be viewed at
http://www.projectliberty.org/resources/specifications.php/?f=re
sources/specifications.php. The WS-I BSP specification can be viewed at
http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html.
For more information about the GlassFish Server deployment descriptor files, see the
GlassFish Server Open Source Edition Application Deployment Guide.
For information about configuring these providers in the GlassFish Server, see the
GlassFish Server Open Source Edition Security Guide. For additional information about
overriding provider settings, see Application-Specific Message Protection.
You can create new message 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 configuration, and select the Message
Security component. For details, click the Help button in the Administration
Console.
■ You can use the asadmin create-message-security-provider command to create
a message security provider. For details, see the GlassFish Server Open Source
Edition Reference Manual.
In addition, you can set a few optional provider properties using the asadmin set
command. For example:
asadmin set
server-config.security-service.message-security-config.provider-config.property.de
bug=true
4-16 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring Message Security for Web Services
To Enable Message Protection for All Methods Using Digital Signature Follow this procedure.
1. In a text editor, open the application's glassfish-ejb-jar.xml file.
For the xms example, this file is located in the directory app-dir/xms-ejb/src/conf,
where app-dir is defined in To Set Up the Sample Application.
2. Modify the glassfish-ejb-jar.xml file by adding the
message-security-binding element as shown:
<glassfish-ejb-jar>
<enterprise-beans>
<unique-id>1</unique-id>
<ejb>
<ejb-name>HelloWorld</ejb-name>
<jndi-name>HelloWorld</jndi-name>
<webservice-endpoint>
4-18 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring Message Security for Web Services
<port-component-name>HelloIF</port-component-name>
<endpoint-address-uri>service/HelloWorld</endpoint-address-uri>
<message-security-binding auth-layer="SOAP">
<message-security>
<request-protection auth-source="content" />
<response-protection auth-source="content"/>
</message-security>
</message-security-binding>
</webservice-endpoint>
</ejb>
</enterprise-beans>
</glassfish-ejb-jar>
3. Compile, deploy, and run the application as described in To Run the Sample
Application.
To Enable Message Protection for a Particular Method or Set of Methods Using Digital Signature
Follow this procedure.
1. In a text editor, open the application's glassfish-ejb-jar.xml file.
For the xms example, this file is located in the directory app-dir/xms-ejb/src/conf,
where app-dir is defined in To Set Up the Sample Application.
2. Modify the glassfish-ejb-jar.xml file by adding the
message-security-binding element as shown:
<glassfish-ejb-jar>
<enterprise-beans>
<unique-id>1</unique-id>
<ejb>
<ejb-name>HelloWorld</ejb-name>
<jndi-name>HelloWorld</jndi-name>
<webservice-endpoint>
<port-component-name>HelloIF</port-component-name>
<endpoint-address-uri>service/HelloWorld</endpoint-address-uri>
<message-security-binding auth-layer="SOAP">
<message-security>
<message>
<java-method>
<method-name>ejbCreate</method-name>
</java-method>
</message>
<message>
<java-method>
<method-name>sayHello</method-name>
</java-method>
</message>
<request-protection auth-source="content" />
<response-protection auth-source="content"/>
</message-security>
</message-security-binding>
</webservice-endpoint>
</ejb>
</enterprise-beans>
</glassfish-ejb-jar>
3. Compile, deploy, and run the application as described in To Run the Sample
Application.
4-20 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring Message Security for Web Services
After you follow these steps, the sample application is located in the directory
as-install/j2ee14-samples/samples/webservices/security/ejb/apps/xms/ or in a
directory of your choice. For easy reference throughout the rest of this section, this
directory is referred to as simply app-dir.
1. Go to the J2EE 1.4 download URL
(http://www.oracle.com/technetwork/java/javaee/download-14177
1.html) in your browser.
2. Click on the Download button for the Samples Bundle.
3. Click on Accept License Agreement.
4. Click on the J2EE SDK Samples link.
5. Choose a location for the j2eesdk-1_4_03-samples.zip file.
Saving the file to as-install is recommended.
6. Unzip the file.
Unzipping to the as-install/j2ee14-samples directory is recommended. For
example, you can use the following command.
unzip j2eesdk-1_4_03-samples.zip -d j2ee14-samples
ant deploy
c. To run samples:
ant run
If the sample has compiled and deployed properly, you see the following response
on your screen after the application has run:
run:[echo] Running the xms program:[exec] Established message level
security : Hello Duke!
5. To undeploy the sample, run the following Ant target:
ant undeploy
All of the web services security examples use the same web service name
(HelloWorld) and web service ports. These examples show only the differences
necessary for protecting web services using various mechanisms. Make sure to
undeploy an application when you have completed running it. If you do not, you
receive an Already in Use error and deployment failures when you try to deploy
another web services example application.
Programmatic Login
Programmatic login allows a deployed Java EE application or module to invoke a
login method. If the login is successful, a SecurityContext is established as if the
client had authenticated using any of the conventional Java EE mechanisms.
Programmatic login is supported for servlet and EJB components on the server side,
and for stand-alone or application clients on the client side. Programmatic login is
useful for an application having special needs that cannot be accommodated by any of
the Java EE standard authentication mechanisms.
4-22 GlassFish Server Open Source Edition 4.0 Application Development Guide
Programmatic Login
The login methods for EJB components have the following signatures:
public java.lang.Boolean login(String user, String password)
The logout methods for EJB components have the following signatures:
public java.lang.Boolean logout()
All of these logout methods return true if logout succeeded, false if logout failed.
If the errors flag is set to true, any exceptions encountered during the logout are
propagated to the caller. If set to false, exceptions are thrown.
4-24 GlassFish Server Open Source Edition 4.0 Application Development Guide
Adding Authentication Mechanisms to the Servlet Container
For more information about the asadmin set command, see the GlassFish Server Open
Source Edition Reference Manual.
4-26 GlassFish Server Open Source Edition 4.0 Application Development Guide
Adding Authentication Mechanisms to the Servlet Container
import java.io.IOException;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.callback.PasswordValidationCallback;
import javax.security.auth.message.module.ServerAuthModule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.util.Base64;
4-28 GlassFish Server Open Source Edition 4.0 Application Development Guide
Adding Authentication Mechanisms to the Servlet Container
if (options.containsKey(GROUP_PROPERTY_NAME)) {
defaultGroup = new String[]{(String)
options.get(GROUP_PROPERTY_NAME)};
}
}
}
String username =
processAuthorizationToken(msgInfo, client);
if (username ==
null && requestPolicy.isMandatory()) {
return sendAuthenticateChallenge(msgInfo);
}
setAuthenticationResult(
username, client, msgInfo);
return AuthStatus.SUCCESS;
} catch (Exception e) {
AuthException ae = new AuthException();
ae.initCause(e);
throw ae;
}
}
HttpServletRequest request =
(HttpServletRequest)
msgInfo.getRequestMessage();
String token =
request.getHeader(AUTHORIZATION_HEADER);
token = token.substring(6).trim();
if (pVC.getResult()) {
return username;
}
}
return null;
}
HttpServletRequest request =
(HttpServletRequest)
msgInfo.getRequestMessage();
realm = request.getServerName();
}
HttpServletResponse response =
(HttpServletResponse)
msgInfo.getResponseMessage();
4-30 GlassFish Server Open Source Edition 4.0 Application Development Guide
Adding Authentication Mechanisms to the Servlet Container
Note that the initialize method looks for the group.name and realm.name
properties. The group.name property configures the default group assigned as a result
of any successful authentication. The realm.name property defines the realm value
sent back to the browser in the WWW-Authenticate challenge.
4-32 GlassFish Server Open Source Edition 4.0 Application Development Guide
5
5Developing Web Services
This chapter describes Oracle GlassFish Server support for web services. The following
topics are addressed here:
■ Creating Portable Web Service Artifacts
■ Deploying a Web Service
■ The Web Service URI, WSDL File, and Test Page
■ The Databinding Provider
■ GlassFish Java EE Service Engine
Note: If you installed the Web Profile, web services are not
supported unless the optional Metro Web Services Stack add-on
component is downloaded from the Update Tool. Without the
Metro add-on component, a servlet or EJB component cannot be a
web service endpoint, and the glassfish-web.xml and
glassfish-ejb-jar.xml elements related to web services are
ignored. For information about the Update Tool, see "Update Tool"
in GlassFish Server Open Source Edition Administration Guide.
In addition, the as-install/modules/webservices-osgi.jar and
as-install/modules/endorsed/webservices-api-osgi.jar files must
be in the classpath of your web services application. IDEs such as
NetBeans and Eclipse do this automatically.
"Web Services" in The Java EE 7 Tutorial shows how to deploy simple web services to
GlassFish Server.
For additional information about JAXB (Java Architecture for XML Binding), see Java
Specification Request (JSR) 222 and The Databinding Provider.
For additional information about JAX-WS (Java API for XML-Based Web Services), see
Java Specification Request (JSR) 224 and Java Specification Request (JSR) 109.
For information about web services security, see Configuring Message Security for
Web Services.
The Fast Infoset standard specifies a binary format based on the XML Information Set.
This format is an efficient alternative to XML. For information about using Fast Infoset,
see the following links:
■ Java Web Services Developer Pack 1.6 Release Notes
(http://download.oracle.com/docs/cd/E17802_
01/webservices/webservices/docs/1.6/ReleaseNotes.html)
You can view the WSDL file of the deployed service in a browser by adding ?WSDL to
the end of the URI. For example:
http://localhost:8080/my-ws/simple?WSDL
For debugging, you can run a test page for the deployed service in a browser by
adding ?Tester to the end of the URL. For example:
5-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
The Databinding Provider
http://localhost:8080/my-ws/simple?Tester
You can also test a service using the Administration Console. Open the Web Services
component, select the web service in the listing on the General tab, and select Test. For
details, click the Help button in the Administration Console.
Note: The test page works only for WS-I compliant web services.
This means that the tester servlet does not work for services with
WSDL files that use RPC/encoded binding.
Generation of the test page is enabled by default. You can disable the test page for a
web service by setting the value of the debugging-enabled element in the
glassfish-web.xml and glassfish-ejb-jar.xml deployment descriptor to false. For
more information, see the GlassFish Server Open Source Edition Application Deployment
Guide.
com.sun.xml.ws.db.glassfish.JAXBRIContextFactory
Specifies the JAXB reference implementation. This is the default.
com.sun.xml.ws.db.toplink.JAXBContextFactory
Specifies Eclipselink MOXy JAXB binding.
For example:
asadmin create-jvm-options
-Dcom.sun.xml.ws.spi.db.BindingContextFactory=com.sun.xml.ws.db.toplink.JAXBContex
tFactory
org.jvnet.ws.databinding.DatabindingModeFeature.GLASSFISH_JAXB
Specifies the JAXB reference implementation. This is the default.
com.sun.xml.ws.db.toplink.JAXBContextFactory.ECLIPSELINK_JAXB
Specifies Eclipselink MOXy JAXB binding.
For example:
import javax.xml.ws.WebServiceFeature;
import org.jvnet.ws.databinding.DatabindingModeFeature;
import com.sun.xml.ws.db.toplink.JAXBContextFactory;
...
WebServiceFeature[] features = {new
DatabindingModeFeature(JAXBContextFactory.ECLIPSELINK_JAXB)};
...
■ Set the databinding attribute of the endpoint element in the sun-jaxws.xml file.
Allowed values are glassfish.jaxb or eclipselink.jaxb. For example:
<endpoint
name='hello'
implementation='hello.HelloImpl'
url-pattern='/hello'
databinding='eclipselink.jaxb'/>
The EclipseLink JAXB compiler is not included but can be used with GlassFish Server.
Download the EclipseLink zip file at
http://www.eclipse.org/eclipselink/downloads/ and unzip it. The
compiler files are located here:
bin/jaxb-compiler.cmd
bin/jaxb-compiler.sh
5-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
GlassFish Java EE Service Engine
The Java EE Service Engine enables the endpoints described in the provides section of
the jbi.xml file in the JBI runtime. Similarly, the Java EE Service Engine routes
invocations of the endpoints described in the consumes section from the Java EE web
service consumer to the JBI runtime.
5-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
6
Configuring the Java Persistence Provider
6
This chapter describes Oracle TopLink, the default persistence provider in GlassFish
Server Open Source Edition, and introduces how to use it. This chapter also tells how
to set the default persistence provider in GlassFish Server and how to use
persistence-related features specific to GlassFish Server such as automatic schema
generation.
The following topics are addressed here:
■ Overview of Oracle TopLink
■ Using Oracle TopLink in GlassFish Server
■ Specifying the Database for an Application
■ Specifying the Persistence Provider for an Application
■ Primary Key Generation Defaults
■ Automatic Schema Generation
■ Restrictions and Optimizations
■ Java Architecture for XML Binding (JAXB) 2.0. The EclipseLink JAXB
implementation, plus EclipseLink extensions, is called MOXy. The
org.eclipse.persistence.moxy.jar file is bundled with GlassFish Server. For
more information about MOXy support in GlassFish Server, see The Databinding
Provider.
For the JAXB 2.0 specification, see Java Specification Request (JSR) 222.
■ EclipseLink utilities are not included but can be used with GlassFish Server.
Download the EclipseLink zip file at
http://www.eclipse.org/eclipselink/downloads/ and unzip it. The
utility files are located here:
bin/jaxb-compiler.cmd
bin/jaxb-compiler.sh
Note: You must have a license for Oracle Coherence to be able to use
TopLink Grid.
6-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Specifying the Database for an Application
If you are using the Java Persistence API by calling Persistence.createEMF(), see
Specifying the Persistence Provider for an Application.
4. If the security manager is enabled and you are using the Java Persistence API by
calling Persistence.createEMF(), see Enabling and Disabling the Security
Manager.
5. Deploy the application. See the GlassFish Server Open Source Edition Application
Deployment Guide.
6. Run the application. See "Application Client Launch" and "To Launch an
Application" in Administration Console online help.
7. Monitor the application. See "Administering the Monitoring Service" in GlassFish
Server Open Source Edition Administration Guide.
TimesTen
Attunity
HSQL
SQLAnyWhere
DBase
DB2Mainframe
Cloudscape
PointBase
For a list of the JDBC drivers currently supported by the GlassFish Server, see the
GlassFish Server Open Source Edition Release Notes. For configurations of supported and
other drivers, see "Configuration Specifics for JDBC Drivers" in GlassFish Server Open
Source Edition Administration Guide.
6-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Primary Key Generation Defaults
1. Install the provider. Copy the provider JAR files to the domain-dir/lib directory,
and restart the GlassFish Server. For more information about the domain-dir/lib
directory, see Using the Common Class Loader. The new persistence provider is
now available to all modules and applications deployed on servers that share the
same configuration.
However, the default provider remains the same, Oracle TopLink or EclipseLink.
2. In your persistence unit, specify the provider and any properties the provider
requires in the persistence.xml file. For example:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name ="em3">
<provider>com.company22.persistence.PersistenceProviderImpl</provider>
<properties>
<property name="company22.database.name" value="MyDB"/>
</properties>
</persistence-unit>
</persistence>
Annotations
The following annotations are used in automatic schema generation:
@AssociationOverride, @AssociationOverrides, @AttributeOverride,
@AttributeOverrides, @Column, @DiscriminatorColumn, @DiscriminatorValue,
@Embedded, @EmbeddedId, @GeneratedValue, @Id, @IdClass, @JoinColumn,
@JoinColumns, @JoinTable, @Lob, @ManyToMany, @ManyToOne, @OneToMany, @OneToOne,
@PrimaryKeyJoinColumn, @PrimaryKeyJoinColumns, @SecondaryTable,
@SecondaryTables, @SequenceGenerator, @Table, @TableGenerator,
@UniqueConstraint, and @Version. For information about these annotations, see the
Java Persistence Specification.
For @Column annotations, the insertable and updatable elements are not used in
automatic schema generation.
For @OneToMany and @ManyToOne annotations, no ForeignKeyConstraint is created in
the resulting DDL files.
Generation Options
Schema generation properties or asadmin command line options can control automatic
schema generation by the following:
6-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Automatic Schema Generation
Note: Before using these options, make sure you have a properly
configured database. See Specifying the Database for an
Application.
Table 6–1 The asadmin deploy and asadmin deploydir Generation Options
Option Default Description
--createtables none If true, causes database tables to be created for entities that need them. No
unique constraints are created. If false, does not create tables. If not
specified, the value of the eclipselink.ddl-generation property in
persistence.xml is used.
--dropandcreatetables none If true, and if tables were automatically created when this application was
last deployed, tables from the earlier deployment are dropped and fresh
ones are created.
If true, and if tables were not automatically created when this application
was last deployed, no attempt is made to drop any tables. If tables with the
same names as those that would have been automatically created are
found, the deployment proceeds, but a warning is thrown to indicate that
tables could not be created.
If false, the eclipselink.ddl-generation property setting in
persistence.xml is overridden.
The following options of the asadmin undeploy command control the automatic
removal of database tables at undeployment.
For more information about the asadmin deploy, asadmin deploydir, and asadmin
undeploy commands, see the GlassFish Server Open Source Edition Reference Manual.
When asadmin deployment options and persistence.xml options are both specified,
the asadmin deployment options take precedence.
6-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Restrictions and Optimizations
Using BLOB or CLOB Types with the Inet Oraxo JDBC Driver
To use BLOB or CLOB data types larger than 4 KB for persistence using the Inet Oraxo
JDBC Driver for Oracle Databases, you must set the database's streamstolob property
value to true.
Unique Constraints
If column names are not explicitly specified on a field, unique constraints and foreign
key mappings must be specified using uppercase references. For example:
@Table(name="Department", uniqueConstraints={ @UniqueConstraint ( columnNames= {
"DEPTNAME" } ) } )
The other way to handle this is by specifying explicit column names for each field with
the required case. For example:
@Table(name="Department", uniqueConstraints={ @UniqueConstraint ( columnNames= {
"deptName" } ) } )
public class Department{ @Column(name="deptName") private String deptName; }
Otherwise, the ALTER TABLE statement generated by the GlassFish Server uses the
incorrect case, and the creation of the unique constraint fails.
JDBC queries to be uppercase, while PostgreSQL and Sybase require table names to be
uppercase in all JDBC queries.
Use the backslash as an escape character in the class file, but not in the
persistence.xml file.
To avoid this error, make sure the finder method input is less than 255 characters.
6-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
Restrictions and Optimizations
javax.transaction.SystemException: java.sql.SQLException:
Error open transaction is not closed
To resolve this issue, add relaxAutoCommit=true to the JDBC URL. For more
information, see http://forums.mysql.com/read.php?39,31326,31404.
■ MySQL does not allow a DELETE on a row that 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;
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;
This can be done only if the foreign key field is allowed to be null. For more
information, see
http://dev.mysql.com/doc/mysql/en/innodb-foreign-key-constrai
nts.html.
6-12 GlassFish Server Open Source Edition 4.0 Application Development Guide
7
7 Developing Web Applications
This chapter describes how web applications are supported in the Oracle GlassFish
Server.
The following topics are addressed here:
■ Using Servlets
■ Using JavaServer Pages
■ Creating and Managing Sessions
■ Using Comet
■ Advanced Web Application Features
For general information about web applications, see "The Web Tier" in The Java EE 7
Tutorial.
Note: The Web Profile of the GlassFish Server supports the EJB 3.1
Lite specification, which allows enterprise beans within web
applications, among other features. The full GlassFish Server
supports the entire EJB 3.1 specification. For details, see JSR 318
(http://jcp.org/en/jsr/detail?id=318).
Using Servlets
GlassFish Server supports the Java Servlet Specification version 3.0.
To develop servlets, use the Java Servlet API. For information about using the Java
Servlet API, see the documentation at
http://www.oracle.com/technetwork/java/javaee/servlet/index.html
.
The GlassFish Server provides the wscompile and wsdeploy tools to help you
implement a web service endpoint as a servlet. For more information about these tools,
see the GlassFish Server Open Source Edition Reference Manual.
This section describes how to create effective servlets to control application
interactions running on a GlassFish Server, including standard-based servlets. In
addition, this section describes the GlassFish Server features to use to augment the
standards.
The following topics are addressed here:
■ Caching Servlet Results
■ About the Servlet Engine
Caching Features
The GlassFish Server has the following web application response caching capabilities:
■ Caching is configurable based on the servlet name or the URI.
■ When caching is based on the URI, this includes user specified parameters in the
query string. For example, a response from /garden/catalog?category=roses is
different from a response from /garden/catalog?category=lilies. These
responses are stored under different keys in the cache.
■ Cache size, entry timeout, and other caching behaviors are configurable.
■ Entry timeout is measured from the time an entry is created or refreshed. To
override this timeout for an individual cache mapping, specify the cache-mapping
subelement timeout.
7-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Servlets
Caching Example
Here is an example cache element in the glassfish-web.xml file:
<cache max-capacity="8192" timeout="60">
<cache-helper name="myHelper" class-name="MyCacheHelper"/>
<cache-mapping>
<servlet-name>myservlet</servlet-name>
<timeout name="timefield">120</timeout>
<http-method>GET</http-method>
<http-method>POST</http-method>
</cache-mapping>
<cache-mapping>
<url-pattern> /catalog/* </url-pattern>
<!-- cache the best selling category; cache the responses to
-- this resource only when the given parameters exist. Cache
-- only when the catalog parameter has 'lilies' or 'roses'
-- but no other catalog varieties:
-- /orchard/catalog?best&category='lilies'
-- /orchard/catalog?best&category='roses'
-- but not the result of
-- /orchard/catalog?best&category='wild'
-->
<constraint-field name='best' scope='request.parameter'/>
<constraint-field name='category' scope='request.parameter'>
<value> roses </value>
<value> lilies </value>
</constraint-field>
<!-- Specify that a particular field is of given range but the
-- field doesn't need to be present in all the requests -->
<constraint-field name='SKUnum' scope='request.parameter'>
<value match-expr='in-range'> 1000 - 2000 </value>
</constraint-field>
<!-- cache when the category matches with any value other than
-- a specific value -->
<constraint-field name="category" scope="request.parameter>
<value match-expr="equals" cache-on-match-failure="true">
bogus
</value>
</constraint-field>
</cache-mapping>
<cache-mapping>
<servlet-name> InfoServlet </servlet-name>
<cache-helper-ref>myHelper</cache-helper-ref>
</cache-mapping>
</cache>
For more information about the glassfish-web.xml caching settings, see "cache" in
GlassFish Server Open Source Edition Application Deployment Guide.
7-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using JavaServer Pages
Request Handling
When a request is made, the GlassFish Server hands the incoming data to the servlet
engine. The servlet engine processes the request's input data, such as form data,
cookies, session information, and URL name-value pairs, into an HttpServletRequest
request object type.
The servlet engine also creates an HttpServletResponse response object type. The
engine then passes both as parameters to the servlet's service method.
In an HTTP servlet, the default service method routes requests to another method
based on the HTTP transfer method: POST, GET, DELETE, HEAD, OPTIONS, PUT, or TRACE.
For example, HTTP POST requests are sent to the doPost method, HTTP GET requests
are sent to the doGet method, and so on. This enables the servlet to process request
data differently, depending on which transfer method is used. Since the routing takes
place in the service method, you generally do not override service in an HTTP
servlet. Instead, override doGet, doPost, and so on, depending on the request type you
expect.
To perform the tasks to answer a request, override the service method for generic
servlets, and the doGet or doPost methods for HTTP servlets. Very often, this means
accessing EJB components to perform business transactions, then collating the
information in the request object or in a JDBC ResultSet object.
■ JSP Caching
■ Options for Compiling JSP Files
JSP Caching
JSP caching lets you cache tag invocation results within the Java engine. Each can be
cached using different cache criteria. For example, suppose you have invocations to
view stock quotes, weather information, and so on. The stock quote result can be
cached for 10 minutes, the weather report result for 30 minutes, and so on.
The following topics are addressed here:
■ Enabling JSP Caching
■ Caching Scope
■ The cache Tag
■ The flush Tag
For more information about response caching as it pertains to servlets, see Caching
Servlet Results.
For more information about the asadmin set command, see the GlassFish Server Open
Source Edition Reference Manual.
To enable JSP caching for a single web application, follow these steps:
1. Extract the META-INF/jspcachtags.tld file from the
as-install/modules/web-glue.jar file.
2. Create a new JAR file (for example, jspcachtags.jar) containing just the
META-INF/jspcachtags.tld file previously extracted.
3. Bundle this new JAR file in the WEB-INF/lib directory of your web application.
Note: Web applications that use JSP caching without bundling the
tag library are not portable.
7-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using JavaServer Pages
Subsequently, the cache tags are available as <prefix:cache> and <prefix:flush>. For
example, if your prefix is mypfx, the cache tags are available as <mypfx:cache> and
<mypfx:flush>.
Caching Scope
JSP caching is available in three different scopes: request, session, and application.
The default is application. To use a cache in request scope, a web application must
specify the com.sun.appserv.web.taglibs.cache.CacheRequestListener in its
web.xml deployment descriptor, as follows:
<listener>
<listener-class>
com.sun.appserv.web.taglibs.cache.CacheRequestListener
</listener-class>
</listener>
Likewise, for a web application to utilize a cache in session scope, it must specify the
com.sun.appserv.web.taglibs.cache.CacheSessionListener in its web.xml
deployment descriptor, as follows:
<listener>
<listener-class>
com.sun.appserv.web.taglibs.cache.CacheSessionListener
</listener-class>
</listener>
To utilize a cache in application scope, a web application need not specify any
listener. The com.sun.appserv.web.taglibs.cache.CacheContextListener is already
specified in the jspcachtags.tld file.
Attributes of cache The following table describes attributes for the cache tag.
Attributes of flush The following table describes attributes for the flush tag.
7-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Creating and Managing Sessions
Configuring Sessions
The following topics are addressed here:
■ HTTP Sessions, Cookies, and URL Rewriting
■ Coordinating Session Access
■ Saving Sessions During Redeployment
■ Logging Session Attributes
■ Distributed Sessions and Persistence
This is especially likely to occur in web applications that use HTML frames where
multiple servlets are executing simultaneously on behalf of the same client. A good
solution is to ensure that one of the servlets modifies the session and the others have
read-only access.
For details, see the GlassFish Server Open Source Edition Reference Manual.
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.
For web applications, this feature is applicable only if in the glassfish-web-app.xml
file the persistence-type attribute of the session-manager element is file.
If any active web session fails to be preserved or restored, none of the sessions will be
available when the redeployment is complete. However, the redeployment continues
and a warning is logged.
The new class loader of the redeployed application is used to deserialize any sessions
previously saved. The usual restrictions about serialization and deserialization apply.
For example, any application-specific class referenced by a session attribute may
evolve only in a backward-compatible fashion. For more information about class
loaders, see Class Loaders.
7-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
Creating and Managing Sessions
■ The web application must be deployed using the deploy or deploydir command
with the --availabilityenabled option set to true. See the GlassFish Server Open
Source Edition Reference Manual.
In the event of an instance or hardware failure, another server instance can take over a
distributed session, with the following limitations:
■ If a distributable web application references a Java EE component or resource, the
reference might be lost. See Table 7–3 for a list of the types of references that
HTTPSession failover supports.
■ References to open files or network connections are lost.
For information about how to work around these limitations, see the GlassFish Server
Open Source Edition Deployment Planning Guide.
In the following 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.
For more information about the InitialContext, see Accessing the Naming Context.
For more information about transaction recovery, see Using the Transaction Service.
For more information about Administered Objects, see "Administering JMS Physical
Destinations" in GlassFish Server Open Source Edition Administration Guide.
Table 7–3 Object Types Supported for Java EE Web Application Session State Failover
Java Object Type Failover Support
Colocated or distributed stateless session, Yes
stateful session, or entity bean reference
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.
JDBC DataSource No
Java Message Service (JMS) No
ConnectionFactory, Destination
JavaMail Session No
Connection Factory No
Administered Object No
Web service reference No
Serializable Java types Yes
Extended persistence context No
Session Managers
A session manager automatically creates new session objects whenever a new session
starts. In some circumstances, clients do not join the session, for example, if the session
manager uses cookies and the client does not accept cookies.
GlassFish Server offers these session management options, determined by the
session-manager element's persistence-type attribute in the glassfish-web.xml file:
■ The memory Persistence Type, the default
■ The file Persistence Type, which uses a file to store session data
■ The replicated Persistence Type, which uses other servers in the cluster for
session persistence
■ The coherence-web Persistence Type, which uses Coherence*Web for session
persistence
For more information, see "session-manager" in GlassFish Server Open Source Edition
Application Deployment Guide.
<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 GlassFish Server Open
Source Edition Application Deployment Guide. The sessionFilename property specifies
the name of the file 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.
7-12 GlassFish Server Open Source Edition 4.0 Application Development Guide
Creating and Managing Sessions
For more information about the glassfish-web.xml file, see the GlassFish Server Open
Source Edition Application Deployment Guide.
To specify the file persistence type for a specific web application, edit the
glassfish-web.xml file 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>
...
</session-config>
...
</glassfish-web-app>
The file persistence type supports all the manager properties listed under
"manager-properties" in GlassFish Server Open Source Edition Application Deployment
Guide except sessionFilename, and supports the directory store property listed
under "store-properties" in GlassFish Server Open Source Edition Application Deployment
Guide.
For more information about the glassfish-web.xml file, see the GlassFish Server Open
Source Edition Application Deployment Guide.
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 GlassFish Server Open Source
Edition 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-frequenc
y=time-based
For more information, see the description of the asadmin set command in the
GlassFish Server Open Source Edition Reference Manual.
To specify the replicated persistence type for a specific web application, edit the
glassfish-web.xml file 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>
<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 GlassFish Server Open Source Edition Application Deployment
Guide except sessionFilename, and supports the persistenceScope store property
listed under "store-properties" in GlassFish Server Open Source Edition Application
Deployment Guide.
For more information about the glassfish-web.xml file, see the GlassFish Server Open
Source Edition Application Deployment Guide.
To specify that web sessions for which high availability is enabled are first buffered
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
7-14 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Comet
Using Comet
This section explains the Comet programming technique and how to create and
deploy a Comet-enabled application with the Oracle GlassFish Server.
The following topics are addressed here:
■ Introduction to Comet
■ Grizzly Comet
■ Bayeux Protocol
Introduction to Comet
Comet is a programming technique that allows a web server to send updates to clients
without requiring the clients to explicitly request them.
This kind of programming technique is called server push, which means that the server
pushes data to the client. The opposite style is client pull, which means that the client
must pull the data from the server, usually through a user-initiated event, such as a
button click.
Web applications that use the Comet technique can deliver updates to clients in a more
timely manner than those that use the client-pull style while avoiding the latency that
results from clients frequently polling the server.
One of the many use cases for Comet is a chat room application. When the server
receives a message from one of the chat clients, it needs to send the message to the
other clients without requiring them to ask for it. With Comet, the server can deliver
messages to the clients as they are posted rather than expecting the clients to poll the
server for new messages.
To accomplish this scenario, a Comet application establishes a long-lived HTTP
connection. This connection is suspended on the server side, waiting for an event to
happen before resuming. This kind of connection remains open, allowing an
application that uses the Comet technique to send updates to clients when they are
available rather than expecting clients to reopen the connection to poll the server for
updates.
web server were to use blocking connections then it might end up holding many
thousands of threads, thereby hindering its scalability.
The GlassFish server includes the Grizzly HTTP Engine, which enables asynchronous
request processing (ARP) by avoiding blocking connections. Grizzly's ARP
implementation accomplishes this by using the Java NIO API.
With Java NIO, Grizzly enables greater performance and scalability by avoiding the
limitations experienced by traditional web servers that must run a thread for each
request. Instead, Grizzly's ARP mechanism makes efficient use of a thread pool system
and also keeps the state of requests so that it can keep requests alive without holding a
single thread for each of them.
Grizzly supports two different implementations of Comet:
■ Grizzly Comet — Based on ARP, this includes a set of APIs that you use from a
web component to enable Comet functionality in your web application. Grizzly
Comet is specific to the Oracle GlassFish Server.
■ Bayeux Protocol — 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 from an Enterprise Java Beans (EJB ) component. The Grizzly
implementation of Cometd consists of a servlet that you reference from your web
application.
HTTP Streaming The HTTP Streaming technique keeps a connection open indefinitely. It
never closes, even after the server pushes data to the client.
7-16 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Comet
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
significantly 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.
How to Choose the Type 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 buffer the response from the 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:
■ The Grizzly Comet API
■ The Hidden Frame Example
■ Creating a Comet-Enabled Application
■ Developing the Web Component
■ Creating the Client Pages
■ Creating the Deployment Descriptor
■ Deploying and Running a Comet-Enabled Application
7-18 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Comet
3. After clicking the button on the button.html page, the page submits a POST
request to the servlet.
4. The doPost method calls the onEvent method of the Comet handler and redirects
the incremented count along with some JavaScript to the count.html page on the
client.
5. The updateCount() JavaScript function on the count.html page updates the
counter on the page.
6. Because this example uses long-polling, the JavaScript code on count.html calls
doGet again to resume the connection after the servlet pushes the update.
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {}
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {);
}
import com.sun.grizzly.comet.CometHandler;
3. Import these additional classes that you need for incrementing a counter and
writing output to the clients:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;
To Register the Servlet With the Comet Engine Follow this procedure.
1. In the servlet's init method, add the following code to get the component's
context path:
ServletContext context = config.getServletContext();
contextPath = context.getContextPath() + "/hidden_comet";
2. Get an instance of the Comet engine by adding this line after the lines from Step 1:
CometEngine engine = CometEngine.getEngine();
3. Register the component with the Comet engine by adding the following lines after
those from Step 2:
CometContext cometContext = engine.register(contextPath);
cometContext.setExpirationDelay(30 * 1000);
To Define a Comet Handler to Send Updates to the Client Follow this procedure.
1. Create a private class that implements CometHandler and add it to the servlet
class:
private class CounterHandler
implements CometHandler<HttpServletResponse> {
private HttpServletResponse response;
}
7-20 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Comet
response.getWriter().close();
CometContext context =
CometEngine.getEngine().getCometContext(contextPath);
context.removeCometHandler(this);
}
To Add the Comet Handler to the Comet Context Follow this procedure.
1. Get an instance of the Comet handler and attach the response to it by adding the
following lines to the doGet method:
CounterHandler handler = new CounterHandler();
handler.attach(res);
3. Add the Comet handler to the Comet context by adding this line to doGet:
context.addCometHandler(handler);
This method first checks if the event type is NOTIFY, which means that the web
component is notifying the CometHandler object that a client has incremented the
count. If the event type is NOTIFY, the onEvent method gets the updated count, and
writes out JavaScript to the client. The JavaScript includes a call to the
updateCount () function, which will update the count on the clients' pages.
The last line resumes the Comet request and removes it from the list of active
CometHandler objects. By this line, you can tell that this application uses the
long-polling technique. If you were to delete this line, the application would use
the HTTP-Streaming technique.
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.
2. Increment the counter and forward the response by adding the following lines to
the 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.
To Create a HTML Welcome Page That Contains IFrames for Receiving and Sending Updates
Follow this procedure.
1. Create an HTML page called index.html.
2. Add the following content to the page:
<html>
<head>
<title>Comet Example: Counter with Hidden Frame</title>
</head>
<body>
</body>
</html>
3. Add IFrames for connecting to the server and receiving and sending updates to
index.html in between the body tags:
<frameset>
<iframe name="hidden" src="hidden_comet"
frameborder="0" height="0" width="100%"></iframe>
7-22 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Comet
The first frame, which is hidden, points to the servlet by referencing its context
path. The second frame displays the content from count.html, which displays the
current count. The second frame displays the content from button.html, which
contains the submit button for incrementing the counter.
To Create a HTML Page That Updates and Displays the Content Follow this procedure.
1. Create an HTML page called count.html and add the following content to it:
<html>
<head>
</head>
<body>
<center>
<h3>Comet Example: Counter with Hidden Frame</h3>
<p>
<b id="count"> </b>
<p>
</center>
</body>
</html>
The JavaScript takes the updated count it receives from the servlet and updates the
count element in the page. The last line in the updateCount () function invokes
the servlet's doGet method again to reestablish the connection.
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.
To Create the HTML Page That Allows Submitting Updates Create an HTML page called
button.html and add the following content to it:
<html>
<head>
</head>
<body>
<center>
<form method="post" action="hidden_comet">
This page displays a form with a button that allows a user to update the count on the
server. The servlet will then broadcast the updated count to all clients.
To Create the Deployment Descriptor Create a file called web.xml and put the following
contents in it:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="httphttp://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd ">
<servlet>
<servlet-name>HiddenCometServlet</servlet-name>
<servlet-class>
com.sun.grizzly.samples.comet.HiddenCometServlet
</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HiddenCometServlet</servlet-name>
<url-pattern>/hidden_comet</url-pattern>
</servlet-mapping>
</web-app>
Enabling Comet in the GlassFish Server Before running a Comet-enabled application, you
need to enable Comet in the HTTP listener for your application by setting a special
attribute in the associated protocol configuration. The following example shows the
asadmin set command that adds this attribute:
asadmin set
server-config.network-config.protocols.protocol.http-1.http.comet-support-enabled=
"true"
7-24 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Comet
To Deploy the Example These instructions tell you how to deploy the Hidden Frame
example.
1. Download grizzly-comet-hidden-1.7.3.1.war
(http://download.java.net/maven/2/com/sun/grizzly/samples/gri
zzly-comet-hidden/1.7.3.1/).
2. Run the following command to deploy the example:
as-install/bin/asadmin deploy grizzly-comet-hidden-1.7.3.1.war
To Run the Example These instructions tell you how to run the Hidden Frame example.
1. Open two web browsers, preferably two different brands of web browser.
2. Enter the following URL in both browsers:
http://localhost:8080/grizzly-comet-hidden/index.html
3. When the first page loads in both browsers, click the button in one of the browsers
and watch the count change in the other browser window.
Bayeux Protocol
The Bayeux protocol, often referred to as Cometd, greatly simplifies 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:
■ Enabling Comet
■ To Configure the web.xml File
■ To Write, Deploy, and Run the Client
Enabling Comet
Before running a Comet-enabled application, you need to enable Comet in the HTTP
listener for your application by setting a special attribute in the associated protocol
configuration. The following example shows the asadmin set command that adds this
attribute:
asadmin set
server-config.network-config.protocols.protocol.http-1.http.comet-support-enabled=
"true"
3. In the script, use publish and subscribe methods to send and receive messages.
For example:
cometd.subscribe("/chat/demo", false, room, "_chat");
cometd.publish("/chat/demo", { user: room._username, chat: text});
4. Deploy the web application as you would any other web application. For example:
asadmin deploy cometd-example.war
7-26 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Web Application Features
See Also
For more information about deployment in the GlassFish Server, see the GlassFish
Server Open Source Edition Application Deployment Guide.
For more information about the Bayeux protocol, see Bayeux Protocol
(http://svn.cometd.com/trunk/bayeux/bayeux.html).
For more information about the Dojo toolkit, see http://dojotoolkit.org/.
For information about REpresentational State Transfer (RESTful) web services and
Comet, see RESTful Web Services and Comet
(http://developers.sun.com/appserver/reference/techart/cometslid
eshow.html).
Internationalization Issues
The following topics are addressed here:
■ The Server's Default Locale
■ Servlet Character Encoding
Servlet Request When processing a servlet request, the server uses the following order
of precedence, first to last, to determine the request character encoding:
■ The getCharacterEncoding method
■ A hidden field in the form, specified by the form-hint-field attribute of the
parameter-encoding element in the glassfish-web.xml file
■ The default-charset attribute of the parameter-encoding element in the
glassfish-web.xml file
■ The default, which is ISO-8859-1
For details about the parameter-encoding element, see "parameter-encoding" in
GlassFish Server Open Source Edition Application Deployment Guide.
Servlet Response When processing a servlet response, the server uses the following
order of precedence, first to last, to determine the response character encoding:
■ The setCharacterEncoding or setContentType method
■ The setLocale method
■ The default, which is ISO-8859-1
7-28 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Web Application Features
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 the GlassFish Server Open Source
Edition 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 from overriding core Java runtime classes or changing the API versions of
specifications that are part of the Java EE platform.
For general information about class loaders, see Class Loaders.
If listings is set to true, you can also determine how directory 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 define your own using
mime-mapping elements in your web application's web.xml file. For more information
about mime-mapping elements, see the Servlet specification.
You can use the Administration Console to edit the default-web.xml file. For details,
click the Help button in the Administration Console. As an alternative, you can edit
the file directly using the following steps.
Select Logger Settings under the relevant configuration, or select the Stand-Alone
Instances component, select the instance from the table, and select the Monitor tab.
7-30 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Web Application Features
Header Management
In all Editions of the GlassFish Server, the Enumeration from request.getHeaders()
contains multiple elements (one element per request header) instead of a single,
aggregated value.
The header names used in HttpServletResponse.addXXXHeader() and
HttpServletResponse.setXXXHeader() are returned as they were created.
You can define these same properties for a virtual server. For more information, see
Virtual Server Properties.
■ Extension match
For example, the following properties specify three glassfish-web.xml docroots. The
URI pattern of the first alternate docroot uses an exact match, whereas the URI
patterns of the second and third alternate docroots use extension and longest path
prefix 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 first component, from,
specifies the alternate docroot's URI pattern, and the second component, dir, specifies
the alternate docroot's physical location (directory).
Suppose the above examples belong to a web application deployed at
http://company22.com/myapp. The first 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 suffix, such as:
http://company22.com/myapp/*.jpg
The third alternate docroot maps any requests whose URI starts with /myapp/jpg/,
such as:
http://company22.com/myapp/jpg/*
To:
/srv/images/jpg/abc/def/my.jpg
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 from the web application's standard docroot, as usual.
7-32 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Web Application Features
To define a global context.xml file, place the file 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 file for a specific virtual server. Specify this property in
one of the following ways:
■ In the Administration Console, open the HTTP Service component under the
relevant configuration. Open the Virtual Servers component and scroll down to
the bottom of the page. Enter contextXmlDefault as the property name and the
path and file name relative to domain-dir as the property value.
■ Use the asadmin create-virtual-server command. For example:
asadmin create-virtual-server --property contextXmlDefault=config/vs1ctx.xml
vs1
■ 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
To define a context.xml file for a specific web application, place the file in the
META-INF directory and name it context.xml.
For more information about virtual server properties, see Virtual Server Properties. For
more information about the context.xml file, see The Context Container
(http://tomcat.apache.org/tomcat-5.5-doc/config/context.html).
Context parameters, environment entries, and resource definitions in context.xml are
supported in the GlassFish Server.
Enabling WebDav
To enable WebDav in the GlassFish Server, you edit the web.xml and
glassfish-web.xml files as follows.
First, enable the WebDav servlet in your web.xml file:
<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 define the servlet mapping associated with your WebDav servlet in your web.xml
file:
<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 file:
<security-constraint>
<web-resource-collection>
<web-resource-name>Login Resources</web-resource-name>
<url-pattern>/webdav/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Admin</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
<security-role>
<role-name>Admin</role-name>
</security-role>
</security-constraint>
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.
You can now use any WebDav client by connecting to the WebDav servlet URL, which
has this format:
http://host:port/context-root/webdav/file
For example:
http://localhost:80/glassfish-webdav/webdav/index.html
You can add the WebDav servlet to your default-web.xml file to enable it for all
applications, but you can't set up a security role mapping to protect it.
Using SSI
To enable SSI (server-side includes) processing for a specific web module, add the
SSIServlet to your web.xml file as follows:
<web-app>
<servlet>
<servlet-name>ssi</servlet-name>
<servlet-class>org.apache.catalina.ssi.SSIServlet</servlet-class>
</servlet>
...
7-34 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Web Application Features
<servlet-mapping>
<servlet-name>ssi</servlet-name>
<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 file.
If the mime-mapping is not specified in web.xml, GlassFish Server attempts to
determine the MIME type from default-web.xml or the operating system default.
You can configure the following init-param values for the SSIServlet.
Using CGI
To enable CGI (common gateway interface) processing for a specific web module, add
the CGIServlet to your web.xml file as follows:
<web-app>
<servlet>
<servlet-name>cgi</servlet-name>
<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 file.
Package the CGI program under 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 from direct viewing or download. For information about
hiding directory listings, see Using the default-web.xml File.
Invoke the CGI program using 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 configure the following init-param values for the CGIServlet.
7-36 GlassFish Server Open Source Edition 4.0 Application Development Guide
8
Using Enterprise JavaBeans Technology
8
This chapter describes how Enterprise JavaBeans ( EJB) technology is supported in the
Oracle GlassFish Server.
The following topics are addressed here:
■ Value Added Features
■ EJB Timer Service
■ Using Session Beans
■ Using Read-Only Beans
■ Using Message-Driven Beans
For general information about enterprise beans, see "Enterprise Beans" in The Java EE 7
Tutorial.
Note: The Web Profile of the GlassFish Server supports the EJB 3.1
Lite specification, which allows enterprise beans within web
applications, among other features. The full GlassFish Server
supports the entire EJB 3.1 specification. For details, see JSR 318
(http://jcp.org/en/jsr/detail?id=318).
The GlassFish Server is backward compatible with 1.1, 2.0, 2.1, and
3.0 enterprise beans. However, to take advantage of version 3.1
features, you should develop new beans as 3.1 enterprise beans.
Read-Only Beans
Another feature that the GlassFish Server provides is the read-only bean, an EJB 2.1
entity bean that is never modified by an EJB client. Read-only beans avoid database
updates completely.
Note: Read-only beans are specific to the GlassFish Server and are
not part of the Enterprise JavaBeans Specification, 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 read-only, use @Column annotations to
mark its columns insertable=false and updatable=false.
A read-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 notified to
refresh its cached data.
The GlassFish Server provides a number of ways by which a read-only bean's state can
be refreshed. By setting the refresh-period-in-seconds element in the
glassfish-ejb-jar.xml file and the trans-attribute element (or
@TransactionAttribute annotation) in the ejb-jar.xml file, it is easy to configure a
read-only bean that is one of the following:
■ 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.
8-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Value Added Features
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 row in 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 from the
cache, usually when cache overflows. 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 file.
Pooling and caching parameters for the glassfish-ejb-jar.xml file are described in
"bean-cache" in GlassFish Server Open Source Edition Application Deployment Guide.
Pooling Parameters
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 specified 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 JVM at a given
time will not exceed the value specified 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 from blocking 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 specified duration.
Caching Parameters
GlassFish Server provides a way that completely avoids caching of entity beans, using
commit option C. Commit option C is particularly useful if beans are accessed in large
number but very rarely reused. For additional information, refer to Commit Options.
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, NRU and FIFO) of picking
victim beans when cache overflow occurs. Caches can also passivate beans that are
idle (not accessed for a specified duration).
is no such thread pool configured 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 flush that precedes execution
of a finder or select query.
Since a transaction often spans many method calls, you might want to find out if the
updates made by a method succeeded or failed immediately after method execution.
To force a flush at the end of a method's execution, use the flush-at-end-of-method
element in the glassfish-ejb-jar.xml file. Only non-finder methods in an entity
bean can be flush-enabled. (For an EJB 2.1 bean, these methods must be in the Local,
Local Home, Remote, or Remote Home interface.) See "flush-at-end-of-method" in
GlassFish Server Open Source Edition 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 flush is a create method, the exception is
wrapped with CreateException.
■ If the method that triggered the flush is a remove method, the exception is
wrapped with RemoveException.
■ For all other methods, the exception is wrapped with EJBException.
All normal end-of-transaction database synchronization steps occur regardless of
whether the database has been flushed during the transaction.
To change the database used by the EJB Timer Service, set the EJB Timer Service's
Timer DataSource setting to a valid JDBC resource. If the EJB Timer Service has already
been started in a server instance, you must also create the timer database table. DDL
files are located in as-install/lib/install/databases.
Using the EJB Timer Service is equivalent to interacting with a single JDBC resource
manager. If an EJB component or application accesses a database either directly
through JDBC or indirectly (for example, through an entity bean's persistence
mechanism), and also interacts with the EJB Timer Service, its data source must be
configured with an XA JDBC driver.
8-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
EJB Timer Service
You can change the following EJB Timer Service settings. You must restart the server
for the changes to take effect.
Maximum Redeliveries
Specifies the maximum number of times the EJB timer service attempts to redeliver a
timer expiration after an exception or rollback of a container-managed transaction. The
default is 1.
Redelivery Interval
Specifies how long in milliseconds the EJB timer service waits after a failed
ejbTimeout delivery before attempting a redelivery. The default is 5000.
Timer DataSource
Specifies the database used by the EJB Timer Service. The default is jdbc/__TimerPool.
The problem is that embedded Java DB runs in the GlassFish Server Java VM, so when
you use the jdbc/__TimerPool resource, each DAS and each clustered server instance
will have its own database table. Because of this, clustered server instances will not be
able to find the database table on the DAS, and the DAS will not be able to find the
tables on the clustered server instances.
The solution is to use either a custom JDBC resource or the jdbc/__default resource
that is preconfigured but not enabled by default in GlassFish Server. The jdbc/__
default resource does not use embedded Java DB by default.
Troubleshooting
If you inadvertently used the jdbc/__TimerPool resource for your EJB timer in a
clustered GlassFish Server environment, the DAS and the clustered server instances
will be using separate Java DB database tables that are running in individual Java
VMs. For timers to work in a clustered environment, the DAS and the clustered server
instances must share a common database table.
If you attempt to deploy an application with EJB timers without setting the timer
resource correctly, the startup will fail, and you will be left with a marker file, named
ejb-timer-service-app, on the DAS that will prevent the Timer Service from
correctly creating the database table.
The solution is to remove the marker file on the DAS, restart the DAS and the clusters,
and then redploy any applications that rely on the offending EJB timer. The marker file
is located on the DAS in domain-dir/generated/ejb/ejb-timer-service-app.
8-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Session Beans
Stateless Container
The stateless container manages stateless session beans, which, by definition, do not
carry client-specific states. All session beans (of a particular type) are considered equal.
A stateless session bean container uses a bean pool to service requests. The GlassFish
Server specific deployment descriptor file, glassfish-ejb-jar.xml, contains the
properties that define the pool:
■ steady-pool-size
■ resize-quantity
■ max-pool-size
■ pool-idle-timeout-in-seconds
For more information about glassfish-ejb-jar.xml, see "The glassfish-ejb-jar.xml
File" in GlassFish Server Open Source Edition 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 GlassFish Server Open Source Edition Reference Manual.
Stateful Container
The stateful container manages the stateful session beans, which, by definition, carry the
client-specific 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 ID that 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 specifies the maximum number of session beans that are
held in cache. If the cache overflows (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 file. The directory in which the file is created is obtained from
the EJB container using the configuration APIs.
For more information about glassfish-ejb-jar.xml, see "The glassfish-ejb-jar.xml
File" in GlassFish Server Open Source Edition Application Deployment Guide.
The passivated beans are stored on the file 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-specific subdirectories created under domain-dir/session-store.
The Session Store Location setting also determines where the session state is persisted
if it is not highly available; see Choosing a Persistence Store.
8-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Session Beans
Table 8–1 Object Types Supported for Java EE Stateful Session Bean State Failover
Java Object Type Failover Support
Colocated or distributed stateless session, Yes
stateful session, or entity bean reference
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.
JDBC DataSource No
Java Message Service (JMS) No
ConnectionFactory, Destination
JavaMail Session No
Connection Factory No
Administered Object No
Web service reference No
Serializable Java types Yes
Extended persistence context No
For more information about the InitialContext, see Accessing the Naming Context.
For more information about transaction recovery, see Using the Transaction Service.
For more information about Administered Objects, see "Administering JMS Physical
Destinations" in GlassFish Server Open Source Edition Administration Guide.
Note: Idempotent URLs are supported along the HTTP path, but
not the RMI-IIOP path. For more information, see Configuring
Idempotent URL Requests.
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 application's session fails over, the
EJB reference is also failed over. For more information, see
Distributed Sessions and Persistence.
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.
Using the --keepstate Option If you are using the file system for 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 from
working 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 GlassFish Server
Open Source Edition Reference Manual.
Using the --asyncreplication Option 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 first buffered 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
buffered but not yet replicated fails, the states are lost. If set to false, performance is
8-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Session Beans
reduced but availability is guaranteed. States are not buffered but immediately
transmitted to other instances in the cluster.
For more information about the asadmin deploy command, see the GlassFish Server
Open Source Edition Reference Manual.
Enabling Checkpointing
The following sections describe how to enable SFSB checkpointing:
■ Server Instance and EJB Container Levels
■ Application and EJB Module Levels
■ SFSB Level
Server Instance and EJB Container Levels To enable SFSB checkpointing at the server
instance or EJB container level, see Choosing a Persistence Store.
Application and EJB Module Levels To enable SFSB checkpointing at the application or
EJB module level during deployment, use the asadmin deploy or asadmin deploydir
command with the --availabilityenabled option set to true. For details, see the
GlassFish Server Open Source Edition Reference Manual.
</checkpoint-at-end-of-method>
</ejb>
...
</enterprise-beans>
</glassfish-ejb-jar>
Restricting Transactions
The following restrictions on transactions are enforced by the container and must be
observed as session beans are developed:
■ A session bean can participate in, at most, a single transaction at a time.
8-12 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Read-Only Beans
EJB Singletons
EJB Singletons are created for each server instance in a cluster, and not once per
cluster.
Note: Read-only beans are specific to the GlassFish Server and are
not part of the Enterprise JavaBeans Specification, 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:
■ Read-Only Bean Characteristics and Life Cycle
■ Read-Only Bean Good Practices
■ Refreshing Read-Only Beans
■ Deploying Read-Only Beans
Refreshing Periodically
Use the refresh-period-in-seconds element in the glassfish-ejb-jar.xml file to
refresh a read-only bean periodically.
■ If the value specified in refresh-period-in-seconds is zero or not specified,
which is the default, the bean is never refreshed (unless a transactional method is
accessed).
■ If the value is greater than zero, the bean is refreshed at the rate specified.
8-14 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Read-Only Beans
Note: This is the only way to refresh the bean state if the data can
be modified external to the GlassFish Server.
By default, a single timer is used for all instances of a read-only bean. When that timer
fires, all bean instances are marked as expired and are refreshed from the database the
next time they are used.
Use the -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true flag 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 flag, use the asadmin create-jvm-options command. For example:
asadmin create-jvm-options
-Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true
Refreshing Programmatically
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 ReadOnlyBeanNotifier to force the
refresh of read-only beans.
To do this, invoke the following methods on the ReadOnlyBeanNotifier bean:
public interface ReadOnlyBeanNotifier extends java.rmi.Remote {
refresh(Object PrimaryKey) throws RemoteException;
}
For a local read-only bean notifier, the lookup has this modification:
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.
8-16 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Message-Driven Beans
■ max-pool-size
■ pool-idle-timeout-in-seconds
For more information about glassfish-ejb-jar.xml, see "The glassfish-ejb-jar.xml
File" in GlassFish Server Open Source Edition Application Deployment Guide.
Domain-Level Settings
You can control the following domain-level message-driven bean settings in the EJB
container:
Idle Timeout
Specifies the maximum time 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). A value of
0 means a bean can remain idle indefinitely.
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 from the
table, and select the Monitor tab.
server resources (threads, memory, and so on), and any concurrency requirements and
limitations from other resources that the message-driven bean accesses.
When tuning performance and resource usage, make sure to consider potential JMS
provider properties for the connection factory used by the container (the
mdb-connection-factory element in the glassfish-ejb-jar.xml file). For example,
you can tune the Open Message Queue flow control related properties for connection
factory in situations where the message incoming rate is much higher than
max-pool-size can handle.
Refer to "Administering the Monitoring Service" in GlassFish Server Open Source Edition
Administration Guide for information on how to get message-driven bean pool
statistics.
For more information about the asadmin set command, see the GlassFish Server Open
Source Edition Reference Manual.
The cmt-max-runtime-exceptions property specifies the maximum number of
runtime exceptions allowed from a message-driven bean's onMessage method before
the container starts to close the container's connection to the message source. By
default this value is 1; -1 disables this container protection.
A message-driven bean's onMessage method can use the
javax.jms.Message.getJMSRedelivered method to check whether a received message
is a redelivered message.
8-18 GlassFish Server Open Source Edition 4.0 Application Development Guide
Using Message-Driven Beans
8-20 GlassFish Server Open Source Edition 4.0 Application Development Guide
9
9Using Container-Managed Persistence
Note: The Web Profile of the GlassFish Server supports the EJB 3.1
Lite specification, which allows enterprise beans within web
applications, among other features. The full GlassFish Server
supports the entire EJB 3.1 specification. For details, see JSR 318
(http://jcp.org/en/jsr/detail?id=318).
CMP Mapping
Implementation for entity beans that use CMP is mostly a matter of mapping CMP
fields and CMR fields (relationships) to the database.
The following topics are addressed here:
■ Mapping Capabilities
■ The Mapping Deployment Descriptor File
■ Mapping Considerations
Mapping Capabilities
Mapping refers to the ability to tie an object-based model to a relational model of data,
usually the schema of a relational database. The CMP implementation provides the
ability to tie a set of interrelated beans containing data and associated behaviors to the
schema. This object representation of the database becomes part of the Java
application. You can also customize this mapping to optimize these beans for the
particular needs of an application. The result is a single data model through which
both persistent database information and regular transient program data are accessed.
The mapping capabilities provided by the GlassFish Server include:
■ Mapping a CMP bean to one or more tables
■ Mapping CMP fields to one or more columns
■ Mapping CMP fields to different column types
■ Mapping tables with compound primary keys
■ Mapping tables with unknown primary keys
■ Mapping CMP relationships to foreign keys
■ Mapping tables with overlapping primary and foreign keys
9-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
CMP Mapping
Mapping Considerations
The following topics are addressed here:
■ Join Tables and Relationships
■ Automatic Primary Key Generation
■ Fixed Length CHAR Primary Keys
■ Managed Fields
■ BLOB Support
■ CLOB Support
The data types used in automatic schema generation are also suggested for manual
mapping. These data types are described in Supported Data Types for CMP.
Managed Fields
A managed field is a CMP or CMR field that is mapped to the same database column
as another CMP or CMR field. CMP fields mapped to the same column and CMR
fields mapped to exactly the same column lists always have the same value in
memory. For CMR fields that share only a subset of their mapped columns, changes to
the columns affect the relationship fields in memory differently. Basically, the
GlassFish Server always tries to keep the state of the objects in memory synchronized
with the database.
A managed field can have any fetched-with subelement. If the fetched-with
subelement is <default/>, the -DAllowManagedFieldsInDefaultFetchGroup flag must
be set to true. See Default Fetch Group Flags and "fetched-with" in GlassFish Server
Open Source Edition Application Deployment Guide.
BLOB Support
Binary Large Object (BLOB) is a data type used to store values that do not correspond
to other types such as numbers, strings, or dates. Java fields whose types implement
java.io.Serializable or are represented as byte[] can be stored as BLOBs.
If a CMP field is defined as Serializable, it is serialized into a byte[] before being
stored in the database. Similarly, the value fetched from the database is deserialized.
However, if a CMP field is defined as byte[], it is stored directly instead of being
serialized and deserialized when stored and fetched, respectively.
To enable BLOB support in the GlassFish Server environment, define a CMP field of
type byte[] or a user-defined type that implements the java.io.Serializable interface. If
you map the CMP bean to an existing database schema, map the field to a column of
type BLOB.
To use BLOB or CLOB data types larger than 4 KB for CMP using the Inet Oraxo JDBC
Driver for Oracle Databases, you must set the streamstolob property value to true.
For a list of the JDBC drivers currently supported by the GlassFish Server, see the
GlassFish Server Open Source Edition Release Notes. For configurations of supported and
9-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Automatic Schema Generation for CMP
other drivers, see "Configuration Specifics for JDBC Drivers" in GlassFish Server Open
Source Edition Administration Guide.
For automatic mapping, you might need to change the default BLOB column length
for the generated schema using the schema-generator-properties element in
glassfish-ejb-jar.xml. See your database vendor documentation to determine
whether you need to specify the length. For example:
<schema-generator-properties>
<property>
<name>Employee.voiceGreeting.jdbc-type</name>
<value>BLOB</value>
</property>
<property>
<name>Employee.voiceGreeting.jdbc-maximum-length</name>
<value>10240</value>
</property>
...
</schema-generator-properties>
CLOB Support
Character Large Object (CLOB) is a data type used to store and retrieve very long text
fields. CLOBs translate into long strings.
To enable CLOB support in the GlassFish Server environment, define a CMP field of
type java.lang.String. If you map the CMP bean to an existing database schema,
map the field to a column of type CLOB.
To use BLOB or CLOB data types larger than 4 KB for CMP using the Inet Oraxo JDBC
Driver for Oracle Databases, you must set the streamstolob property value to true.
For a list of the JDBC drivers currently supported by the GlassFish Server, see the
GlassFish Server Open Source Edition Release Notes. For configurations of supported and
other drivers, see "Configuration Specifics for JDBC Drivers" in GlassFish Server Open
Source Edition Administration Guide.
For automatic mapping, you might need to change the default CLOB column length
for the generated schema using the schema-generator-properties element in
glassfish-ejb-jar.xml. See your database vendor documentation to determine
whether you need to specify the length. For example:
<schema-generator-properties>
<property>
<name>Employee.resume.jdbc-type</name>
<value>CLOB</value>
</property>
<property>
<name>Employee.resume.jdbc-maximum-length</name>
<value>10240</value>
</property>
...
</schema-generator-properties>
9-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Automatic Schema Generation for CMP
Table 9–1 (Cont.) Java Type to JDBC Type Mappings for CMP
Java Type JDBC Type Nullability
char CHAR No
java.lang.Character CHAR Yes
java.lang.String VARCHAR or CLOB Yes
Serializable BLOB Yes
byte[] BLOB Yes
java.util.Date DATE (Oracle only) Yes
TIMESTAMP (all other databases)
java.sql.Date DATE Yes
java.sql.Time TIME Yes
java.sql.Timestamp TIMESTAMP Yes
The following table contains the mappings of JDBC types to database vendor-specific
types when automatic mapping is used. For a list of the JDBC drivers currently
supported by the GlassFish Server, see the GlassFish Server Open Source Edition Release
Notes. For configurations of supported and other drivers, see "Configuration Specifics
for JDBC Drivers" in GlassFish Server Open Source Edition Administration Guide.
Table 9–2 Mappings of JDBC Types to Database Vendor Specific Types for CMP
Java DB, Derby, Sybase ASE
JDBC Type CloudScape Oracle DB2 12.5 MS-SQL Server
BIT SMALLINT SMALLINT SMALLINT TINYINT BIT
TINYINT SMALLINT SMALLINT SMALLINT TINYINT TINYINT
SMALLINT SMALLINT SMALLINT SMALLINT SMALLINT SMALLINT
INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER
BIGINT BIGINT NUMBER BIGINT NUMERIC NUMERIC
REAL REAL REAL FLOAT FLOAT REAL
DOUBLE DOUBLE DOUBLE DOUBLE DOUBLE FLOAT
PRECISION PRECISION PRECISION
DECIMAL(p,s) DECIMAL(p,s) NUMBER(p,s) DECIMAL(p,s) DECIMAL(p,s) DECIMAL(p,s)
VARCHAR VARCHAR VARCHAR2 VARCHAR VARCHAR VARCHAR
DATE DATE DATE DATE DATETIME DATETIME
TIME TIME DATE TIME DATETIME DATETIME
TIMESTAMP TIMESTAMP TIMESTAMP(9) TIMESTAMP DATETIME DATETIME
BLOB BLOB BLOB BLOB IMAGE IMAGE
CLOB CLOB CLOB CLOB TEXT NTEXT
Note: Before using these options, make sure you have a properly
configured CMP resource. See Configuring the CMP Resource.
For a read-only bean, do not create the database schema during
deployment. Instead, work with your database administrator to
populate the data into the tables. See Using Read-Only Beans.
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. See Version Column Consistency Checking.
9-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Automatic Schema Generation for CMP
The following options of the asadmin deploy or asadmin deploydir command control
the automatic creation of database tables at deployment.
Table 9–4 The asadmin deploy and asadmin deploydir Generation Options for CMP
Option Default Description
--createtables none If true, causes database tables to be created for beans that need them. No
unique constraints are created. If false, does not create tables. If not
specified, the value of the create-tables-at-deploy attribute in
glassfish-ejb-jar.xml is used.
Table 9–4 (Cont.) The asadmin deploy and asadmin deploydir Generation Options for CMP
Option Default Description
--dropandcreatetables none If true, and if tables were automatically created when this application was
last deployed, tables from the earlier deployment are dropped and fresh
ones are created.
If true, and if tables were not automatically created when this application
was last deployed, no attempt is made to drop any tables. If tables with the
same names as those that would have been automatically created are
found, the deployment proceeds, but a warning indicates that tables could
not be created.
If false, settings of create-tables-at-deploy or
drop-tables-at-undeploy in the glassfish-ejb-jar.xml file are
overridden.
--uniquetablenames none If true, specifies that table names are unique within each GlassFish Server
domain. If not specified, the value of the use-unique-table-names
property in glassfish-ejb-jar.xml is used.
--dbvendorname none Specifies the name of the database vendor for which tables are created.
Allowed values are javadb, db2, mssql, oracle, postgresql, pointbase,
derby (also for CloudScape), and sybase, case-insensitive.
If not specified, the value of the database-vendor-name attribute in
glassfish-ejb-jar.xml is used.
If no value is specified, a connection is made to the resource specified by
the jndi-name subelement of the cmp-resource element in the
glassfish-ejb-jar.xml file, and the database vendor name is read. If the
connection cannot be established, or if the value is not recognized, SQL-92
compliance is presumed.
If one or more of the beans in the module are manually mapped and you use any of
the asadmin deploy or asadmin deploydir options, the deployment is not harmed in
any way, but the options have no effect, and a warning is written to the server log.
The following options of the asadmin undeploy command control the automatic
removal of database tables at undeployment.
For more information about the asadmin deploy, asadmin deploydir, and asadmin
undeploy commands, see the GlassFish Server Open Source Edition Reference Manual.
When command line and glassfish-ejb-jar.xml options are both specified, the
asadmin options take precedence.
Schema Capture
The following topics are addressed here:
■ Automatic Database Schema Capture
■ Using the capture-schema Utility
9-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring the CMP Resource
For example, if the JDBC resource has the JNDI name jdbc/MyDatabase, set the CMP
resource in the glassfish-ejb-jar.xml file as follows:
<cmp-resource>
<jndi-name>jdbc/MyDatabase</jndi-name>
</cmp-resource>
Performance-Related Features
The GlassFish Server provides the following features to enhance performance or allow
more fine-grained data checking. These features are supported only for entity beans
with container managed persistence.
The following topics are addressed here:
■ Version Column Consistency Checking
■ Relationship Prefetching
■ Read-Only Beans
■ Default Fetch Group Flags
9-12 GlassFish Server Open Source Edition 4.0 Application Development Guide
Performance-Related Features
Relationship Prefetching
In many cases when an entity bean's state is fetched from the database, its relationship
fields 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 CMR fields in a single database round trip.
To enable relationship prefetching for a CMR field, use the default subelement of the
fetched-with element in the sun-cmp-mappings.xml file. By default, these CMR fields
are prefetched whenever findByPrimaryKey or a custom finder is executed for the
entity, or when the entity is navigated to from a relationship. (Recursive prefetching is
not supported, because it does not usually enhance performance.) See "fetched-with"
in GlassFish Server Open Source Edition Application Deployment Guide.
To disable prefetching for specific custom finders, use the prefetch-disabled element
in the glassfish-ejb-jar.xml file. See "prefetch-disabled" in GlassFish Server Open
Source Edition 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
Read-Only Beans
Another feature that the GlassFish Server provides is the read-only bean, an entity bean
that is never modified by an EJB client. Read-only beans avoid database updates
completely.
Note: Read-only beans are specific to the GlassFish Server and are
not part of the Enterprise JavaBeans Specification, v2.1. Use of this
feature for an EJB 2.1 bean results in a non-portable application.
A read-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 notified to
refresh its cached data.
The GlassFish Server provides a number of ways by which a read-only bean's state can
be refreshed. By setting the refresh-period-in-seconds element in the
glassfish-ejb-jar.xml file and the trans-attribute element (or
@TransactionAttribute annotation) in the ejb-jar.xml file, it is easy to configure a
read-only bean that is one of the following:
■ Always refreshed
■ Periodically refreshed
■ Never refreshed
■ Programmatically refreshed
Access to CMR fields 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.
9-14 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring Queries for 1.1 Finders
■ Query variable declaration - Specifies the name and type of one or more query
variables. Follows the syntax for local variables in the Java language. A query filter
might use query variables to implement joins.
■ Query ordering declaration - Specifies the ordering expression of the query.
Corresponds to the ORDER BY clause of EJB QL.
The GlassFish Server specific deployment descriptor (glassfish-ejb-jar.xml)
provides the following elements to store the EJB 1.1 finder method settings:
query-filter
query-params
query-variables
query-ordering
The bean developer uses these elements to construct a query. When the finder method
that uses these elements executes, the values of these elements are used to execute a
query in the database. The objects from the JDOQL query result set are converted into
primary key instances to be returned by the EJB 1.1 ejbFind method.
The JDO specification, JSR 12 (http://jcp.org/en/jsr/detail?id=12),
provides a comprehensive description of JDOQL. The following information
summarizes the elements used to define EJB 1.1 finders.
String.indexOf(String str)
String.indexOf(String str, int start)
String.length()
Math.abs(numeric n)
Math.sqrt(double d)
Query Parameters
The parameter declaration is a String containing one or more parameter type
declarations separated by commas. This follows the Java syntax for method signatures.
Query Variables
The type declarations follow the Java syntax for local variable declarations.
JDOQL Examples
This section provides a few query examples.
Example 1
The following query returns all players called Michael. It defines a filter that compares
the name field with a string literal:
name == "Michael"
9-16 GlassFish Server Open Source Edition 4.0 Application Development Guide
CMP Restrictions and Optimizations
<method-name>findPlayerByName</method-name>
<query-filter>name == "Michael"</query-filter>
</finder>
Example 2
This query returns all products in a specified price range. It defines two query
parameters which are the lower and upper bound for the price: double low, double
high. The filter compares the query parameters with the price field:
low < price && price < high
Example 3
This query returns all players having a higher salary than the player with the specified
name. It defines a query parameter for the name java.lang.String name.
Furthermore, it defines a variable to which the player's salary is compared. It has the
type of the persistence capable class that corresponds to the bean:
mypackage.PlayerEJB_170160966_JDOState player
The filter compares the salary of the current player denoted by the this keyword with
the salary of the player with the specified name:
(this.salary> player.salary) && (player.name == name)
9-18 GlassFish Server Open Source Edition 4.0 Application Development Guide
CMP Restrictions and Optimizations
■ Do not expose the get and set methods for CMR fields 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 fields of the entity bean through the bean's 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 JAR file.
To avoid this error, make sure the finder method input is less than 255 characters.
For some databases, this code results in only the year, month, and date portion of the
field value being stored in the database. Later if the client tries to find 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 custom query has a date or time value comparison in its WHERE
clause.
For automatic mapping to an Oracle database, fields of type java.util.Date,
java.sql.Date, and java.sql.Time are mapped to Oracle's DATE data type. Fields of
type java.sql.Timestamp are mapped to Oracle's TIMESTAMP(9) data type.
9-20 GlassFish Server Open Source Edition 4.0 Application Development Guide
CMP Restrictions and Optimizations
■ 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 new connection 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:
Can't call rollback when autocommit=true
javax.transaction.SystemException: java.sql.SQLException:
Error open transaction is not closed
To resolve this issue, add relaxAutoCommit=true to the JDBC URL. For more
information, see http://forums.mysql.com/read.php?39,31326,31404.
■ Change the trigger create format from the following:
CREATE TRIGGER T_UNKNOWNPKVC1
BEFORE UPDATE ON UNKNOWNPKVC1
FOR EACH ROW
WHEN (NEW.VERSION = OLD.VERSION)
BEGIN
:NEW.VERSION := :OLD.VERSION + 1;
END;
/
To the following:
DELIMITER |
CREATE TRIGGER T_UNKNOWNPKVC1
BEFORE UPDATE ON UNKNOWNPKVC1
FOR EACH ROW
WHEN (NEW.VERSION = OLD.VERSION)
BEGIN
:NEW.VERSION := :OLD.VERSION + 1;
END
|
DELIMITER ;
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;
This can be done only if the foreign key field is allowed to be null. For more
information, see
http://dev.mysql.com/doc/mysql/en/innodb-foreign-key-constrai
nts.html.
■ When an SQL script has foreign key constraints defined, 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;
9-22 GlassFish Server Open Source Edition 4.0 Application Development Guide
10
Developing Java Clients
10
This chapter describes how to develop, assemble, and deploy Java clients.
The following topics are addressed here:
■ Introducing the Application Client Container
■ Developing Clients Using the ACC
■ Developing Clients Without the ACC
ACC Security
The ACC determines when authentication is needed. This typically occurs when the
client refers to an EJB component that requires authorization or when annotations in
the client's main class trigger injection which, in turn, requires contact with the
GlassFish Server's naming service. To authenticate the end user, the ACC prompts for
any required information, such as a username and password. The ACC itself provides
a very simple dialog box to prompt for and read these values.
The ACC integrates with the GlassFish Server's authentication system. It also supports
SSL (Secure Socket Layer)/IIOP if configured and when necessary; see Using
RMI/IIOP Over SSL.
You can provide an alternate implementation to gather authentication information,
tailored to the needs of the application client. To do so, include the class to perform
these duties in the application client and identify the fully-qualified name of this class
in the callback-handler element of the application-client.xml descriptor for the
client. The ACC uses this class instead of its default class for asking for and reading
the authentication information. The class must implement the
javax.security.auth.callback.CallbackHandler interface. See the Java EE specification,
section 9.2, Application Clients: Security, for more details.
Application clients can use Programmatic Login.
ACC Naming
The client container enables the application clients to use the Java Naming and
Directory Interface (JNDI) to look up Java EE services (such as JMS resources, EJB
components, web services, security, and so on.) and to reference configurable
parameters set at the time of deployment.
10-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
For more information about the asadmin get command, see the GlassFish Server
Open Source Edition Reference Manual.
7. To set up load balancing and failover of remote EJB references, define at least two
target-server elements in the sun-acc.xml file or the appclient script. This step
is not needed for Java Web Start.
If the GlassFish Server instance on which the application client is deployed
participates in a cluster, the ACC finds all currently active IIOP endpoints in the
cluster automatically. However, a client should have at least two endpoints
specified for bootstrapping purposes, in case one of the endpoints has failed.
The target-server elements in the sun-acc.xml file specify one or more IIOP
endpoints used for load balancing. The address attribute is an IPv4 address or
host name, and the port attribute specifies the port number. See "client-container"
in GlassFish Server Open Source Edition Application Deployment Guide.
The --targetserver option of the appclient script specifies one or more IIOP
endpoints used for load balancing. For more information, see Running an
Application Client Using the appclient Script.
10-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
Next Steps
■ For instructions on running the application client, see Using Java Web Start or
Running an Application Client Using the appclient Script.
■ For more information about RMI-IIOP load balancing and failover, see "RMI-IIOP
Load Balancing and Failover" in GlassFish Server Open Source Edition High
Availability Administration Guide.
To disable Java Web Start for a stand-alone eligible application client, use the following
command:
asadmin set
applications.application.module-name.property.java-web-start-enabled="false"
10-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
■ 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 first 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 default URL for an application client module embedded within an application is
as follows. Note that the relative path to the application client JAR file is included.
http://host:port/application-id/appclient-path
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.
Automatically Signing JAR Files The GlassFish Server automatically creates a signed
version of the required JAR file if none exists. When a Java Web Start request for the
gf-client.jar file arrives, the GlassFish Server looks for
domain-dir/java-web-start/gf-client.jar. When a request for an application's
10-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
generated application client JAR file arrives, the GlassFish Server looks in the directory
domain-dir/java-web-start/app-name for a file with the same name as the generated
JAR file created during deployment.
In either case, if the requested signed JAR file is absent or older than its unsigned
counterpart, the GlassFish Server creates a signed version of the JAR file automatically
and deposits it in the relevant directory. Whether the GlassFish Server just signed the
JAR file or not, it serves the file from the domain-dir/java-web-start directory tree in
response to the Java Web Start request.
To sign these JAR files, by default the GlassFish Server uses its self-signed certificate.
When you create a new domain, either by installing the GlassFish Server or by using
the asadmin create-domain command, the GlassFish Server creates a self-signed
certificate and adds it to the domain's key store.
A self-signed certificate is generally untrustworthy because no certification authority
vouches for its authenticity. The automatic signing feature uses the same certificate to
create all required signed JAR files.
Starting with Java SE 7 Update 21, stricter security is enforced for applications
launched using Java Web Start. Application users will see various security messages,
depending on their Java security settings. If Java security is set to Very High on their
systems, users will not be able to launch application clients signed using the GlassFish
Server self-signed certificate.
To minimize impacts to application users, all Java Web Start applications should be
signed with a trusted certificate instead of the GlassFish Server self-signed certificate.
If you use the GlassFish Server Java Web Start feature or deploy applications that
provide their own Java Web Start applications, perform the following steps:
1. Obtain a trusted certificate from a certification authority if your organization does
not already have one.
2. Stop GlassFish Server.
3. Replace the GlassFish Server self-signed certificate with the trusted certificate by
importing the trusted certificate into the GlassFish Server keystore using the s1as
alias. By default, the keystore is located at domain-dir/config/keystore.jks.
For more information about importing a trusted certificate into the domain
keystore, see "Administering JSSE Certificates" in GlassFish Server Open Source
Edition Security Guide.
4. Delete any signed JARs already generated by GlassFish Server:
a. At the command prompt, type:
rm -rf domain-dir/java_web_start
b. For each application that contains an application client launched using Java
Web Start, type:
rm -rf domain-dir/generated/xml/app-name/signed
c. Restart GlassFish Server.
5. Ensure that the Java security setting on user systems is set to Very High.
After you perform these steps, the first time a user launches an application client on
their system, Java Web Start detects that the server's signed JARs are newer than those
cached on the user’s system and downloads them again. This happens on the first
launch only, regardless of the client. Even though the application client is now signed
using a trusted certificate, users will again be asked whether to trust the downloaded
application and can choose to skip that prompt for future launches.
For more information about the asadmin deploy command, see the GlassFish Server
Open Source Edition Reference Manual.
Error Handling
When an application client is launched using Java Web Start, any error that the
application client logic does not catch and handle is written to System.err and
displayed in a dialog box. This display appears if an error occurs even before the
application client logic receives control. It also appears if the application client code
does not catch and handle errors itself.
The following example vendor element contains an icon, a splash screen, and a text
string:
<vendor>images/icon.jpg::otherDir/splash.jpg::MyCorp, Inc.</vendor>
The following example vendor element contains an icon and a text string:
<vendor>images/icon.jpg::MyCorp, Inc.</vendor>
The following example vendor element contains a splash screen and a text string; note
the initial double colon:
<vendor>::otherDir/splash.jpg::MyCorp, Inc.</vendor>
10-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
You can also specify a vendor-specific icon, splash screen, text string, or a combination
by using a custom JNLP file; see Creating a Custom JNLP File.
Specifying the JNLP File in the Deployment Descriptor To specify a custom JNLP file for Java
Web Start, use the jnlp-doc element in the glassfish-application-client.xml file. If
none is specified, a default JNLP file is generated.
The value of the jnlp-doc element is a relative path with the following format:
[path-to-JAR-in-EAR!]path-to-JNLP-in-JAR
The default path-to-JAR-in-EAR is the current application client JAR file. For example,
if the JNLP file is in the application client JAR file at custom/myInfo.jnlp, the element
value would look like this:
<java-web-start-access>
<jnlp-doc>custom/myInfo.jnlp</jnlp-doc>
</java-web-start-access>
If the application client is inside an EAR file, you can place the custom JNLP file inside
another JAR file in the EAR. For example, if the JNLP file is in a JAR file at
other/myLib.jar, the element value would look like this, with an exclamation point
(!) separating the path to the JAR from the path in the JAR:
<java-web-start-access>
<jnlp-doc>other/myLib.jar!custom/myInfo.jnlp</jnlp-doc>
</java-web-start-access>
Referring to JAR Files from the JNLP File As with any JNLP document, the custom JNLP
file can refer to JAR files the application client requires.
Do not specify every JAR on which the client depends. GlassFish Server automatically
handles JAR files that the Java EE specification requires to be available to the
application client. This includes JAR files listed in the application client JAR file's
manifest Class-Path and JAR files in the EAR file's library directory (if any) and their
transitive closures. The custom JNLP file should specify only those JAR files the client
needs that GlassFish Server would not otherwise include.
Package these JAR files in the EAR file, as with any JAR file required by an application
client. Use relative URIs in the <jar href="..."> and <nativelib href="...">
elements to point to the JAR files. The codebase that GlassFish Server assigns for the
final client JNLP file corresponds to the top level of the EAR file. Therefore, relative
href references correspond directly to the relative path to the JAR files within the EAR
file.
Neither the Java EE specification nor GlassFish Server supports packaging JAR files
inside the application client JAR file itself. Nothing prevents this, but GlassFish Server
does no special processing of such JAR files. They do not appear in the runtime class
path and they cannot be referenced from the custom JNLP file.
Referring to Other JNLP Files The JNLP file can also refer to other custom JNLP files
using <extension href="..."/> elements. To be consistent with relative href
references to JAR files, the relative href references to JNLP files are resolved within the
EAR file. You can place these JNLP files directly in the EAR file or inside JAR files that
the EAR file contains. Use one of these formats for these href references:
[path-to-JAR-in-EAR!]path-to-JNLP-in-JAR
path-to-JNLP-in-EAR
Note that these formats are not equivalent to the format of the jnlp-doc element in the
glassfish-application-client.xml file.
These formats follow the standard entry-within-a-JAR URI syntax and semantics.
Support for this syntax comes from the automated Java Web Start support in GlassFish
Server. This is not a feature of Java Web Start or the JNLP standard.
Combining Custom and Automatically Generated Content GlassFish Server recognizes these
types of content in the JNLP file:
■ Owned — GlassFish Server owns the content and ignores any custom content
■ Merged — Automatically generated content and custom content are merged
■ Defaulted — Custom content is used if present, otherwise default content is
provided
You can compose a complete JNLP file and package it with the application client.
GlassFish Server then combines it with its automatically generated JNLP file. You can
also provide content that only adds to or replaces what GlassFish Server generates.
The custom content must conform to the general structure of the JNLP format so that
GlassFish Server can properly place it in the final JNLP file.
For example, to specify a single native library to be included only for Windows
systems, the new element to add might be as follows:
<nativelib href="windows/myLib.jar"/>
However, you must indicate where in the overall document this element belongs. The
actual custom JNLP file should look like this:
<jnlp>
<resources os="Windows">
<nativelib href="windows/myLib.jar"/>
</resources>
</jnlp>
10-12 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
own content within those elements with custom content under those elements.
Further, you can provide your own <information> and <resources> elements (and
fragments within them) that specify at least one of these attributes.
In general, you can perform the following customizations:
■ 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 flexibility allows you to add JAR files to the application (including
platform-specific 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 file you can
add to and modify.
10-14 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
or
...
The ACC loads 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 ACC returns. The ACC has 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 know
when the client's asynchronous work completes, the embedding application and the
client must agree on how this happens.
The ACC's shutdown handling is invoked from the 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 VM shutdown if the code has not invoked close before then.
The ACC does not prevent the calling application from creating 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.
as-install/bin directory. For details, see the GlassFish Server Open Source Edition
Reference Manual.
For more information about the glassfish-ejb-jar.xml and sun-acc.xml files, see
the GlassFish Server Open Source Edition Application Deployment Guide.
10-16 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Using the ACC
To use a client certificate, you must also specify the system properties 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 system properties in one of the following
ways:
■ Use the new syntax of the appclient script and specify the system properties as
JVM options. See Running an Application Client Using the appclient Script.
■ 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>
-Dcom.sun.corba.ee.ORBUserConfigurators.com.sun.corba.ee.impl.plugin.hwlb.VirtualA
ddressAgentImpl=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.ORBConfigurator
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 specified for the IIOP port in the GlassFish Server configuration.
10-18 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Without the ACC
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 GlassFish Server Open Source
Edition Reference Manual.
If load balancing is enabled as in Step 6 and the EJB components being accessed
are in a different cluster, the endpoint list must be included in the lookup, as
follows:
corbaname:host1:port1,host2:port2,.../NameService#ejb/jndi-name
For more information about naming and lookups, see Accessing the Naming
Context.
3. Deploy the EJB component to be accessed.
For more information on deployment, see "About Deployment Tools" in GlassFish
Server Open Source Edition Application Deployment Guide.
4. Copy the as-install/lib/gf-client.jar file to the client machine and include it in
the classpath on the client side.
The gf-client.jar file references GlassFish Server JAR files in its MANIFEST.MF
file. If there is no GlassFish Server installation on the client machine, you must also
copy the as-install/modules directory to the client machine and maintain its
directory structure relative to the as-install/lib/gf-client.jar file. Or you can
use the package-appclient script; see Using the package-appclient Script.
5. To access EJB components that are residing in a remote system, set the following
system properties for the Java Virtual Machine startup options:
-Dorg.omg.CORBA.ORBInitialHost=${ORBhost}
-Dorg.omg.CORBA.ORBInitialPort=${ORBport}
Here ORBhost is the GlassFish Server hostname and ORBport is the ORB port
number (default is 3700 for the default server instance, named server).
You can use the asadmin get command to get the IIOP port numbers. For
example:
asadmin get
"configs.config.server-config.iiop-service.iiop-listener.orb-listener-1.*"
6. To set up load balancing and remote EJB reference failover, define the endpoints
property as follows:
-Dcom.sun.appserv.iiop.endpoints=host1:port1,host2:port2,...
10-20 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing Clients Without the ACC
If the endpoints list is changed dynamically in the code, the new list is used only
if a new InitialContext is created.
2. In the module code, look up the home object by specifying the JNDI name of the
home object.
Here is an EJB 2.x example:
Object ref = ctx.lookup("jndi-name");
BeanAHome = (BeanAHome)PortableRemoteObject.narrow(ref,BeanAHome.class);
If load balancing is enabled as in Step 1 and the EJB components being accessed
are in a different cluster, the endpoint list must be included in the lookup, as
follows:
corbaname:host1:port1,host2:port2,.../NameService#ejb/jndi-name
For more information about naming and lookups, see Accessing the Naming
Context.
3. Deploy the EJB component to be accessed.
For more information on deployment, see "About Deployment Tools" in GlassFish
Server Open Source Edition Application Deployment Guide.
4. To access EJB components that are residing in a remote system, set the following
system properties for the Java Virtual Machine startup options:
-Dorg.omg.CORBA.ORBInitialHost=${ORBhost}
-Dorg.omg.CORBA.ORBInitialPort=${ORBport}
Here ORBhost is the Application Server hostname and ORBport is the ORB port
number (default is 3700 for the default server instance, named server).
5. Deploy the module.
For more information on deployment, see "About Deployment Tools" in GlassFish
Server Open Source Edition Application Deployment Guide.
Here ORBhost is the Application Server hostname and ORBport is the ORB port
number (default is 3700 for the default server instance, named server).
You can use the asadmin get command to get the IIOP port numbers. For
example:
asadmin get
"configs.config.server-config.iiop-service.iiop-listener.orb-listener-1.*"
10-22 GlassFish Server Open Source Edition 4.0 Application Development Guide
11
Developing Connectors
11
This chapter describes Oracle GlassFish Server support for the Java EE 1.6 Connector
Architecture, also known as JSR 322 (http://jcp.org/en/jsr/detail?id=322).
The Java EE Connector Architecture provides a Java solution to the problem of
connectivity between multiple application servers and existing enterprise information
systems (EISs). By using the Java EE Connector architecture, EIS vendors no longer
need to customize their product for each application server. Application server
vendors who conform to the Java EE Connector architecture do not need to write
custom code to add connectivity to a new EIS.
This chapter uses the terms connector and resource adapter interchangeably. Both terms
refer to a resource adapter module that is developed in conformance with the Java EE
Connector Architecture Specification.
Note: If you installed the Web Profile, connector modules that use
only outbound communication features and work-management
that does not involve inbound communication features are
supported. Other connector features are supported only in the full
GlassFish Server.
Connector Configuration
The GlassFish Server does not need to use sun-ra.xml, which previous GlassFish
Server versions used, to store server-specific deployment information inside a
Resource Adapter Archive (RAR) file. (However, the sun-ra.xml file is still supported
for backward compatibility.) Instead, the information is stored in the server
11-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Connector Configuration Options
configuration. As a result, you can create multiple connector connection pools for a
connection definition 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.
Thread Associations
Connectors can submit work instances to the GlassFish Server for execution. By
default, the GlassFish Server services work requests for all connectors from its default
thread pool. However, you can associate a specific user-created thread pool to service
work requests from a connector. A thread pool can service work requests from
multiple resource adapters. To create a thread pool:
■ In the Administration Console, select Thread Pools under the relevant
configuration. For details, click the Help button in the Administration Console.
■ Use the asadmin create-threadpool command. For details, see the GlassFish
Server Open Source Edition Reference Manual.
To associate a connector with a thread pool:
■ In the Administration Console, open the Applications component and select
Resource Adapter Configs. Specify the name of the thread pool in the Thread Pool
ID field. For details, click the Help button in the Administration Console.
■ Use the --threadpoolid option of the asadmin create-resource-adapter-config
command. For details, see the GlassFish Server Open Source Edition Reference
Manual.
If you create a resource adapter configuration for a connector module that is already
deployed, the connector module deployment is restarted with the new configuration
properties.
Security Maps
Create a security map for a connector connection pool to map an application principal
or a user group to a back end EIS principal. The security map is usually used in
situations where one or more EIS back end principals are used to execute operations
(on the EIS) initiated by various principals or user groups in the application.
To create or update security maps for a connector connection pool:
■ 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
GlassFish Server Open Source Edition Reference Manual.
If a security map already exists for a connector connection pool, the new security map
is appended to the previous one. The connector security map configuration 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 first
checks for an exact match to a mapped back end EIS principal using the security map
defined for the connector connection pool. If there is no exact match, the GlassFish
Server uses the wild card character specification, if any, to determined the mapped
back end EIS principal.
11-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Connector Configuration Options
You can specify configuration properties either before or after resource adapter
deployment. If you specify properties after deploying the resource adapter, the
existing resource adapter is restarted with the new properties.
You can also use token replacement for overriding resource adapter configuration
properties in individual server instances when the resource adapter is deployed to a
cluster. For example, for a property called inboundPort, you can assign the value
${inboundPort}. You can then assign a different value to this property for each server
instance. Changes to system properties take effect upon server restart.
finds 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 configuration 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 specifies whether connections have
to be validated before being given to the application. If a resource's validation fails, it
is destroyed, and a new resource is created and returned. The default is false.
The prefer-validate-over-recreate property specifies that validating idle
connections is preferable to closing them. This property has no effect 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 configuration settings during creation of a connector
connection pool. Or, you can use the asadmin set command to dynamically
reconfigure 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-recr
eate="true"
For details, see the GlassFish Server Open Source Edition Reference Manual.
The interface ValidatingManagedConnectionFactory exposes the method
getInvalidConnections to allow retrieval 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.
For details, see the GlassFish Server Open Source Edition Reference Manual.
The GlassFish Server deactivates all message-driven bean deployments before
stopping a resource adapter.
11-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Advanced Connector Configuration Options
For details, see the GlassFish Server Open Source Edition Reference Manual.
11-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring a Message Driven Bean to Use a Resource Adapter
When the message-driven bean is deployed, the value for the resource-adapter-mid
element in the glassfish-ejb-jar.xml file is set to the resource adapter module name
that delivers messages to the message endpoint (to the message-driven bean). In the
following example, the jmsra JMS resource adapter, which is the bundled resource
adapter for the Message Queue message provider, is specified as the resource adapter
module identifier for the SampleMDB bean.
<glassfish-ejb-jar>
<enterprise-beans>
<unique-id>1</unique-id>
<ejb>
<ejb-name>SampleMDB</ejb-name>
<jndi-name>SampleQueue</jndi-name>
<!-- JNDI name of the destination from which messages would be
delivered from MDB needs to listen to -->
...
<mdb-resource-adapter>
<resource-adapter-mid>jmsra</resource-adapter-mid>
<!-- Resource Adapter Module Id that would deliver messages to
this message endpoint -->
</mdb-resource-adapter>
...
</ejb>
...
</enterprise-beans>
...
</glassfish-ejb-jar>
When the message-driven bean is deployed, the GlassFish Server uses the
resourceadapter-mid setting to associate the resource adapter with a message
endpoint through the message inflow contract. This message inflow contract with the
GlassFish Server gives the resource adapter a handle to the MessageEndpointFactory
and the ActivationSpec JavaBean, and the adapter uses this handle to deliver
messages to the message endpoint instances (which are created by the
MessageEndpointFactory).
When a message-driven bean first created for use on the GlassFish Server 7 is
deployed, the Connector runtime transparently transforms the previous deployment
style to the current connector-based deployment style. If the deployer specifies neither
a resource-adapter-mid element nor the Message Queue resource adapter's activation
configuration properties, the Connector runtime maps the message-driven bean to the
jmsra system resource adapter and converts the JMS-specific configuration to the
Message Queue resource adapter's activation configuration properties.
11-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
12
Developing Lifecycle Listeners
12
12-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Considerations for Lifecycle Modules
■ 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. A lifecycle 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.
12-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
13
Developing OSGi-enabled Java EE
13
Applications
This chapter describes the features and interfaces that GlassFish Server provides to
develop OSGi-enabled enterprise applications. This chapter includes the following
sections:
■ Overview of OSGi Application and GlassFish Server
■ Developing OSGi Application Bundles for GlassFish Server
■ Deploying OSGi Bundles in GlassFish Server
13-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing OSGi Application Bundles for GlassFish Server
HTTP Service
The GlassFish Server web container is made available as a service for OSGi users who
do not use OSGi Web Application Bundles (WABs). This service is made available
using the standard OSGi/HTTP service specification, which is a light API that
predates the concept of a web application as we know it today. This simple API allows
users to register servlets and static resources dynamically and draw a boundary
around them in the form of a HttpContext. This simple API can be used to build
feature-rich web application, such as the Felix Web Console for example.
The GlassFish Server web container has one or more virtual servers. A virtual server
has one or more web application deployed in it. Each web application has a distinct
context path. Each virtual server has a set of HTTP listeners. Each HTTP listener
listens on a particular port. When multiple virtual servers are present, one of them is
treated as the default virtual server. Every virtual server comes configured with a
default web application. The default web application is used to serve static content
from the docroot of GlassFish Server. This default web application uses / as the
context path. A web application contains static and dynamic resources. Each virtual
server is mapped to an org.osgi.services.http.HttpService instance. When there
are multiple virtual servers present, there will be multiple occurrences of HttpService
registered in the service registry. In order to distinguish one service from another, each
service is registered with a service property named VirtualServer, whose value is the
name of the virtual server. The service corresponding to default virtual server has the
highest ranking, so when looking up a service of type HttpService without any
additional criteria returns the HttpService corresponding to the default virtual server.
In a typical GlassFish Server installation, the default virtual server is configured to
listen on port 8080 for the HTTP protocol and port 8181 for the HTTPS protocol.
The context path / is reserved for the default web application. Every resource and
servlet registered using the registerResource() and registerServlet() methods of
HttpService are made available under a special context path named /osgi in the
virtual server. The /osgi context path can be changed to some other value by setting
an appropriate value in the OSGi configuration property or in a system property called
org.glassfish.osgihttp.ContextPath.
For example, HelloWorldServlet will be available at
http://localhost:8080/osgi/helloworld when the following code is executed:
Transaction Service
The Java Transaction API (JTA) defines three interfaces to interact with the transaction
management system: UserTransaction, TransactionManager, and
TransactionSynchronizationRegistry. They all belong to the javax.transaction
package. TransactionManagerand TransactionSynchronizationRegistry are
intended for system level code, such as a persistence provider. Whereas,
UserTransaction is the entity that you should use to control transactions. All the
objects of the underlying JTA layer are made available in the OSGi service registry
using the following service interfaces:
■ 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 JTA
artifacts, then they can look it up in the service registry. Here is an example of such
code:
BundleContext context;
ServiceReference txRef =
context.getServiceReference(UserTransaction.class.getName());
UserTransaction utx = (UserTransaction);
context.getService(txRef);
13-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing OSGi Application Bundles for GlassFish Server
@Inject
@OSGiService(true,
"(jndi-name=jdbc/MyDS)")
private DataSource ds;
Service
JMS Object Service Interface Properties Comments
JMS Queue javax.jms.Queue jndi-name jndi-name is set to the JNDI name of the
destination queue
JMS Topic javax.jms.Topic jndi-name jndi-name is set to the JNDI name of the
destination topic
JMS javax.jms.QueueConnectionFactory or jndi-name jndi-name is set to the JNDI name of the
connection javax.jms.TopicConnectionFactory or topic.
factory javax.jms.ConnectionFactory
The actual service interface depends on
which type of connection factory was
created.
foo.war/
index.html
foo.jsp
WEB-INF/classes/
foo/BarServlet.class
WEB-INF/lib/lib1.jar
WEB-INF/lib/lib2.jar
Then the OSGi metadata for the WAB as specified in META-INF/MANIFEST.MF of the
WAB would appear as follows:
MANIFEST.MF:Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-SymbolicName: com.acme.foo
Bundle-Version: 1.0
Bundle-Name: Foo Web Application Bundle Version 1.0
Import-Package: javax.servlet; javax.servlet.http, version=[3.0, 4.0)
Bundle-ClassPath: WEB-INF/classes, WEB-INF/lib/lib1.jar, WEB-INF/lib/lib2.jar
Web-ContextPath: /foo
@WebServlet
public class MyServlet extends HttpServlet {
@Inject @OSGiService(dynamic=true)
FooService fooService;
}
To learn more about this feature, refer to OSGi CDI Extension for WABs.
13-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Developing OSGi Application Bundles for GlassFish Server
metadata to customize the service discovery and injection behavior. The following
@OsgiService attributes are currently available:
■ serviceCriteria — An LDAP filter query used for service selection in the OSGi
service registry.
■ waitTimeout — Waits the specified duration for a service that matches the criteria
specified to appear in the OSGi service registry.
■ dynamic — Dynamically obtain a service reference (true/false).
Since OSGi services are dynamic, they may not match the life cycle of the
application component that has injected a reference to the service. Through this
attribute, you could indicate that a service reference can be obtained dynamically
or not. For stateless or idempotent services, a dynamic reference to a service
implementation would be useful. The container then injects a proxy to the service
and dynamically switches to an available implementation when the current
service reference is invalid.
@Servlet
public void BarServlet extends HttpServlet{
@Inject @OSGiService(dynamic=true)
private com.acme.Foo f;
}
myEjb.jar/
com/acme/Foo
com/acme/impl/FooEJB
META-INF/MANIFEST.MF
MANIFEST.MF:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-SymbolicName: com.acme.foo EJB bundle
Bundle-Version: 1.0.0.BETA
Bundle-Name: com.acme.foo EJB bundle version 1.0.0.BETA
Export-EJB: ALL
Export-Package: com.acme; version=1.0
Import-Package: javax.ejb; version=[3.0, 4.0), com.acme; version=[1.0, 1.1)
@Stateless
public class MyEJB {
@Inject @OSGiService(dynamic=true)
Foo foo;
...
}
To learn more about this feature, refer to Using the OSGi CDI Extension With EJB
Bundles.
13-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Part III
Part III Using Services and APIs
14
Using the JDBC API for Database Access
14
This chapter describes how to use the Java Database Connectivity (JDBC) API for
database access with the Oracle GlassFish Server. This chapter also provides high level
JDBC implementation instructions for servlets and EJB components using the
GlassFish Server. If the JDK version 1.6 is used, the GlassFish Server supports the
JDBC 4.0 API.
The JDBC specifications are available at
http://www.oracle.com/technetwork/java/javase/jdbc/index.html.
A useful JDBC tutorial is located at
http://download.oracle.com/javase/tutorial/jdbc/index.html.
Statements
The following topics are addressed here:
■ Using an Initialization Statement
■ Setting a Statement Timeout
■ Statement Leak Detection and Leaked Statement Reclamation
■ Statement Caching
■ Statement Tracing
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
14-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Statements
When selecting a value for Statement Leak Timeout In Seconds, make sure that:
■ 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 Reclaim Leaked Statements for the JDBC connection pool to a true value in one
of the following ways:
■ Specify the --statementleakreclaim=true option in the
create-jdbc-connection-pool subcommand. For more information, see
create-jdbc-connection-pool(1).
■ Specify the statement-leak-reclaim option in the set subcommand. For
example:
asadmin set
resources.jdbc-connection-pool.pool-name.statement-leak-reclaim=true
Statement Caching
Statement caching stores statements, prepared statements, and callable statements that
are executed repeatedly by applications in a cache, thereby improving performance.
Instead of the statement being prepared each time, the cache is searched for a match.
The overhead of parsing and creating new statements each time is eliminated.
Statement caching is usually a feature of the JDBC driver. The GlassFish Server
provides caching for drivers that do not support caching. To enable this feature, set the
Statement Cache Size for the JDBC connection pool 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 --statementcachesize option in the asadmin
create-jdbc-connection-pool command. For more information, see the GlassFish
Server Open Source Edition Reference Manual.
■ 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 GlassFish Server Open Source Edition Reference
Manual.
By default, this attribute is set to zero and the statement caching is turned off. 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
flushed, the connections in the statement cache are recreated.
Statement Tracing
You can trace the SQL statements executed by applications that use a JDBC connection
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 --sqltracelisteners option in the asadmin
create-jdbc-connection-pool command. For more information, see the GlassFish
Server Open Source Edition Reference Manual.
■ 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 GlassFish Server Open Source Edition Reference
Manual.
The GlassFish Server provides a public interface,
org.glassfish.api.jdbc.SQLTraceListener , that implements a means of recording
SQLTraceRecord objects. To make custom implementations 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
form of SQLTraceRecord objects in the server.log file. The module name under which
the SQL operation is logged is javax.enterprise.resource.sqltrace. SQL traces are
logged as FINE messages along with the module name to enable easy filtering of the
SQL logs. A sample SQL trace record looks like this:
[#|2009-11-27T15:46:52.202+0530|FINE|glassfishv3.0|javax.enterprise.resource.sqltr
ace.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 | |#]
time-to-keep-queries-in-minutes
Specifies how long 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
Specifies how many 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 them as properties in the Edit JDBC Connection Pool Properties page in the
Administration Console. For more information, click the Help button in the
Administration Console.
■ Specify them using the --property option in the create-jdbc-connection-pool
subcommand. For more information, see create-jdbc-connection-pool(1).
14-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Connections
Connections
The following topics are addressed here:
■ Transparent Pool Reconfiguration
■ Disabling Pooling
■ Associating Connections with Threads
■ Custom Connection Validation
■ Sharing Connections
■ Marking Bad Connections
■ Handling Invalid Connections
This property specifies the time in seconds to wait for in-use connections to close and
in-flight transactions to complete. Any connections in use or transaction in flight past
this time must be retried.
Disabling Pooling
To disable connection pooling, set the Pooling attribute to false. The default is true.
You can enable or disable connection pooling in one of the following ways:
■ 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 create-jdbc-connection-pool
command. For more information, see the GlassFish Server Open Source Edition
Reference Manual.
■ Specify the pooling option in the asadmin set command. For example:
asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.pooling=false
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
The pooling option and the system property
com.sun.enterprise.connectors.SwitchoffACCConnectionPooling, which turns off
connection pooling in the Application Client Container, do not affect 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 flush 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
14-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Connections
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
By default, optimized validation mechanisms are provided for DB2, Java DB, MSSQL,
MySQL, Oracle, PostgreSQL and Sybase databases. Additionally, for JDBC 4.0
compliant database drivers, a validation mechanism is provided that uses the
Connection.isValid(0) implementation.
Sharing Connections
When multiple connections acquired by an application use the same JDBC resource,
the connection pool provides connection sharing within the same transaction scope.
For example, suppose Bean A starts a transaction and obtains a connection, then calls a
method in Bean B. If Bean B acquires a connection to the same JDBC resource with the
same sign-on information, and if Bean A completes the transaction, the connection can
be shared.
Connections obtained through a resource are shared only if the resource reference
declared by the Java EE component allows it to be shareable. This is specified in a
component's deployment descriptor by setting the res-sharing-scope element to
Shareable for the particular resource reference. To turn off connection sharing, set
res-sharing-scope to Unshareable.
For general information about connections and JDBC URLs, see "Administering
Database Connectivity" in GlassFish Server Open Source Edition Administration Guide.
For example:
com.sun.appserv.jdbc.DataSource ds=
(com.sun.appserv.jdbc.DataSource)context.lookup("dataSource");
Connection con = ds.getConnection();
Statement stmt = null;
try{
stmt = con.createStatement();
stmt.executeUpdate("Update");
}
catch (BadConnectionException e){
ds.markConnectionAsBad(con) //marking it as bad for removal
}
finally{
stmt.close();
con.close(); //Connection will be destroyed during close.
}
14-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Connection Wrapping
For details, see the GlassFish Server Open Source Edition Reference Manual.
The interface ValidatingManagedConnectionFactory exposes the method
getInvalidConnections to allow retrieval of the invalid connections. The GlassFish
Server checks if the JDBC driver implements this interface, and if it does, invalid
connections are removed when the connection pool is resized.
Connection Wrapping
The following topics are addressed here:
■ Wrapping Connections
■ Obtaining a Physical Connection From a Wrapped Connection
■ Using the Connection.unwrap() Method
Wrapping Connections
If the Wrap JDBC Objects option is true (the default), wrapped JDBC objects are
returned for Statement, PreparedStatement, CallableStatement, ResultSet, and
DatabaseMetaData.
This option ensures that Statement.getConnection() is the same as
DataSource.getConnection(). Therefore, this option should be true when both
Statement.getConnection() and DataSource.getConnection() are done.
You can specify the Wrap JDBC Objects option in the following ways:
■ Check or uncheck the Wrap JDBC Objects box on the Edit Connection Pool
Advanced Attributes page in the Administration Console. For more information,
click the Help button in the Administration Console.
■ Specify the --wrapjdbcobjects option in the asadmin
create-jdbc-connection-pool command. For more information, see the GlassFish
Server Open Source Edition Reference Manual.
For example:
InitialContext ctx = new InitialContext();
com.sun.appserv.jdbc.DataSource ds = (com.sun.appserv.jdbc.DataSource)
ctx.lookup("jdbc/MyBase");
Connection con = ds.getConnection();
Connection drivercon = ds.getConnection(con); //get physical connection from
wrapper
// Do db operations.
// Do not close driver connection.
con.close(); // return wrapped connection to pool.
14-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
Restrictions and Optimizations
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
■ Create a JDBC resource with a __pm suffix.
Accessing a DataSource using the Synchronization.beforeCompletion() method
requires setting Allow Non Component Callers to true. For more information about
the Transaction Synchronization Registry, see The Transaction Manager, the
Transaction Synchronization Registry, and UserTransaction.
14-12 GlassFish Server Open Source Edition 4.0 Application Development Guide
15
Using the Transaction Service
15
By default, the transaction isolation level is undefined (empty), and the JDBC driver's
default isolation level is used. You can specify the transaction isolation level in the
following ways:
■ Select the value from the Transaction Isolation drop-down list on the New JDBC
Connection Pool or Edit Connection Pool page in the Administration Console. For
more information, click the Help button in the Administration Console.
■ Specify the --isolationlevel option in the asadmin
create-jdbc-connection-pool command. For more information, see the GlassFish
Server Open Source Edition Reference Manual.
■ Specify the transaction-isolation-level option in the asadmin set command.
For example:
asadmin set
domain1.resources.jdbc-connection-pool.DerbyPool.transaction-isolation-level=se
rializable
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
Note that you cannot call setTransactionIsolation during a transaction.
You can set the default transaction isolation level for a JDBC connection pool. For
details, see "To Create a JDBC Connection Pool" in GlassFish Server Open Source Edition
Administration Guide.
To verify that a level is supported by your database management system, test your
database programmatically using the supportsTransactionIsolationLevel method
in java.sql.DatabaseMetaData, as shown in the following example:
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("jdbc/MyBase");
Connection con = ds.getConnection();
DatabaseMetaData dbmd = con.getMetaData();
if (dbmd.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE)
{ Connection.setTransactionIsolation(TRANSACTION_SERIALIZABLE); }
For more information about these isolation levels and what they mean, see the JDBC
API specification.
Setting or resetting the transaction isolation level for every getConnection call can
degrade performance. So by default the isolation level is not guaranteed.
15-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Handling Transactions with Databases
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
For more information, see the GlassFish Server Open Source Edition Reference
Manual.
■ Use the DataSource implementation in the GlassFish Server, which provides a
getNonTxConnection method. This method retrieves a JDBC connection that is not
in the scope of any transaction. There are two variants.
public java.sql.Connection getNonTxConnection() throws java.sql.SQLException
■ Create a resource with the JNDI name ending in __nontx. This forces all
connections looked up using this resource to be non transactional.
Flat Transactions
The Enterprise JavaBeans Specification, v3.0 requires support for flat (as opposed to
nested) transactions. In a flat transaction, each transaction is decoupled from and
independent of other transactions in the system. Another transaction cannot start in
the same thread until the current transaction ends.
Flat transactions are the most prevalent model and are supported by most commercial
database systems. Although nested transactions offer a finer granularity of control
over transactions, they are supported by far fewer commercial database systems.
15-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Handling Transactions with Enterprise Beans
Commit Options
The EJB protocol is designed to give the container the flexibility to select the
disposition of the instance state at the time a transaction is committed. This allows the
container to best manage caching an entity object's state and associating an entity
object identity with the EJB instances.
There are three commit-time options:
■ 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 instance's state from
the persistent storage at the beginning of the next transaction.
■ 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 instance's 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 C looks
like this.
ejbActivate ejbLoad business method ejbStore ejbPassivate
If there is more than one transactional client concurrently accessing the same
entity, the first client gets the ready instance and subsequent concurrent clients get
new instances from the pool.
The glassfish-ejb-jar.xml deployment descriptor has an element, commit-option,
that specifies the commit option to be used. Based on the specified commit option, the
appropriate handler is instantiated.
15-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
16
Using the Java Naming and Directory
16
Interface
A naming service maintains a set of bindings, which relate names to objects. The Java
EE naming service is based on the Java Naming and Directory Interface (JNDI) API.
The JNDI API allows application components and clients to look up distributed
resources, services, and EJB components. For general information about the JNDI API,
see http://www.oracle.com/technetwork/java/jndi/index.html. You can
also see the JNDI tutorial at
http://download.oracle.com/javase/jndi/tutorial/.
The following topics are addressed here:
■ Accessing the Naming Context
■ Configuring Resources
■ Using a Custom jndi.properties File
■ Mapping References
Note: The Web Profile of the GlassFish Server supports the EJB 3.1
Lite specification, which allows enterprise beans within web
applications, among other features. The full GlassFish Server
supports the entire EJB 3.1 specification. For details, see JSR 318
(http://jcp.org/en/jsr/detail?id=318).
16-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Accessing the Naming Context
– For an EJB 3.0 dependency or a session bean with a remote interface, the
default is the fully qualified name of the remote business interface.
– If both EJB 2.x and EJB 3.0 remote interfaces are specified, or if more than
one 3.0 remote interface is specified, there is no GlassFish Server
V2-specific default. For an entity bean, a global JNDI name must be
assigned.
■ 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.
false
Enables the automatic use of GlassFish Server V2-specific JNDI names in addition to
portable global JNDI names. This is the default setting.
true
Disables the automatic use of V2-specific JNDI names. In all cases, only portable global
JNDI names are used.
Note that this setting applies to all session beans deployed to the server.
For details about asadmin create-jvm-options, see the GlassFish Server Open Source
Edition Reference Manual.
Or you can set this property in the code, as follows:
This makes the programming model for accessing EJB components in another
GlassFish Server exactly the same as accessing them in 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 difference is that the deployer maps the ejb-ref element to an
interoperable name in a GlassFish Server deployment descriptor file 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:
<ejb-ref>
<ejb-ref-name>ejb/Foo</ejb-ref-name>
<jndi-name>corbaname:iiop:host:port#a/b/Foo</jndi-name>
</ejb-ref>
For a client that doesn't 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");
16-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring Resources
Configuring Resources
The GlassFish Server exposes special resources in the naming environment.
■ External JNDI Resources
■ Custom Resources
■ Built-in Factories for Custom Resources
■ Using Application-Scoped Resources
Custom Resources
A custom resource specifies a custom server-wide resource object factory that
implements the javax.naming.spi.ObjectFactory interface. There is no specific JNDI
parent context for external JNDI resources, except for the standard java:comp/env/.
Create a custom resource in one of these ways:
■ To create a custom resource using the Administration Console, open the Resources
component, open the JNDI component, and select Custom Resources. For details,
click the Help button in the Administration Console.
■ To create a custom resource, use the asadmin create-custom-resource command.
For details, see the GlassFish Server Open Source Edition Reference Manual.
JavaBeanFactory
To create a custom resource that provides instances of a JavaBean class, follow these
steps:
1. Set the custom resource's factory class to
org.glassfish.resources.custom.factory.JavaBeanFactory.
2. Create a property in the custom resource for each setter method in the JavaBean
class.
For example, if the JavaBean class has a method named setAccount, specify a
property named account and give it a value.
3. Make sure the JavaBean class is accessible to the GlassFish Server.
For example, you can place the JavaBean class in the as-install/lib directory.
PropertiesFactory
To create a custom resource that provides properties to applications, set the custom
resource's factory class to
org.glassfish.resources.custom.factory.PropertiesFactory, then specify one or
both of the following:
■ Create a property in the custom resource named
org.glassfish.resources.custom.factory.PropertiesFactory.fileName and
specify as its value the path to a properties file or an XML file.
The path can be absolute or relative to as-install. The file must be accessible to the
GlassFish Server.
If an XML file is specified, it must match the document type definition (DTD)
specified in the API definition of java.util.Properties
(http://download.oracle.com/javase/6/docs/api/java/util/Prope
rties.html).
■ Create the desired properties directly as properties of the custom resource.
If both the fileName property and other properties are specified, the resulting
property set is the union. If the same property is defined in the file and directly in
the custom resource, the value of the latter takes precedence.
PrimitivesAndStringFactory
To create a custom resource that provides Java primitives to applications, follow these
steps:
16-6 GlassFish Server Open Source Edition 4.0 Application Development Guide
Configuring Resources
URLFactory
To create a custom resource that provides URL instances to applications, follow these
steps:
1. Set the custom resource's factory class to
org.glassfish.resources.custom.factory.URLObjectFactory.
2. Choose which of the following constructors to use:
■ URL(protocol, host, port, file)
■ URL(protocol, host, file)
■ URL(spec)
3. Define properties according to the chosen constructor.
For example, for the first constructor, define properties named protocol, host,
port, and file. Example values might be http, localhost, 8085, and index.html,
respectively.
For the third constructor, define a property named spec and assign it the value of
the entire URL.
Mapping References
The following XML elements in the GlassFish Server deployment descriptors map
resource references in application client, EJB, and web application components to JNDI
names configured in GlassFish Server:
■ resource-env-ref - Maps the @Resource or @Resources annotation (or the
resource-env-ref element in the corresponding Java EE XML file) to the absolute
JNDI name configured in GlassFish Server.
■ resource-ref - Maps the @Resource or @Resources annotation (or the
resource-ref element in the corresponding Java EE XML file) to the absolute
JNDI name configured in GlassFish Server.
■ ejb-ref - Maps the @EJB annotation (or the ejb-ref element in the corresponding
Java EE XML file) to the absolute JNDI name configured in 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.
These elements are part of the glassfish-web.xml,
glassfish-application-client.xml, glassfish-ejb-jar.xml, and
glassfish-application.xml deployment descriptor files. For more information about
how these elements behave in each of the deployment descriptor files, see "Elements of
the GlassFish Server Deployment Descriptors" in GlassFish Server Open Source Edition
Application Deployment Guide.
The rest of this section uses an example of a JDBC resource lookup to describe how to
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 JDBC resource configured in the GlassFish Server, the annotation
alone is enough to reference the resource.
However, you can use a GlassFish Server specific deployment descriptor to override
the annotation. For example, the resource-ref element in the glassfish-web.xml file
maps the res-ref-name (the name specified in the annotation) to the JNDI name of
another JDBC resource configured in GlassFish Server.
<resource-ref>
<res-ref-name>jdbc/helloDbDs</res-ref-name>
<jndi-name>jdbc/helloDbDataSource</jndi-name>
</resource-ref>
16-8 GlassFish Server Open Source Edition 4.0 Application Development Guide
Mapping References
16-10 GlassFish Server Open Source Edition 4.0 Application Development Guide
17
Using the Java Message Service
17
This chapter describes how to use the Java Message Service (JMS) API. The Oracle
GlassFish Server has a fully integrated JMS provider: the Open Message Queue
software.
For information about the JMS API, see "Java Message Service Concepts" in The Java EE
7 Tutorial and "Java Message Service Examples" in The Java EE 7 Tutorial.
For detailed information about JMS concepts and JMS support in the GlassFish Server,
see "Administering the Java Message Service (JMS)" in GlassFish Server Open Source
Edition Administration Guide.
For more information about Message Queue software, see the Open Message Queue
Administration Guide.
The following topics are addressed here:
■ Using Application-Scoped JMS Resources
■ Load-Balanced Message Inflow
■ Authentication With ConnectionFactory
■ Delivering SOAP Messages Using the JMS API
17-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Delivering SOAP Messages Using the JMS API
This is the utility whose methods you use to convert SOAP messages to JMS
messages and the reverse. You can then send a JMS message containing a SOAP
payload as if it were a normal JMS message.
2. Initialize the TopicConnectionFactory, TopicConnection, TopicSession, and
publisher.
tcf = new TopicConnectionFactory();
tc = tcf.createTopicConnection();
session = tc.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
topic = session.createTopic(topicName);
publisher = session.createPublisher(topic);
3. Construct a SOAP message using the SOAP with Attachments API for Java
(SAAJ).
/*construct a default soap MessageFactory */
MessageFactory mf = MessageFactory.newInstance();
* Create a SOAP message object.*/
SOAPMessage soapMessage = mf.createMessage();
/** Get SOAP part.*/
SOAPPart soapPart = soapMessage.getSOAPPart();
/* Get SOAP envelope. */
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
/* Get SOAP body.*/
SOAPBody soapBody = soapEnvelope.getBody();
/* Create a name object. with name space */
/* http://www.sun.com/imq. */
Name name = soapEnvelope.createName("HelloWorld", "hw",
"http://www.sun.com/imq");
* Add child element with the above name. */
SOAPElement element = soapBody.addChildElement(name)
/* Add another child element.*/
element.addTextNode( "Welcome to GlassFish Web Services." );
/* Create an atachment with activation API.*/
URL url = new URL ("http://java.sun.com/webservices/");
DataHandler dh = new DataHandler (url);
AttachmentPart ap = soapMessage.createAttachmentPart(dh);
/*set content type/ID. */
ap.setContentType("text/html");
ap.setContentId("cid-001");
/** add the attachment to the SOAP message.*/
soapMessage.addAttachmentPart(ap);
soapMessage.saveChanges();
This is the utility whose methods you use to convert SOAP messages to JMS
messages and the reverse. The JMS message containing the SOAP payload is
received as if it were a normal JMS message.
2. Initialize the TopicConnectionFactory, TopicConnection, TopicSession,
TopicSubscriber, and Topic.
messageFactory = MessageFactory.newInstance();
tcf = new com.sun.messaging.TopicConnectionFactory();
tc = tcf.createTopicConnection();
session = tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
topic = session.createTopic(topicName);
subscriber = session.createSubscriber(topic);
subscriber.setMessageListener(this);
tc.start();
17-4 GlassFish Server Open Source Edition 4.0 Application Development Guide
18
Using the JavaMail API
18
This chapter describes how to use the JavaMail API, which provides a set of abstract
classes defining objects that comprise a mail system.
The following topics are addressed here:
■ Introducing JavaMail
■ Creating a JavaMail Session
■ JavaMail Session Properties
■ Looking Up a JavaMail Session
■ Sending and Reading Messages Using JavaMail
■ Using Application-Scoped JavaMail Resources
Introducing JavaMail
The JavaMail API defines classes such as Message, Store, and Transport. The API can
be extended and can be subclassed to provide new protocols and to add functionality
when necessary. In addition, the API provides concrete subclasses of the abstract
classes. These subclasses, including MimeMessage and MimeBodyPart, implement
widely used Internet mail protocols and conform to the RFC822 and RFC2045
specifications. The JavaMail API includes support for the IMAP4, POP3, and SMTP
protocols.
The JavaMail architectural components are as follows:
■ 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.
■ 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 "Administering the JavaMail Service" in GlassFish Server
Open Source Edition Administration Guide and the JavaMail specification at
http://www.oracle.com/technetwork/java/javamail/index.html. A
useful JavaMail tutorial is located at
http://java.sun.com/developer/onlineTraining/JavaMail/.
For more information about the JNDI API, see Using the Java Naming and Directory
Interface.
18-2 GlassFish Server Open Source Edition 4.0 Application Development Guide
Sending and Reading Messages Using JavaMail
import javax.mail.internet.*;
import javax.naming.*;
4. Create a MimeMessage.
The msgRecipient, msgSubject, and msgTxt variables in the following example
contain input from the user:
Message msg = new MimeMessage(session);
msg.setSubject(msgSubject);
msg.setSentDate(new Date());
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(msgRecipient, false));
msg.setText(msgTxt);
4. Get a Store object from the Session, then connect to the mail server using the
Store object's connect method.
You must supply a mail server name, a mail user name, and a password.
Store store = session.getStore();
store.connect("MailServer", "MailUser", "secret");
6. It is efficient to read the Message objects (which represent messages on the server)
into an array.
Message[] messages = folder.getMessages();
18-4 GlassFish Server Open Source Edition 4.0 Application Development Guide