Eclipse GlassFish Application Development Guide, Release 7

This Application Development Guide describes how to create and run Java Platform, Enterprise Edition (Jakarta EE platform) applications that follow the open Java standards model for Jakarta EE components and APIs in the Eclipse GlassFish environment. Topics include developer tools, security, and debugging. This book is intended for use by software developers who create, assemble, and deploy Jakarta EE applications using Oracle servers and software.

Eclipse GlassFish Application Development Guide, Release 7

Copyright © 2013, 2019 Oracle and/or its affiliates. All rights reserved.

This program and the accompanying materials are made available under the terms of the Eclipse Public License v. 2.0, which is available at http://www.eclipse.org/legal/epl-2.0.

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.

2. Preface

This documentation is part of the Java Enterprise Edition contribution to the Eclipse Foundation and is not intended for use in relation to Java Enterprise Edition or Orace GlassFish. The documentation is in the process of being revised to reflect the new Jakarta EE branding. Additional changes will be made as requirements and procedures evolve for Jakarta EE. Where applicable, references to Jakarta EE or Java Enterprise Edition should be considered references to Jakarta EE.

Please see the Title page for additional license information.

This Application Development Guide describes how to create and run Java Platform, Enterprise Edition (Jakarta EE platform) applications that follow the open Java standards model for Jakarta EE components and APIs in the Eclipse GlassFish environment. Topics include developer tools, security, and debugging. This book is intended for use by software developers who create, assemble, and deploy Jakarta EE applications using Eclipse GlassFishs.

This preface contains information about and conventions for the entire Eclipse GlassFish (Eclipse GlassFish) documentation set.

Eclipse GlassFish 7 is developed through the GlassFish project open-source community at https://github.com/eclipse-ee4j/glassfish. The GlassFish project provides a structured process for developing the Eclipse GlassFish platform that makes the new features of the Jakarta EE platform available faster, while maintaining the most important feature of Jakarta EE: compatibility. It enables Java developers to access the Eclipse GlassFish source code and to contribute to the development of the Eclipse GlassFish.

The following topics are addressed here:

Eclipse GlassFish Documentation Set

The Eclipse GlassFish documentation set describes deployment planning and system installation. For an introduction to Eclipse GlassFish, refer to the books in the order in which they are listed in the following table.

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.

Explains how to get started with the Eclipse GlassFish product.

Explains how to install the software and its components.

Explains how to upgrade to the latest version of Eclipse GlassFish. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications.

Explains how to build a production deployment of Eclipse GlassFish that meets the requirements of your system and enterprise.

Explains how to configure, monitor, and manage Eclipse GlassFish subsystems and components from the command line by using the asadmin (1M) utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help.

Provides instructions for configuring and administering Eclipse GlassFish security.

Explains how to assemble and deploy applications to the Eclipse GlassFish and provides information about deployment descriptors.

Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the Eclipse GlassFish. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging.

Explains how to use published interfaces of Eclipse GlassFish to develop add-on components for Eclipse GlassFish. This document explains how to perform only those tasks that ensure that the add-on component is suitable for Eclipse GlassFish.

Explains how to run applications in embedded Eclipse GlassFish and to develop applications in which Eclipse GlassFish is embedded.

Explains how to configure Eclipse GlassFish to provide higher availability and scalability through failover and load balancing.

Explains how to optimize the performance of Eclipse GlassFish.

Describes common problems that you might encounter when using Eclipse GlassFish and explains how to solve them.

Describes error messages that you might encounter when using Eclipse GlassFish.

Provides reference information in man page format for Eclipse GlassFish administration commands, utility commands, and related concepts.

Describes new features, compatibility issues, and existing bugs for Open Message Queue.

Provides an introduction to the technology, concepts, architecture, capabilities, and features of the Message Queue messaging service.

Explains how to set up and manage a Message Queue messaging system.

Describes the application programming interface in Message Queue for programmatically configuring and monitoring Message Queue resources in conformance with the Java Management Extensions (JMX).

Provides information about concepts and procedures for developing Java messaging applications (Java clients) that work with Eclipse GlassFish.

Provides programming and reference information for developers 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 Jakarta EE applications:

Javadoc tool reference documentation for packages that are provided with Eclipse GlassFish is available as follows.

For information about creating enterprise applications in the NetBeans Integrated Development Environment (IDE), see the NetBeans Documentation, Training & Support page.

For information about the Derby database for use with the Eclipse GlassFish, see the Derby page.

The Jakarta EE Samples project is a collection of sample applications that demonstrate a broad range of Jakarta EE technologies. The Jakarta EE Samples are bundled with the Jakarta EE Software Development Kit (SDK) and are also available from the repository ( https://github.com/eclipse-ee4j/glassfish-samples ).

Typographic Conventions

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

The names of commands, files, and directories, and onscreen computer output

Edit your .login file.

Use ls a to list all files.

machine_name% you have mail.

What you type, contrasted with onscreen computer output

A placeholder to be replaced with a real name or value

The command to remove a file is rm filename.

Book titles, new terms, and terms to be emphasized (note that some emphasized items appear bold online)

Read Chapter 6 in the User’s Guide.

A cache is a copy that is stored locally.

Do not save the file.

Symbol Conventions

The following table explains symbols that might be used in this book.

Contains optional arguments and command options.

The -l option is not required.

Contains a set of choices for a required command option.

The -d option requires that you use either the y argument or the n argument.

Indicates a variable reference.

References the value of the com.sun.javaRoot variable.

Joins simultaneous multiple keystrokes.

Press the Control key while you press the A key.

Joins consecutive multiple keystrokes.

Press the Control key, release it, and then press the subsequent keys.

Indicates menu item selection in a graphical user interface.

File > New > Templates

From the File menu, choose New. From the New submenu, choose Templates.

Default Paths and File Names

The following table describes the default paths and file names that are used in this book.

Represents the base installation directory for Eclipse GlassFish. In configuration files, as-install is represented as follows: $

user’s-home-directory /glassfish7/glassfish SystemDrive :\glassfish7\glassfish

Represents the parent of the base installation directory for Eclipse GlassFish.

user’s-home-directory /glassfish7 SystemDrive :\glassfish7

Represents the directory in which a domain is created by default.

Represents the directory in which a domain’s configuration is stored. In configuration files, domain-dir is represented as follows: $

Represents the directory for a server instance.

Part I

3. Development Tasks and Tools

4. Setting Up a Development Environment

This chapter gives guidelines for setting up an application development environment in the Eclipse GlassFish. Setting up an environment for creating, assembling, deploying, and debugging your code involves installing the mainstream version of the Eclipse GlassFish and making use of development tools. In addition, sample applications are available.

The following topics are addressed here:

Installing and Preparing the Server for Development

For more information about Eclipse GlassFish installation, see the Eclipse GlassFish Installation Guide.

The following components are included in the full installation.

The NetBeans Integrated Development Environment (IDE) bundles the GlassFish edition of the Eclipse GlassFish, so information about this IDE is provided as well.

After you have installed Eclipse GlassFish, you can further optimize the server for development in these ways:

High Availability Features

High availability features such as load balancing and session failover are discussed in detail in the Eclipse GlassFish High Availability Administration Guide. This book describes the following features in the following sections:

Development Tools

The following general tools are provided with the Eclipse GlassFish:

The following development tools are provided with the Eclipse GlassFish or downloadable from Oracle:

The following third-party tools might also be useful:

The asadmin Command

The asadmin command allows you to configure a local or remote server and perform both administrative and development tasks at the command line. For general information about asadmin , see the Eclipse GlassFish Reference Manual.

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

The Administration Console

The Administration Console lets you configure the server and perform both administrative and development tasks using a web browser. For general information about the Administration Console, click the Help button in the Administration Console. This displays the Eclipse GlassFish online help.

To access the Administration Console, type http://`host :4848` in your browser. The host is the name of the machine on which the Eclipse GlassFish is running. By default, the host is localhost . For example:

http://localhost:4848

The Migration Tool

The Migration Tool converts and reassembles Jakarta EE applications and modules developed on other application servers. This tool also generates a report listing how many files are successfully and unsuccessfully migrated, with reasons for migration failure. For more information and to download the Migration Tool, see http://java.sun.com/j2ee/tools/migration/index.html .

Code Editors

There is several advanced editors with an integration with GlassFish or generic Jakarta EE servers. Sometimes you have to install additional extensions, sometimes all you need is just some configuration.

Debugging Tools

You can use several debugging tools with the Eclipse GlassFish. For more information, see Debugging Applications.

Profiling Tools

You can use several profilers with the Eclipse GlassFish. For more information, see Profiling Tools.

Sample Applications

Most Eclipse GlassFish samples have the following directory structure:

5. Class Loaders

Understanding Eclipse GlassFish class loaders can help you determine where to place supporting JAR and resource files for your modules and applications.

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 Web Profile of the Eclipse GlassFish supports the EJB 3.1 Lite specification, which allows enterprise beans within web applications, among other features. The full Eclipse GlassFish 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.

The Class Loader Hierarchy

Class loaders in the Eclipse GlassFish runtime follow a delegation hierarchy that is illustrated in the following figure and fully described in Table 2-1.

The following table describes the class loaders in the Eclipse GlassFish.

Table 2-1 Eclipse GlassFish Class Loaders

The Bootstrap class loader loads the basic runtime classes provided by the JVM software.

The Extension class loader loads classes from JAR files present in the system extensions directory, domain-dir /lib/ext . It is parent to the Public API class loader. See Using the Java Optional Package Mechanism.

The Public API class loader makes available all classes specifically exported by the Eclipse GlassFish runtime for use by deployed applications. This includes, but is not limited to, Jakarta EE APIs and other Oracle APIs. It is parent to the Common class loader.

The Common class loader loads JAR files in the as-install /lib directory, followed by JAR files in the domain-dir /lib directory. Using domain-dir /lib is recommended whenever possible, and required for custom login modules and realms. It is parent to the Connector class loader. See Using the Common Class Loader.

The Connector class loader is a single class loader instance that loads individually deployed connector modules, which are shared across all applications. It is parent to the Applib class loader and the LifeCycleModule class loader.

The LifeCycleModule class loader is created once per lifecycle module. Each lifecycle module’s classpath is used to construct its own class loader. For more information on lifecycle modules, see Developing Lifecycle Listeners.

The Applib class loader loads the library classes, specified during deployment, for a specific enabled module or Jakarta EE application; see Application-Specific Class Loading. One instance of this class loader is present in each class loader universe; see Class Loader Universes. It is parent to the Archive class loader.

When multiple deployed applications use the same library, they share the same instance of the library. One library cannot reference classes from another library.

The Archive class loader loads classes from the WAR, EAR, and JAR files or directories (for directory deployment) of applications or modules deployed to the Eclipse GlassFish. This class loader also loads any application-specific classes generated by the Eclipse GlassFish runtime, such as stub classes or servlets generated by JSP pages.

In previous Eclipse GlassFish versions, the JVM options provided classpath-prefix and classpath-suffix attributes that made it possible to add JAR files or directories either in front of, or after the application server’s system classpath . These options are not present in Eclipse GlassFish 6.0.

The classpath-prefix was typically used to substitute another package for one of the Eclipse GlassFish packages, for example if a newer one was available. This same result can be achieved on a per-application basis with the --libraries option for the deploy subcommand. For more information, see the deploy (1) help page. The Java Optional Package Mechanism does what classpath-suffix used to do. For more information, see Using the Java Optional Package Mechanism.

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 Eclipse GlassFish 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" 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 Eclipse GlassFish 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 Jakarta EE platform.

Using the Java Optional Package Mechanism

Optional packages are packages of Java classes and associated native code that application developers can use to extend the functionality of the core platform.

To use the Java optional package mechanism, copy the JAR files into the domain-dir /lib/ext directory, or use the asadmin add-library command with the --type ext option, then restart the server. For more information about the asadmin add-library command, see the Eclipse GlassFish Reference Manual.

Using the Endorsed Standards Override Mechanism

Endorsed standards handle changes to classes and APIs that are bundled in the JDK but are subject to change by external bodies.

To use the endorsed standards override mechanism, copy the JAR files into the domain-dir`/lib/endorsed` directory, then restart the server.

Class Loader Universes

Access to components within applications and modules installed on the server occurs within the context of isolated class loader universes, each of which has its own Applib and Archive class loaders.

A resource such as a file that is accessed by a servlet, JSP, or EJB component must be in one of the following locations:

module-name/WEB-INF/classes module-name/WEB-INF/lib

Application-Specific Class Loading

You can specify module- or application-specific library classes in one of the following ways:

None of these alternatives apply to application clients. For more information, see Using Libraries with Application Clients.

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 Eclipse GlassFish 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.

You can use application-specific class loading to specify a different XML parser than the default Eclipse GlassFish XML parser.

You can also use application-specific class loading to access different versions of a library from different applications.

If multiple applications or modules refer to the same libraries, classes in those libraries are automatically shared. This can reduce the memory footprint and 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 Eclipse GlassFish Application Deployment Guide.

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.

Circumventing Class Loader Isolation

Since each application or individually deployed module class loader universe is isolated, an application or module cannot load classes from another application or module. This prevents two similarly named classes in different applications or modules from interfering with each other.

To circumvent this limitation for libraries, utility classes, or individually deployed modules accessed by more than one application, you can include the relevant path to the required classes in one of these ways:

Using the Common Class Loader

To use the Common class loader, copy the JAR files into the domain-dir /lib or as-install /lib directory, or use the asadmin add-library command with the --type common option, then restart the server. For more information about the asadmin add-library command, see the Eclipse GlassFish Reference Manual.

Using the Common class loader makes an application or module accessible to all applications or modules deployed on servers that share the same configuration. However, this accessibility does not extend to application clients. For more information, see Using Libraries with Application Clients.

For example, using the Common class loader is the recommended way of adding JDBC drivers to the Eclipse GlassFish. For a list of the JDBC drivers currently supported by the Eclipse GlassFish, see the Eclipse GlassFish Release Notes. For configurations of supported and other drivers, see "Configuration Specifics for JDBC Drivers" in Eclipse GlassFish Administration Guide.

To activate custom login modules and realms, place the JAR files in the domain-dir /lib directory, then restart the server.

Sharing Libraries Across a Cluster

To share libraries across a specific cluster, copy the JAR files to the domain-dir /config/ cluster-config-name /lib directory.

Packaging the Client JAR for One Application in Another Application

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

As an alternative for a production environment, you can have the Common class loader load the client JAR of the dependent application as described in Using the Common Class Loader. Restart the server to make the dependent application accessible to all applications or modules deployed on servers that share the same configuration.

To Package the Client JAR for One Application in Another Application

  1. Deploy the dependent application.
  2. Add the dependent application’s client JAR file to the calling application.
Class-Path: filepath1.jar filepath2.jar . 

Each filepath is relative to the directory or JAR file containing the MANIFEST.MF file. For details, see the Jakarta EE specification.

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.

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.

6. Debugging Applications

This chapter gives guidelines for debugging applications in the Eclipse GlassFish.

The following topics are addressed here:

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 more information about the jdb debugger, see the following links:

Eclipse GlassFish debugging is based on the JPDA. For more information, see JPDA Options.

You can attach to the Eclipse GlassFish using any JPDA compliant debugger.

You can enable debugging even when the Eclipse GlassFish is started without the --debug option. This is useful if you start the Eclipse GlassFish from the Windows Start Menu, or if you want to make sure that debugging is always turned on.

To Set the Server to Automatically Start Up in Debug Mode

  1. Use the Administration Console. Select the JVM Settings component under the relevant configuration.
  2. Check the Debug Enabled box.
  3. To specify a different port (from 9009, the default) to use when attaching the JVM software to a debugger, specify address= port-number in the Debug Options field.
  4. To add JPDA options, add any desired JPDA debugging options in Debug Options. See JPDA Options.

For details, click the Help button in the Administration Console from the JVM Settings page.

JPDA Options

The default JPDA options in Eclipse GlassFish are as follows:

-Xdebug -agentlib:transport=dt_socket,server=y,suspend=n,address=9009

For Windows, you can change dt_socket to dt_shmem .

If you substitute suspend=y , the JVM software starts in suspended mode and stays suspended until a debugger attaches to it. This is helpful if you want to start debugging as soon as the JVM software starts.

To specify a different port (from 9009, the default) to use when attaching the JVM software to a debugger, specify `address=`port-number.

You can include additional options. A list of JPDA debugging options is available at http://java.sun.com/javase/technologies/core/toolsapis/jpda/ .

Generating a Stack Trace for Debugging

To generate a Java stack trace for debugging, use the asadmin generate-jvm-report --type=thread command. The stack trace goes to the domain-dir`/logs/server.log` file and also appears on the command prompt screen. For more information about the asadmin generate-jvm-report command, see the Eclipse GlassFish Reference Manual.

Application Client Debugging

When the appclient script executes the java command to run the Application Client Container (ACC), which in turn runs the client, it includes on the command line the value of the VMARGS environment variable. You can set this variable to any suitable value. For example:

VMARGS=-agentlib:transport=dt_socket,server=y,suspend=y,address=8118

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 Eclipse GlassFish Reference Manual.

The Application Client Container is supported only in the full Eclipse GlassFish, not in the Web Profile. See Developing Java Clients.

Open Message Queue Debugging

Open Message Queue has a broker logger, which can be useful for debugging Java Message Service (JMS) applications, including message-driven bean applications. You can adjust the logger’s verbosity, and you can send the logger output to the broker’s console using the broker’s -tty option. For more information, see the Open Message Queue Administration Guide.

JMS resources are supported only in the full Eclipse GlassFish, not in the Web Profile. See Using the Java Message Service.

Enabling Verbose Mode

To have the server logs and messages printed to System.out on your command prompt screen, you can start the server in verbose mode. This makes it easy to do simple debugging using print statements, without having to view the server.log file every time.

To start the server in verbose mode, use the --verbose option as follows:

asadmin start-domain --verbose [domain-name]

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://docs.oracle.com/javase/8/docs/technotes/tools/share/jstack.html ) or the command kill -QUIT process_id.

Class Loader Debugging

To generate class loading messages, use the following asadmin create-jvm-options command:

asadmin create-jvm-options -verbose\:class

To send the JVM messages to a special JVM log file instead of stdout , use the following asadmin create-jvm-options commands:

asadmin create-jvm-options -XX\:+LogVMOutput asadmin create-jvm-options -XX\:LogFile=$/logs/jvm.log

These -XX options are specific to the OpenJDK (or Hotspot) JVM and do not work with the JRockit JVM.

To send the Eclipse GlassFish messages to the Administration Console instead of stderr , start the domain in verbose mode as described in Enabling Verbose Mode.

Eclipse GlassFish Logging

You can use the Eclipse GlassFish’s log files to help debug your applications. Use the Administration Console. Select the Stand-Alone Instances component, select the instance from the table, then click the View Log Files button in the General Information page. Or select the Cluster component, select the cluster from the table, select the Instances tab, select the instance from the table, then click the View Log Files button in the General Information page.

To change logging settings, select Logger Settings under the relevant configuration.

For details about logging, click the Help button in the Administration Console.

Profiling Tools

You can use a profiler to perform remote profiling on the Eclipse GlassFish to discover bottlenecks in server-side performance. This section describes how to configure profilers for use with Eclipse GlassFish.

The following topics are addressed here:

Information about comprehensive monitoring and management support in the Java 2 Platform, Standard Edition ( J2SE platform) is available at http://docs.oracle.com/javase/8/docs/technotes/guides/management/index.html .

The NetBeans Profiler

For information on how to use the NetBeans profiler, see http://profiler.netbeans.org/index.html .

The HPROF Profiler

The Heap and CPU Profiling Agent (HPROF) is a simple profiler agent shipped with the Java 2 SDK. It is a dynamically linked library that interacts with the Java Virtual Machine Profiler Interface (JVMPI) and writes out profiling information either to a file or to a socket in ASCII or binary format.

HPROF can monitor CPU usage, heap allocation statistics, and contention profiles. In addition, it can also report complete heap dumps and states of all the monitors and threads in the Java virtual machine. For more details on the HPROF profiler, see the technical article at http://java.sun.com/developer/technicalArticles/Programming/HPROF.html .

After HPROF is enabled using the following instructions, its libraries are loaded into the server process.

To Use HPROF Profiling on UNIX
  1. Use the Administration Console. Select the JVM Settings component under the relevant configuration. Then select the Profiler tab.
  2. Edit the following fields:
-Xrunhprof[:help]|[:param=value,param2=value2, . ]
Here is an example of params you can use:
-Xrunhprof:file=log.txt,thread=y,depth=3
The file parameter determines where the stack dump is written. Using help lists parameters that can be passed to HPROF. The output is as follows:
Hprof usage: -Xrunhprof[:help]|[:=, . ] == Option Name and Value Description Default ----------- ------- heap=dump|sites|all heap profiling all cpu=samples|old CPU usage off format=a|b ascii or binary output a file= write data to file java.hprof (.txt for ascii) net=: send data over a socket write to file depth= stack trace depth 4 cutoff= output cutoff point 0.0001 lineno=y|n line number in traces? y thread=y|n thread in traces? n doe=y|n dump on exit? y

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. This writes an HPROF stack dump to the file you specified using the file HPROF parameter.

The JProbe Profiler

Information about JProbe from Sitraka is available at http://www.quest.com/jprobe/ .

After JProbe is installed using the following instructions, its libraries are loaded into the server process.

To Enable Remote Profiling With JProbe
  1. Install JProbe 3.0.1.1. For details, see the JProbe documentation.
  2. Configure Eclipse GlassFish using the Administration Console:
  1. Select the JVM Settings component under the relevant configuration.
  2. Then select the Profiler tab.
  3. Edit the following fields before selecting Save and restarting the server:
    Profiler Name - jprobe
    Profiler Enabled - true
    Classpath - (leave blank)
    Native Library Path - JProbe-dir /profiler
    JVM Option - For each of these options, select Add, type the option in the Value field, then check its box:
 -Xbootclasspath/p:JProbe-dir/profiler/jpagent.jar -Xrunjprobeagent -Xnoclassgc

If any of the configuration options are missing or incorrect, the profiler might experience problems that affect the performance of the Eclipse GlassFish.

When the server starts up with this configuration, you can attach the profiler.
JPROBE_ARGS_0=-jp_input=JPL-file-path
See Step 6 for instructions on how to create the JPL file.
  1. Select Server Side for the type of application.
  2. On the Program tab, provide the following details:
    Target Server - other-server
    Server home Directory - as-install
    Server class File - com.sun.enterprise.server.J2EERunner
    Working Directory - as-install
    Classpath - as-install /lib/appserv-rt.jar
    Source File Path - source-code-dir (in case you want to get the line level details)
    Server class arguments - (optional)
    Main Package - com.sun.enterprise.server
    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 .

Part II

7. Developing Applications and Application Components

8. API for development

Eclipse GlassFish provides several APIs to build applications and components:

GlassFish API is composed of a few sets of APIs:

GlassFish API

Most of the functionality specific to Eclipse GlassFish is available in the GlassFish API. To compile applications or components, add the glassfish-api.jar to the compile classpath. You may also need scattered-archive-api.jar .

The glassfish-api.jar is located in the Eclipse GlassFish installation in as-install /modules/glassfish-api.jar .

In Maven project, you can add it as the following dependency:

 org.glassfish.main.common glassfish-api 

This will already add scattered-archive-api.jar as a transitive dependency.

GlassFish EE API

GlassFish EE API provides functionality related to Jakarta EE. To compile applications or components, add the glassfish-ee-api.jar to the compile classpath.

The glassfish-ee-api.jar is located in the Eclipse GlassFish installation in as-install /modules/glassfish-ee-api.jar .

In Maven project, you can add it as the following dependency:

 org.glassfish.main.common glassfish-ee-api 

Simple GlassFish API

Simple GlassFish API provides basic functionality to deploy applications and run admin commands. Mostly to use embedded Eclipse GlassFish programmatically. To compile applications or components, add the simple-glassfish-api.jar to the compile classpath.

The simple-glassfish-api.jar is located in the Eclipse GlassFish installation in as-install /modules/simple-glassfish-api.jar .

In Maven project, you can add it as the following dependency:

 org.glassfish.main.common simple-glassfish-api 

9. Securing Applications

This chapter describes how to write secure Jakarta EE applications, which contain components that perform user authentication and access authorization for the business logic of Jakarta EE components.

For information about administrative security for the Eclipse GlassFish, see the Eclipse GlassFish Security Guide.

For general information about Jakarta EE security, see Security in The Jakarta EE Tutorial.

The following topics are addressed here:

The Web Profile of the Eclipse GlassFish supports the EJB 3.1 Lite specification, which allows enterprise beans within web applications, among other features. The full Eclipse GlassFish 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 Eclipse GlassFish is to provide highly secure, interoperable, and distributed component computing based on the Jakarta EE security model. Security goals include:

Eclipse GlassFish Specific Security Features

The Eclipse GlassFish supports the Jakarta EE security model, as well as the following features which are specific to the Eclipse GlassFish:

Container Security

The component containers are responsible for providing Jakarta EE application security. The container provides two security forms:

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 Jakarta EE application’s security structure, including security roles, access control, and authentication requirements.

The Eclipse GlassFish supports the deployment descriptors specified by Jakarta EE and has additional security elements included in its own deployment descriptors. Declarative security is the application deployer’s responsibility. For more information about Eclipse GlassFish deployment descriptors, see the Eclipse GlassFish Application Deployment Guide.

There are two levels of declarative security, as follows:

Application Level Security

For an application, roles used by any application must be defined in @DeclareRoles annotations in the code or role-name elements in the application deployment descriptor ( application.xml ). Those role names are scoped to the EJB XML deployment descriptors ( ejb-jar.xml and glassfish-ejb-jar.xml files) and to the servlet XML deployment descriptors ( web.xml and glassfish-web.xml files). For an individually deployed web or EJB module, you define roles using @DeclareRoles annotations or role-name elements in the Jakarta EE deployment descriptor files web.xml or ejb-jar.xml .

To map roles to principals and groups, define matching security-role-mapping elements in the glassfish-application.xml , glassfish-ejb-jar.xml , or glassfish-web.xml file for each role-name used by the application. By default, group principal names are mapped to roles of the same name. Accordingly, the Default Principal To Role Mapping setting is enabled by default on the Security page of the Eclipse GlassFish Administration Console. This default role mapping definition is in effect if you do not define your own mapping in the deployment descriptor for your application as described in this section. For more information, see Roles, Principals, and Principal to Role Mapping.

Component Level Security

Component level security encompasses web components and EJB components.

A secure web container authenticates users and authorizes access to a servlet or JSP by using the security policy laid out in the servlet XML deployment descriptors ( web.xml and glassfish-web.xml files).

The EJB container is responsible for authorizing access to a bean method by using the security policy laid out in the EJB XML deployment descriptors ( ejb-jar.xml and glassfish-ejb-jar.xml files).

Programmatic Security

Programmatic security involves an EJB component or servlet using method calls to the security API, as specified by the Jakarta 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 API for programmatic security consists of methods of the Jakarta EE Security API SecurityContext interface, and methods of the EJB EJBContext interface and the servlet HttpServletRequest interface. The Eclipse GlassFish supports these interfaces as specified in the Java EE specification.

There is also a proprietary Glassfish API for programmatic login. See Programmatic Login Using the ProgrammaticLogin Class.

For more information about programmatic security, see Using Programmatic Security in the The Jakarta EE Tutorial.

Roles, Principals, and Principal to Role Mapping

By default, any groups that an authenticated user belongs to will be mapped to roles with the same names. Therefore, the Default Principal To Role Mapping setting is enabled by default on the Security page of the GlassFish Administration Console. To change the default mapping you can clear this setting. For applications, you define roles in @DeclareRoles annotations or the Jakarta EE deployment descriptor file application.xml . You define the corresponding role mappings in the Eclipse GlassFish deployment descriptor file glassfish-application.xml . For individually deployed web or EJB modules, you define roles in @DeclareRoles annotations or the Jakarta EE deployment descriptor files web.xml or ejb-jar.xml . You define the corresponding role mappings in the Eclipse GlassFish deployment descriptor files glassfish-web.xml or glassfish-ejb-jar.xml .

For more information regarding Jakarta EE deployment descriptors, see the Jakarta EE Specification. For more information regarding Eclipse GlassFish deployment descriptors, see "Elements of the Eclipse GlassFish Deployment Descriptors" in Eclipse GlassFish Application Deployment Guide.

Each security-role-mapping element in the glassfish-application.xml , glassfish-web.xml , or glassfish-ejb-jar.xml file maps a role name permitted by the application or module to principals and groups. For example, a glassfish-web.xml file for an individually deployed web module might contain the following:

   manager jgarcia mwebster team-leads   administrator dsmith  

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 Eclipse GlassFish authorization process. For example:

  administrator  class-name="CustomPrincipalImplClass"> dsmith 

You can specify a default principal and a default principal to role mapping, each of which applies to the entire Eclipse GlassFish 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:

asadmin set server-config.security-service.default-principal=dsmith asadmin set server-config.security-service.default-principal-password=secret
You can set the default principal to role mapping as follows.
asadmin set server-config.security-service.activate-default-principal-to-role-mapping=true asadmin set server-config.security-service.mapped-principal-class=CustomPrincipalImplClass

Default principal to role mapping is enabled by default. To disable it, set the default principal to role mapping property to false.

Realm Configuration

The following topics are addressed here:

Supported Realms

The following realms are supported in the current release of the Eclipse GlassFish:

In the JDBC realm, the server gets user credentials from a database. The Eclipse GlassFish uses the database information and the enabled JDBC realm option in the configuration file. For digest authentication, a JDBC realm should be created with digestRealm as the JAAS context.

For information about configuring realms, see How to Configure a Realm.

How to Configure a Realm

You can configure a realm in one of these ways:

How to Set a Realm for an Application or Module

The following deployment descriptor elements have optional realm or realm-name data subelements or attributes that override the domain’s default realm:

If modules within an application specify realms, these are ignored. If present, the realm defined in glassfish-application.xml is used, otherwise the domain’s default realm is used.

For example, a realm is specified in glassfish-application.xml as follows:

 . ldap 

For more information about the deployment descriptor files and elements, see "Elements of the Eclipse GlassFish Deployment Descriptors" in Eclipse GlassFish Application Deployment Guide.

Creating a Custom Realm

You can create a custom realm by providing a custom Java Authentication and Authorization Service (JAAS) login module class and a custom realm class. Note that client-side JAAS login modules are not suitable for use with the Eclipse GlassFish.

To activate the custom login modules and realms, place the JAR files in the domain-dir /lib directory or the class files in the domain-dir`/lib/classes` directory. For more information about class loading in the Eclipse GlassFish, see Class Loaders.

JAAS is a set of APIs that enable services to authenticate and enforce access controls upon users. JAAS provides a pluggable and extensible framework for programmatic user authentication and authorization. JAAS is a core API and an underlying technology for Jakarta EE security mechanisms. For more information about JAAS, refer to the specification, available at https://jakarta.ee/specifications/authentication/ and https://jakarta.ee/specifications/authorization/ .

For general information about realms and login modules, see the section about working with realms, users, groups, and roles in Introduction to Security in the Jakarta EE Platform in The Jakarta EE Tutorial.

For Javadoc tool pages relevant to custom realms, see the com.sun.appserv.security package.

Custom login modules must extend the com.sun.appserv.security.AppservPasswordLoginModule class. This class implements javax.security.auth.spi.LoginModule. Custom login modules must not implement LoginModule directly.

Custom login modules must provide an implementation for one abstract method defined in AppservPasswordLoginModule :

abstract protected void authenticateUser() throws LoginException

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 Eclipse GlassFish 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;

The authenticateUser method must end with the following sequence:

String[] grpList; // populate grpList with the set of groups to which // _username belongs in this realm, if any commitUserAuthentication(grpList);

Custom realms must extend the com.sun.appserv.security.AppservRealm class and implement the following methods:

public void init(Properties props) throws BadRealmException, NoSuchRealmException

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 Eclipse GlassFish 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 returns true if the realm supports user management.

public abstract Enumeration getGroupNames() throws BadRealmException;

This method returns an Enumeration of all group names.

public abstract Enumeration getUserNames() throws BadRealmException;

This method returns an Enumeration of all user names.

public abstract void refresh() throws BadRealmException;

This method refreshes the realm data so that new users and groups are visible.

public abstract void persist() throws BadRealmException;

This method persists the realm data to permanent storage.

public abstract User getUser(String name) throws NoSuchUserException, 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;

This method adds a new user, who cannot already exist.

public abstract void removeUser(String name) throws NoSuchUserException, BadRealmException;

This method removes a user, who must exist.

public abstract void updateUser(String name, String newName, String password, String[] groups) throws NoSuchUserException, BadRealmException, IASSecurityException;

This method updates data for a user, who must exist.

The array passed to the commitUseAuthentication method should be newly created and otherwise unreferenced. This is because the group name array elements are set to null after authentication as part of cleanup. So the second time your custom realm executes it returns an array with null elements.

Ideally, your custom realm should not return member variables from the authenticate method. It should return local variables as the default JDBCRealm does. Your custom realm can create a local String array in its authenticate method, copy the values from the member variables, and return the String array. Or it can use clone on the member variables.

Jakarta EE Security API Support

JSR-375 defines several authentication-related plugin SPIs, such as, HttpAuthenticationMechanism interface, the IdentityStore and IdentityStoreHandler interfaces:

In addition to these authentication plugin SPIs, the Jakarta EE Security API specification defines the SecurityContext API for use by application code to query and interact with the current security context. The SecurityContext interface defines methods that allow an application to access security information about a caller, authenticate a caller, and authorize a caller. These methods include getCallerPrincipal() , getPrincipalsByType() , isCallerInRole() , authenticate() , and hasAccessToWebResource() .

JACC Support

JACC (Java Authorization Contract for Containers) is part of the Jakarta 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 Jakarta 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 Eclipse GlassFish 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.

Pluggable Audit Module Support

Audit modules collect and store information on incoming requests (servlets, EJB components) and outgoing responses. You can create a custom audit module.

The following topics are addressed here:

Configuring an Audit Module

To configure an audit module, you can perform one of the following tasks:

The AuditModule Class

You can create a custom audit module by implementing a class that extends com.sun.enterprise.security.audit.AuditModule .

For Javadoc tool pages relevant to audit modules, see the com.sun.enterprise.security.audit package.

The AuditModule class provides default "no-op" implementations for each of the following methods, which your custom class can override.

public void init(Properties props)

The preceding method is invoked during server startup when the audit module is initially loaded. The props argument contains the properties defined for this module. The module can do any initialization it needs in this method. If the method returns without throwing an exception, the Eclipse GlassFish 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.

The server.policy File

Each Eclipse GlassFish domain has its own global J2SE policy file, located in domain-dir /config . The file is named server.policy .

The Eclipse GlassFish is a Jakarta EE compliant application server. As such, it follows the requirements of the Jakarta EE specification, including the presence of the security manager (the Java component that enforces the policy) and a limited permission set for Jakarta EE application code.

The following topics are addressed here:

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 Eclipse GlassFish 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. Jakarta 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.

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 $ . For more information about system properties, see the asadmin create-system-properties command in the Eclipse GlassFish Reference Manual.

Table 4-1 Predefined System Properties

depends on operating system

Specifies the directory where the Eclipse GlassFish is installed.

depends on operating system

Specifies the top level directory for a server instance.

Specifies the name of the host (machine).

depends on operating system

Specifies the installation directory for the Java runtime.

depends on operating system

Specifies the library directory for the Open Message Queue software.

Specifies the name of the configuration used by a server instance.

Specifies the name of the server instance. This property is not used in the default configuration, but can be used to customize configuration.

Specifies the name of the cluster. This property is only set on clustered server instances. This property is not used in the default configuration, but can be used to customize configuration.

Specifies the name of the domain. This property is not used in the default configuration, but can be used to customize configuration.

Changing Permissions for an Application

The default policy for each domain limits the permissions of Jakarta EE deployed applications to the minimal set of permissions required for these applications to operate correctly. Do not add extra permissions to the default set (the grant block with no codebase, which applies to all code). Instead, add a new grant block with a codebase specific to the applications requiring the extra permissions, and only add the minimally necessary permissions in that block.

If you develop multiple applications that require more than this default set of permissions, you can add the custom permissions that your applications need. The com.sun.aas.instanceRoot variable refers to the domain-dir. For example:

grant codeBase "file:$/applications/-"

You can add permissions to stub code with the following grant block:

grant codeBase "file:$/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:$/applications/MyApp/-"
grant codeBase "file:$/applications/MyModule/-"

Deployment directories may change between Eclipse GlassFish releases.

An alternative way to add permissions to a specific application or module is to edit the granted.policy file for that application or module. The granted.policy file is located in the domain-dir`/generated/policy/`app-or-module-name directory. In this case, you add permissions to the default grant block. Do not delete permissions from this file.

When the Eclipse GlassFish policy subsystem determines that a permission should not be granted, it logs a server.policy message specifying the permission that was not granted and the protection domains, with indicated code source and principals that failed the protection check. For example, here is the first part of a typical message:

[#|2005-12-17T16:16:32.671-0200|INFO|sun-appserver-pe9.1| javax.enterprise.system.core.security|_ThreadID=14;_ThreadName=Thread-31;| JACC Policy Provider: PolicyWrapper.implies, context(null)- permission((java.util.PropertyPermission java.security.manager write)) domain that failed(ProtectionDomain (file:/E:/glassfish/domains/domain1/applications/cejug-clfds/ . ) . 

Granting the following permission eliminates the message:

grant codeBase "file:$/applications/cejug-clfds/-"

Do not add java.security.AllPermission to the server.policy file for application code. Doing so completely defeats the purpose of the security manager, yet you still get the performance overhead associated with it.

As noted in the Jakarta EE specification, an application should provide documentation of the additional permissions it needs. If an application requires extra permissions but does not document the set it needs, contact the application author for details.

As a last resort, you can iteratively determine the permission set an application needs by observing AccessControlException occurrences in the server log.

If this is not sufficient, you can add the -Djava.security.debug=failure JVM option to the domain. Use the following asadmin create-jvm-options command, then restart the server:

asadmin create-jvm-options -Djava.security.debug=failure

For more information about the asadmin create-jvm-options command, see the Eclipse GlassFish Reference Manual.

You can use the J2SE standard policytool or any text editor to edit the server.policy file. For more information, see http://docs.oracle.com/javase/tutorial/security/tour2/index.html .

For detailed information about the permissions you can set in the server.policy file, see http://docs.oracle.com/javase/8/docs/technotes/guides/security/permissions.html .

Enabling and Disabling the Security Manager

The security manager is disabled by default.

In a production environment, you may be able to safely disable the security manager if all of the following are true:

Disabling the security manager may improve performance significantly for some types of applications.

To enable the security manager, do one of the following:

asadmin create-jvm-options -Djava.security.manager

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 Eclipse GlassFish 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:

asadmin create-jvm-options -Declipselink.security.usedoprivileged=true

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.

You must grant additional permissions to CDI-enabled Jakarta EE applications that are deployed in a Eclipse GlassFish 7 domain or cluster for which security manager is enabled. These additional permissions are not required when security manager is disabled.

To deploy CDI-enabled Jakarta EE applications in a Eclipse GlassFish 7 domain or cluster for which security manager is enabled, add the following permissions to the applications:

grant codeBase "file:$/applications/[ApplicationName]" < permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; >;

For example, for a CDI application named foo.war , add the following permissions to the server.policy file, restart the domain or cluster, and then deploy and use the application.

grant codeBase "file:$/applications/foo" < permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; >;

For more information about modifying application permissions, see Changing Permissions for an Application.

Configuring Message Security for Web Services

In message security, security information is applied at the message layer and travels along with the web services message. Web Services Security (WSS) is the use of XML Encryption and XML Digital Signatures to secure messages. WSS profiles the use of various security tokens including X.509 certificates, Security Assertion Markup Language (SAML) assertions, and username/password tokens to achieve this.

Message layer security differs from transport layer security in that it can be used to decouple message protection from message transport so that messages remain protected after transmission, regardless of how many hops they travel.

Message security (JSR 196) is supported only in the full Eclipse GlassFish, not in the Web Profile.

In this release of the Eclipse GlassFish, message layer annotations are not supported.

For more information about web services, see Developing Web Services.

For more information about message security, see the following:

The following topics are addressed here:

Message Security Providers

When you first install the Eclipse GlassFish, the providers XWS_ClientProvider and XWS_ServerProvider are configured but disabled. You can enable them in one of the following ways:

asadmin set server-config.security-service.message-security-config.SOAP.default_provider=XWS_ServerProvider asadmin set server-config.security-service.message-security-config.SOAP.default_client_provider=XWS_ClientProvider
For more information about the asadmin set command, see the Eclipse GlassFish 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 Eclipse GlassFish prior to running the example.

If you install the OpenSSO, you have these additional provider choices:

For more information about the Eclipse GlassFish deployment descriptor files, see the Eclipse GlassFish Application Deployment Guide.

For information about configuring these providers in the Eclipse GlassFish, see the Eclipse GlassFish 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:

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.debug=true

The following table describes these message security provider properties.

Table 4-2 Message Security Provider Properties

domain-dir`/ config/ wss-server- `config-1.0.xml

Specifies the location of the message security configuration file. To point to a configuration file in the domain-dir /config directory, use the system property $/``config/ , for example:

If true , enables dumping of server provider debug messages to the server log.

If true , signals the provider runtime to collect the user name and password from the CallbackHandler for each request. If false , the user name and password for wsse:UsernameToken(s) is collected once, during module initialization. This property is only applicable for a ClientAuthModule .

Specifies the encryption key used by the provider. The key is identified by its keystore alias.

Specifies the signature key used by the provider. The key is identified by its keystore alias.

Message Security Responsibilities

In the Eclipse GlassFish, the system administrator and application deployer roles are expected to take primary responsibility for configuring message security. In some situations, the application developer may also contribute, although in the typical case either of the other roles may secure an existing application without changing its implementation and without involving the developer.

The following topics are addressed here:

Application Developer Responsibilities

The application developer can turn on message security, but is not responsible for doing so. Message security can be set up by the system administrator so that all web services are secured, or set up by the application deployer when the provider or protection policy bound to the application must be different from that bound to the container.

The application developer is responsible for the following:

Application Deployer Responsibilities

The application deployer is responsible for the following:

These security tasks are discussed in Application-Specific Message Protection. A sample application using message security is discussed in Understanding and Running the Sample Application.

System Administrator Responsibilities

The system administrator is responsible for the following:

A system administrator uses the Administration Console to manage server security settings and uses a command line tool to manage certificate databases. Certificates and private keys are stored in key stores and are managed with keytool . If Network Security Services (NSS) is installed, certificates and private keys are stored in an NSS database, where they are managed using certutil . System administrator tasks are discussed in the Eclipse GlassFish Security Guide.

Application-Specific Message Protection

When the Eclipse GlassFish provided configuration is insufficient for your security needs, and you want to override the default protection, you can apply application-specific message security to a web service.

Application-specific security is implemented by adding the message security binding to the web service endpoint, whether it is an EJB or servlet web service endpoint. Modify Eclipse GlassFish XML files to add the message binding information.

Message security can also be specified using a WSIT security policy in the WSDL file. For details, see the WSIT page at http://wsit.java.net/ .

For more information about message security providers, see Message Security Providers.

For more details on message security binding for EJB web services, servlet web services, and clients, see the XML file descriptions in "Elements of the Eclipse GlassFish Deployment Descriptors" in Eclipse GlassFish Application Deployment Guide.

The following topics are addressed here:

Using a Signature to Enable Message Protection for All Methods

To enable message protection for all methods using digital signature, update the message-security-binding element for the EJB web service endpoint in the application’s glassfish-ejb-jar.xml file. In this file, add request-protection and response-protection elements, which are analogous to the request-policy and response-policy elements discussed in the Eclipse GlassFish Security Guide. To apply the same protection mechanisms for all methods, leave the method-name element blank. Configuring Message Protection for a Specific Method Based on Digital Signatures discusses listing specific methods or using wildcard characters.

This section uses the sample application discussed in Understanding and Running the Sample Application to apply application-level message security to show only the differences necessary for protecting web services using various mechanisms.

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.

   1  HelloWorld HelloWorld  HelloIF service/HelloWorld  auth-layer="SOAP">  auth-source="content" />  auth-source="content"/>      
Configuring Message Protection for a Specific Method Based on Digital Signatures

To enable message protection for a specific method, or for a set of methods that can be identified using a wildcard value, follow these steps. As in the example discussed in Using a Signature to Enable Message Protection for All Methods, to enable message protection for a specific method, update the message-security-binding element for the EJB web service endpoint in the application’s glassfish-ejb-jar.xml file. To this file, add request-protection and response-protection elements, which are analogous to the request-policy and response-policy elements discussed in the Eclipse GlassFish Security Guide. The administration guide includes a table listing the set and order of security operations for different request and response policy configurations.

This section uses the sample application discussed in Understanding and Running the Sample Application to apply application-level message security to show only the differences necessary for protecting web services using various mechanisms.

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.

   1  HelloWorld HelloWorld  HelloIF service/HelloWorld  auth-layer="SOAP">    ejbCreate     sayHello    auth-source="content" />  auth-source="content"/>      

Understanding and Running the Sample Application

This section discusses the WSS sample application. This sample application is installed on your system only if you installed the J2EE 1.4 samples. If you have not installed these samples, see To Set Up the Sample Application.

The objective of this sample application is to demonstrate how a web service can be secured with WSS. The web service in the xms example is a simple web service implemented using a Jakarta EE EJB endpoint and a web service endpoint implemented using a servlet. In this example, a service endpoint interface is defined with one operation, sayHello , which takes a string then sends a response with Hello prefixed to the given string. You can view the WSDL file for the service endpoint interface at app-dir`/xms-ejb/src/ `conf/HelloWorld.wsdl , where app-dir is defined in To Set Up the Sample Application.

In this application, the client looks up the service using the JNDI name java:comp/env/service/HelloWorld and gets the port information using a static stub to invoke the operation using a given name. For the name Duke, the client gets the response Hello Duke!

This example shows how to use message security for web services at the Eclipse GlassFish level. For information about using message security at the application level, see Application-Specific Message Protection. The WSS message security mechanisms implement message-level authentication (for example, XML digital signature and encryption) of SOAP web services invocations using the X.509 and username/password profiles of the OASIS WS-Security standard, which can be viewed from the following URL: http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0.pdf .

The following topics are addressed here:

To Set Up the Sample Application

Before You Begin

To have access to this sample application, you must have previously installed the J2EE 1.4 samples. If the samples are not installed, follow the steps in the following section.

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 ( https://www.oracle.com/java/technologies/java-archive-eesdk-downloads.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.

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
To Run the Sample Application
  1. Make sure that the Eclipse GlassFish is running.
    Message security providers are set up when the Ant targets are run, so you do not need to configure these on the Eclipse GlassFish prior to running this example.
  2. If you are not running HTTP on the default port of 8080, change the WSDL file for the example to reflect the change, and change the common.properties file to reflect the change as well.
    The WSDL file for this example is located at app-dir`/xms-ejb/ `src/conf/HelloWorld.wsdl . The port number is in the following section:
 name="HelloWorld">  name="HelloIFPort" binding="tns:HelloIFBinding">  location="http://localhost:8080/service/HelloWorld"/>  

Verify that the properties in the as-install /samples/common.properties` file are set properly for your installation and environment. If you need a more detailed description of this file, refer to the "Configuration" section for the web services security applications at as-install /j2ee14-samples/samples/webservices/security/docs/common.html#Logging`.

  1. To compile samples: ant
  2. To deploy samples: ant deploy
  3. 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!

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 Using the ProgrammaticLogin Class

Programmatic login allows a deployed Jakarta 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 Jakarta 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 Jakarta EE standard authentication mechanisms.

This section describes a proprietary GlassFish mechanism, but see also the standard security APIs in the Jakarta EE tutorial.

The com.sun.appserv.security.ProgrammaticLogin class in Eclipse GlassFish is not a Jakarta EE API; therefore, it is not portable to other application servers.

The following topics are addressed here:

Programmatic Login Precautions

The Eclipse GlassFish is not involved in how the login information ( user , password ) is obtained by the deployed application. Programmatic login places the burden on the application developer with respect to assuring that the resulting system meets security requirements. If the application code reads the authentication information across the network, the application determines whether to trust the user.

Programmatic login allows the application developer to bypass the Eclipse GlassFish-supported authentication mechanisms and feed authentication data directly to the security service. While flexible, this capability should not be used without some understanding of security issues.

Since this mechanism bypasses the container-managed authentication process and sequence, the application developer must be very careful in making sure that authentication is established before accessing any restricted resources or methods. It is also the application developer’s responsibility to verify the status of the login attempt and to alter the behavior of the application accordingly.

The programmatic login state does not necessarily persist in sessions or participate in single sign-on.

Lazy authentication is not supported for programmatic login. If an access check is reached and the deployed application has not properly authenticated using the programmatic login method, access is denied immediately and the application might fail if not coded to account for this occurrence. One way to account for this occurrence is to catch the access control or security exception, perform a programmatic login, and repeat the request.

Granting Programmatic Login Permission

The ProgrammaticLoginPermission permission is required to invoke the programmatic login mechanism for an application if the security manager is enabled. For information about the security manager, see The server.policy File. This permission is not granted by default to deployed applications because this is not a standard Jakarta EE mechanism.

To grant the required permission to the application, add the following to the domain-dir`/config/server.policy` file:

grant codeBase "file:jar-file-path" < permission com.sun.appserv.security.ProgrammaticLoginPermission "login"; >;

The jar-file-path is the path to the application’s JAR file.

The ProgrammaticLogin Class

The com.sun.appserv.security.ProgrammaticLogin class enables a user to perform login programmatically.

For Javadoc tool pages relevant to programmatic login, see the com.sun.appserv.security package.

The ProgrammaticLogin class has four login methods, two for servlets or JSP files and two for EJB components.

The login methods for servlets or JSP files have the following signatures:

public java.lang.Boolean login(String user, String password, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) public java.lang.Boolean login(String user, String password, String realm, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, boolean errors) throws java.lang.Exception

The login methods for EJB components have the following signatures:

public java.lang.Boolean login(String user, String password) public java.lang.Boolean login(String user, String password, String realm, boolean errors) throws java.lang.Exception

All of these login methods accomplish the following:

The login occurs on the realm specified unless it is null, in which case the domain’s default realm is used. The methods with no realm parameter use the domain’s default realm.

If the errors flag is set to true , any exceptions encountered during the login are propagated to the caller. If set to false , exceptions are thrown.

On the client side, realm and errors parameters are ignored and the actual login does not occur until a resource requiring a login is accessed. A java.rmi.AccessException with COBRA NO_PERMISSION occurs if the actual login fails.

The logout methods for servlets or JSP files have the following signatures:

public java.lang.Boolean logout(HttpServletRequest request, HttpServletResponse response) public java.lang.Boolean logout(HttpServletRequest request, HttpServletResponse response, boolean errors) throws java.lang.Exception

The logout methods for EJB components have the following signatures:

public java.lang.Boolean logout() public java.lang.Boolean logout(boolean errors) throws java.lang.Exception

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.

User Authentication for Single Sign-on

The single sign-on feature of the Eclipse GlassFish allows multiple web applications deployed to the same virtual server to share the user authentication state. With single sign-on enabled, users who log in to one web application become implicitly logged into other web applications on the same virtual server that require the same authentication information. Otherwise, users would have to log in separately to each web application whose protected resources they tried to access.

A sample application using the single sign-on scenario could be a consolidated airline booking service that searches all airlines and provides links to different airline web sites. After the user signs on to the consolidated booking service, the user information can be used by each individual airline site without requiring another sign-on.

Single sign-on operates according to the following rules:

The single sign-on feature utilizes HTTP cookies to transmit a token that associates each request with the saved user identity, so it can only be used in client environments that support cookies.

To configure single sign-on, set the following virtual server properties:

Here are example asadmin set commands with default values:

asadmin set server-config.http-service.virtual-server.vsrv1.property.sso-enabled="true" asadmin set server-config.http-service.virtual-server.vsrv1.property.sso-max-inactive-seconds="300" asadmin set server-config.http-service.virtual-server.vsrv1.property.sso-reap-interval-seconds="60"

For more information about the asadmin set command, see the Eclipse GlassFish Reference Manual.

Adding Authentication Mechanisms to the Servlet Container

You can use JSR 196 in the web tier to facilitate the injection of pluggable authentication modules within the servlet constraint processing engine. The Eclipse GlassFish includes implementations of a number of HTTP layer authentication mechanisms such as basic, form, and digest authentication. You can add alternative implementations of the included mechanisms or implementations of new mechanisms such as HTTP Negotiate/SPNEGO, OpenID, or CAS.

The following topics are addressed here:

The Eclipse GlassFish and JSR-375

The Eclipse GlassFish implements JSR-375 to provide built-in support for BASIC, FORM and Custom FORM authentication mechanisms. JSR-375 also defines plug-in interfaces for authentication and identity stores, that is, the HttpAuthenticationMechanism interface and the IdentityStore interface, respectively. Though HttpAuthenticationMechanism implementations can authenticate users in any manner they choose, the IdentityStore interface provides a convenient mechanism. A significant advantage of using HttpAuthenticationMechanism and IdentityStore over the declarative mechanisms defined by the Servlet specification is that it allows an application to control the identity stores that it authenticates against, in a standard, portable way. You can use the built-in implementations of these APIs, or define custom implementations.

Jakarta EE Security API defines several annotations, with names that end with Definition, which when used makes the corresponding built-in mechanism available as a CDI bean. Jakarta EE Security API also supports the use of Expression Language 3.0 in these annotations to allow dynamic configuration.

Built-in Authentication Mechanisms

An application packages its own HttpAuthenticationMechanism by including in a bean archive that is a part of the application. Alternatively, it may select and configure one of the container’s built-in mechanisms using the corresponding annotation, as listed below:

In Eclipse GlassFish, all built-in authentication mechanisms need to be authenticated using an identity store. The IdentityStore interface, included in the Jakarta EE Security API, defines an SPI for interacting with identity stores, which are directories or databases containing user account information. The IdentityStore interface has four methods: validate(Credential) , getCallerGroups(CredentialValidationResult) , validationTypes() and priority() .Developers can provide their own implementation of this interface, or use one of the built-in Identity Stores. The RememberMeIdentityStore interface, which is a variation on the IdentityStore interface, can be used when an application wants to "remember" a user’s authenticated session for an extended period, so that the caller can return to the application periodically without needing to present primary authentication credentials each time.

There are two built-in implementations of IdentityStore : an LDAP identity store, and a Database identity store. The following snippet shows the usage of DatabaseIdentityStoreDefinition , which makes DatabaseIdentityStore available as CDI bean.

@DatabaseIdentityStoreDefinition( callerQuery = "# ", groupsQuery = "select group_name from caller_groups where caller_name = ?", hashAlgorithm = Pbkdf2PasswordHash.class, priorityExpression = "# ", hashAlgorithmParameters = < "Pbkdf2PasswordHash.Iterations=3072", "$ " > )

Since Jakarta EE Security API provides support for Expression Langauge 3.0, regular expressions can be used to set value of annotation attributes.

The Eclipse GlassFish provides out of the box implementation of Pbkdf2PasswordHash that supports PBKDF2 password hashing. It is suggested that you use Pbkdf2PasswordHash for generating and validating passwords, unless there are specific requirements which cannot be met any other way.

Custom Authentication Mechanism

An application provider can choose to provide its own custom authentication mechanism, apart from built-in authentication mechanism.

A custom authentication mechanism implements the HttpAuthenticationMechanism interface, introduced in Jakarta EE Security API. This interface defines the following three methods.

AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext ) throws AuthenticationException; AuthenticationStatus secureResponse(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext ) throws AuthenticationException; void cleanSubject(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext);

HttpAuthenticationMechanism returns AuthenticationStatus to indicate the status of authentication request. Internally, it gets translated to corresponding JASPIC AuthStatus as shown below:

Each method of the HttpAuthenticationMechanism interface performs the same function as the corresponding ServerAuth methods. Unlike JASPIC, HttpAuthenticationMechanism is specified for the servlet container only. Only the validateRequest() must be implemented, for other two methods, default behaviors are specified.

validateRequest allows a caller to authenticate. The request gets inspected inside validateRequest to read credential or any other information, or it can write to standard response with status of the authentication request or redirect the caller to an OAuth provider. Once the credential is validated, the result of the validation is communicated to the container using the HttpMessageContext parameter.

Sample Http Authentication Mechanism

The class MyAuthenticationMechanism.java is a sample HttpAuthenticationMechanism implementation. Note that only validateRequest method has been implemented, since Jakarta EE Security API provides default implementation of other two methods. An application provider may choose to override the default implementation depending on the requirement.

import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.security.enterprise.AuthenticationException; import javax.security.enterprise.AuthenticationStatus; import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism; import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext; import javax.security.enterprise.credential.UsernamePasswordCredential; import javax.security.enterprise.identitystore.CredentialValidationResult; import javax.security.enterprise.identitystore.IdentityStoreHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID; @RequestScoped public class MyAuthenticationMechanism implements HttpAuthenticationMechanism < @Inject private IdentityStoreHandler identityStoreHandler; @Override public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException < // Get the (caller) name and password from the request // NOTE: This is for the smallest possible example only. In practice // putting the password in a request query parameter is highly // insecure and is discouraged. String name = request.getParameter("name"); String password = request.getParameter("password"); if (name != null && password != null) < // Delegate the identity data out> function to // the Identity Store CredentialValidationResult result = identityStoreHandler.validate( new UsernamePasswordCredential(name, password)); if (result.getStatus() == VALID) < // Communicate the details of the authenticated user to the // container. response.addHeader("Authentication Mechanism", "MyAuthenticationMechanism"); return httpMessageContext.notifyContainerAboutLogin( result.getCallerPrincipal(), result.getCallerGroups()); > else < return httpMessageContext.responseUnauthorized(); > > return httpMessageContext.doNothing(); > >

The Eclipse GlassFish and JSR 196

The Eclipse GlassFish implements the Servlet Container Profile of JSR 196, Java Authentication Service Provider Interface for Containers. JSR 196 defines a standard service provider interface (SPI) that extends the concepts of the Java Authentication and Authorization Service (JAAS) to enable pluggability of message authentication modules in message processing runtimes. The JSR 196 standard defines profiles that establish contracts for the use of the SPI in specific contexts. The Servlet Container Profile of JSR 196 defines the use of the SPI by a Servlet container such that:

The JSR 196 specification defines a simple message processing model composed of four interaction points:

  1. secureRequest on the client
  2. validateRequest on the server
  3. secureResponse on the server
  4. validateResponse on the client

A message processing runtime uses the SPI at these interaction points to delegate the corresponding message security processing to authentication providers, also called authentication modules, integrated into the runtime by way of the SPI.

A compatible server-side message processing runtime, such as the Eclipse GlassFish servlet container, supports the validateRequest and secureResponse interaction points of the message processing model. The servlet container uses the SPI at these interaction points to delegate the corresponding message security processing to a server authentication module (SAM), integrated by the SPI into the container.

Writing a Server Authentication Module

A key step in adding an authentication mechanism to a compatible server-side message processing runtime such as the Eclipse GlassFish servlet container is acquiring a SAM that implements the desired authentication mechanism. One way to do that is to write the SAM yourself.

A SAM implements the javax.security.auth.message.module.ServerAuthModule interface as defined by JSR 196. A SAM is invoked indirectly by the message processing runtime at the validateRequest and secureResponse interaction points. A SAM must implement the five methods of the ServerAuthModule interface:

The validateRequest method may also throw an AuthException to indicate that the message processing by the SAM failed without establishing a failure response message in messageInfo .

See the Servlet Container Profile section in the JSR 196 specification for additional background and details.

Sample Server Authentication Module

The class MySam.java is a sample SAM implementation. Notice that the sample implements the five methods of the ServerAuthModule interface. This SAM implements an approximation of HTTP basic authentication.

package tip.sam; 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; public class MySam implements ServerAuthModule < protected static final Class[] supportedMessageTypes = new Class[]< HttpServletRequest.class, HttpServletResponse.class >; private MessagePolicy requestPolicy; private MessagePolicy responsePolicy; private CallbackHandler handler; private Map options; private String realmName = null; private String defaultGroup[] = null; privte static final String REALM_PROPERTY_NAME = "realm.name"; private static final String GROUP_PROPERTY_NAME = "group.name"; private static final String BASIC = "Basic"; static final String AUTHORIZATION_HEADER = "authorization"; static final String AUTHENTICATION_HEADER = "WWW-Authenticate"; public void initialize(MessagePolicy reqPolicy, MessagePolicy resPolicy, CallbackHandler cBH, Map opts) throws AuthException < requestPolicy = reqPolicy; responsePolicy = resPolicy; handler = cBH; options = opts; if (options != null) < realmName = (String) options.get(REALM_PROPERTY_NAME); if (options.containsKey(GROUP_PROPERTY_NAME)) < defaultGroup = new String[]<(String) options.get(GROUP_PROPERTY_NAME)>; > > > public Class[] getSupportedMessageTypes() < return supportedMessageTypes; > public AuthStatus validateRequest( MessageInfo msgInfo, Subject client, Subject server) throws AuthException < try < 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; > > private String processAuthorizationToken( MessageInfo msgInfo, Subject s) throws AuthException < HttpServletRequest request = (HttpServletRequest) msgInfo.getRequestMessage(); String token = request.getHeader(AUTHORIZATION_HEADER); if (token != null && token.startsWith(BASIC + " ")) < token = token.substring(6).trim(); // Decode and parse the authorization token String decoded = new String(Base64.decode(token.getBytes())); int colon = decoded.indexOf(':'); if (colon 0 || colon == decoded.length() - 1) < return (null); > String username = decoded.substring(0, colon); // use the callback to ask the container to // validate the password PasswordValidationCallback pVC = new PasswordValidationCallback(s, username, decoded.substring(colon + 1).toCharArray()); try < handler.handle(new Callback[]); pVC.clearPassword(); > catch (Exception e) < AuthException ae = new AuthException(); ae.initCause(e); throw ae; > if (pVC.getResult()) < return username; > > return null; > private AuthStatus sendAuthenticateChallenge( MessageInfo msgInfo) < String realm = realmName; // if the realm property is set use it, // otherwise use the name of the server // as the realm name. if (realm == null) < HttpServletRequest request = (HttpServletRequest) msgInfo.getRequestMessage(); realm = request.getServerName(); >HttpServletResponse response = (HttpServletResponse) msgInfo.getResponseMessage(); String header = BASIC + " realm=\"" + realm + "\""; response.setHeader(AUTHENTICATION_HEADER, header); response.setStatus( HttpServletResponse.SC_UNAUTHORIZED); return AuthStatus.SEND_CONTINUE; > public AuthStatus secureResponse( MessageInfo msgInfo, Subject service) throws AuthException < return AuthStatus.SEND_SUCCESS; > public void cleanSubject(MessageInfo msgInfo, Subject subject) throws AuthException < if (subject != null) < subject.getPrincipals().clear(); >> private static final String AUTH_TYPE_INFO_KEY = "javax.servlet.http.authType"; // distinguish the caller principal // and assign default groups private void setAuthenticationResult(String name, Subject s, MessageInfo m) throws IOException, UnsupportedCallbackException < handler.handle(new Callback[]< new CallerPrincipalCallback(s, name) >); if (name != null) < // add the default group if the property is set if (defaultGroup != null) < handler.handle(new Callback[]< new GroupPrincipalCallback(s, defaultGroup) >); > m.getMap().put(AUTH_TYPE_INFO_KEY, ""MySAM"); > > >

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.

Compiling and Installing a Server Authentication Module

Before you can use the sample SAM, you need to compile, install, and configure it. Then you can bind it to an application.

To compile the SAM, include the SPI in your classpath. When the Eclipse GlassFish is installed, the JAR file containing the SPI, jmac-api.jar , is installed in the as-install /lib directory. After you compile the SAM, install it by copying a JAR file containing the compiled SAM to the as-install /lib directory.

Configuring a Server Authentication Module

You can configure a SAM in one of these ways:

For details, click the Help button in the Administration Console. For details, see the Eclipse GlassFish Reference Manual.

Binding a Server Authentication Module to Your Application

After you install and configure the SAM, you can bind it for use by the container on behalf of one or more of your applications. You have two options in how you bind the SAM, depending on whether you are willing to repackage and redeploy your application:

10. Developing Web Services

This chapter describes Eclipse GlassFish support for web services. The following topics are addressed here:

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.

In addition, the as-install /modules/webservices-osgi.jar and as-install /modules/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 Jakarta EE Tutorial shows how to deploy simple web services to Eclipse GlassFish.

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 more information about using Fast Infoset, see the Metro WSIT Guide

Creating Portable Web Service Artifacts

For a tutorial that shows how to use the wsimport and wsgen commands, see " Web Services" in The Jakarta EE Tutorial.

Deploying a Web Service

You deploy a web service endpoint to the Eclipse GlassFish just as you would any servlet, stateless session bean (SLSB), or application.

For complex services with dependent classes, user specified WSDL files, or other advanced features, autodeployment of an annotated file is not sufficient.

The Eclipse GlassFish deployment descriptor files glassfish-web.xml and glassfish-ejb-jar.xml provide optional web service enhancements in the webservice-endpoint and webservice-description elements, including a debugging-enabled subelement that enables the creation of a test page. The test page feature is enabled by default and described in The Web Service URI, WSDL File, and Test Page.

For more information about deployment, autodeployment, and deployment descriptors, see the Eclipse GlassFish Application Deployment Guide. For more information about the asadmin deploy command, see the Eclipse GlassFish Reference Manual.

The Web Service URI, WSDL File, and Test Page

Clients can run a deployed web service by accessing its service endpoint address URI, which has the following format:

http://host:port/context-root/servlet-mapping-url-pattern

The context-root is defined in the application.xml or web.xml file, and can be overridden in the glassfish-application.xml or glassfish-web.xml file. The servlet-mapping-url-pattern is defined in the web.xml file.

In the following example, the context-root is my-ws and the servlet-mapping-url-pattern is /simple :

http://localhost:8080/my-ws/simple

You can view the WSDL 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:

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.

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 Eclipse GlassFish Application Deployment Guide.

The Databinding Provider

The JAX-WS reference implementation (RI) used to be dependent on the JAXB RI for databinding. JAXB and JAX-WS implementations have been decoupled, and databinding is modular. JAXB and JAX-WS are no longer Jakarta EE APIs.

The EclipseLink JAXB implementation, plus EclipseLink extensions, is called MOXy. The org.eclipse.persistence.moxy.jar file is bundled with Eclipse GlassFish, which supports the JAXB RI and MOXy as databinding providers.

To specify the databinding provider for the JVM, set the com.sun.xml.ws.spi.db.BindingContextFactory JVM property to one of the following values:

com.sun.xml.ws.db.glassfish.JAXBRIContextFactory

Specifies the JAXB reference implementation. This is the default.

Specifies Eclipselink MOXy JAXB binding.

asadmin create-jvm-options -Dcom.sun.xml.ws.spi.db.BindingContextFactory=com.sun.xml.ws.db.toplink.JAXBContextFactory

To specify the databinding provider for a web service endpoint:

Allowed values are as follows

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 jakarta.xml.ws.WebServiceFeature; import org.jvnet.ws.databinding.DatabindingModeFeature; import com.sun.xml.ws.db.toplink.JAXBContextFactory; . WebServiceFeature[] features = new DatabindingModeFeature(JAXBContextFactory.ECLIPSELINK_JAXB)>; . 
import jakarta.jws.WebService; import org.jvnet.ws.databinding.DatabindingMode; import com.sun.xml.ws.db.toplink.JAXBContextFactory; . @WebService() @DatabindingMode(JAXBContextFactory.ECLIPSELINK_JAXB); . 
 name='hello' implementation='hello.HelloImpl' url-pattern='/hello' databinding='eclipselink.jaxb' />

The EclipseLink JAXB compiler is not included but can be used with Eclipse GlassFish. 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

11. Configuring the Java Persistence Provider

This chapter describes Oracle TopLink, the default persistence provider in Eclipse GlassFish, and introduces how to use it. This chapter also tells how to set the default persistence provider in Eclipse GlassFish and how to use persistence-related features specific to Eclipse GlassFish such as automatic schema generation.

The following topics are addressed here:

Overview of Oracle TopLink

Oracle TopLink is the default persistence provider in Eclipse GlassFish. It is a comprehensive standards-based object-persistence and object-transformation framework that provides APIs, schemas, and run-time services for the persistence layer of an application.

TopLink includes all of EclipseLink, from the Eclipse Foundation. EclipseLink is the default persistence provider in Eclipse GlassFish. EclipseLink is the open source implementation of the development framework and the runtime provided in TopLink. EclipseLink implements the following specifications, plus value-added extensions:

JPA 2.0 is part of Java Platform, Enterprise Edition 6 (Jakarta EE 6). It includes improvements and enhancements to domain modeling, object/relational mapping, EntityManager and Query interfaces, and the Java Persistence Query Language (JPQL). It includes an API for criteria queries, a metamodel API, and support for validation. The Java Persistence API can be used with non-EJB components outside the EJB container.

For the JPA 2.0 Specification, see Java Specification Request (JSR) 317. For basic information about the Java Persistence API, see Persistence in The Jakarta EE Tutorial.

For the JAXB 2.0 specification, see Java Specification Request (JSR) 222.
bin/jaxb-compiler.cmd bin/jaxb-compiler.sh

In addition to all of EclipseLink, Oracle TopLink includes TopLink Grid, an integration between TopLink and Oracle Coherence that allows TopLink to use Oracle Coherence as a level 2 (L2) cache and persistence layer for entities. The toplink-grid.jar file is bundled with Eclipse GlassFish.

You must have a license for Oracle Coherence to be able to use TopLink Grid.

For information about developing, deploying, and configuring Oracle TopLink, EclipseLink, and TopLink Grid applications, see the following:

Using Oracle TopLink in Eclipse GlassFish

To run TopLink JPA applications in Eclipse GlassFish, you must configure the server and coordinate certain server and application settings. These are described in the following steps. For a summary of these steps, see "Using TopLink with WebLogic Server" in Oracle Fusion Middleware Solution Guide for Oracle TopLink. For more detailed explanations of these steps, see the links in the steps.

  1. Set up the datasource. See " Administering Database Connectivity" in Eclipse GlassFish Administration Guide.
  2. Create the application. For guidance in writing your application, see Persistence in The Jakarta EE Tutorial.
  3. Create the persistence.xml file. See Specifying the Database for an Application for considerations specific to Eclipse GlassFish.

If you are using the Java Persistence API by calling Persistence.createEMF() , see Specifying the Persistence Provider for an Application.

Specifying the Database for an Application

Eclipse GlassFish uses the bundled Apache Derby database by default, named jdbc/__default . If the transaction-type element is omitted or specified as JTA and both the jta-data-source and non-jta-data-source elements are omitted in the persistence.xml file, Apache Derby is used as a JTA data source. If transaction-type is specified as RESOURCE_LOCAL and both jta-data-source and non-jta-data-source are omitted, Apache Derby is used as a non-JTA data source.

To use a non-default database, either specify a value for the jta-data-source element, or set the transaction-type element to RESOURCE_LOCAL and specify a value for the non-jta-data-source element.

If you are using the default persistence provider, the provider attempts to automatically detect the database type based on the connection metadata. This database type is used to issue SQL statements specific to the detected database type’s dialect. You can specify the optional eclipselink.target-database property to guarantee that the database type is correct. For example:

  xmlns="http://java.sun.com/xml/ns/persistence">  name ="em1"> jdbc/MyDB2DB  name="eclipselink.target-database" value="DB2"/>   

The following eclipselink.target-database property values are allowed. Supported platforms have been tested with the Eclipse GlassFish and are found to be Jakarta EE compatible.

//Supported platforms JavaDB Derby Oracle MySQL4 //Others available SQLServer DB2 Sybase PostgreSQL Informix TimesTen Attunity HSQL SQLAnyWhere DBase DB2Mainframe Cloudscape PointBase

If you are using the Java Persistence API by calling Persistence.createEMF() , do not specify the jta-data-source or non-jta-data-source elements. Instead, specify the provider element and any additional properties required by the JDBC driver or the database. For example:

  xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">  name ="em2"> org.eclipse.persistence.jpa.PersistenceProvider ejb3.war.servlet.JpaBean  name="eclipselink.target-database" value="Derby"/>  name="eclipselink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>  name="eclipselink.jdbc.url" value="jdbc:derby://localhost:1527/testdb;retrieveMessagesFromServerOnGetMessage=true;create=true;"/>  name="eclipselink.jdbc.user" value="APP"/>  name="eclipselink.jdbc.password" value="APP"/>   

For a list of the JDBC drivers currently supported by the Eclipse GlassFish, see the Eclipse GlassFish Release Notes. For configurations of supported and other drivers, see "Configuration Specifics for JDBC Drivers" in Eclipse GlassFish Administration Guide.

Specifying the Persistence Provider for an Application

If you are using the default persistence provider in an application that uses the Java Persistence API by injecting or looking up an entity manager or entity manager factory, you do not need to specify the provider.

If you are using the Java Persistence API by calling Persistence.createEMF() , you should always specify the persistence provider for specification compliance. To specify the default provider, set the provider element of the persistence.xml file to org.eclipse.persistence.jpa.PersistenceProvider .

You can specify a non-default persistence provider for an application in the manner described in the Java Persistence API Specification:

  1. Install the provider. Copy the provider JAR files to the domain-dir /lib directory, and restart the Eclipse GlassFish. 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.
  xmlns="http://java.sun.com/xml/ns/persistence">  name ="em3"> com.company22.persistence.PersistenceProviderImpl  name="company22.database.name" value="MyDB"/>   

To specify the provider programmatically instead of in the persistence.xml file, set the javax.persistence.provider property and pass it to the Map parameter of the following method:

javax.persistence.Persistence.createEntityManagerFactory(String, Map)

Primary Key Generation Defaults

In the descriptions of the @GeneratedValue , @SequenceGenerator , and @TableGenerator annotations in the Java Persistence Specification, certain defaults are noted as specific to the persistence provider. The default persistence provider’s primary key generation defaults are listed here.

@GeneratedValue defaults are as follows:

The @SequenceGenerator annotation has one default specific to the default provider. The default sequenceName is the specified name .

@TableGenerator defaults are as follows:

Automatic Schema Generation

The automatic schema generation feature of the Eclipse GlassFish defines database tables based on the fields or properties in entities and the relationships between the fields or properties. This insulates developers from many of the database related aspects of development, allowing them to focus on entity development. The resulting schema is usable as-is or can be given to a database administrator for tuning with respect to performance, security, and so on.

The following topics are addressed here:

Automatic schema generation is supported on an all-or-none basis: it expects that no tables exist in the database before it is executed. It is not intended to be used as a tool to generate extra tables or constraints.

Deployment won’t fail if all tables are not created, and undeployment won’t fail if not all tables are dropped. Instead, an error is written to the server log. This is done to allow you to investigate the problem and fix it manually. You should not rely on the partially created database schema to be correct for running the application.

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:

Before using these options, make sure you have a properly configured database. See Specifying the Database for an Application.

Optional schema generation properties control the automatic creation of database tables. You can specify them in the persistence.xml file. For more information, see Using EclipseLink JPA Extensions for Schema Generation ( http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#Using_EclipseLink_JPA_Extensions_for_Schema_Generation ).

The following options of the asadmin deploy or asadmin deploydir command control the automatic creation of database tables at deployment.

Table 6-1 The asadmin deploy and asadmin deploydir Generation Options

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.

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.

Table 6-2 The asadmin undeploy Generation Options

If true , causes database tables that were automatically created when the entities were last deployed to be dropped when the entities are undeployed. If false , does not drop tables.

If not specified, tables are dropped only if the eclipselink.ddl-generation property setting in persistence.xml is drop-and-create-tables .

For more information about the asadmin deploy , asadmin deploydir , and asadmin undeploy commands, see the Eclipse GlassFish Reference Manual.

When asadmin deployment options and persistence.xml options are both specified, the asadmin deployment options take precedence.

Restrictions and Optimizations

This section discusses restrictions and performance optimizations that affect using the Java Persistence API.

The following topics are addressed here:

Oracle Database Enhancements

EclipseLink features a number of enhancements for use with Oracle databases. These enhancements require classes from the Oracle JDBC driver JAR files to be visible to EclipseLink at runtime. If you place the JDBC driver JAR files in domain-dir /lib , the classes are not visible to Eclipse GlassFish components, including EclipseLink.

If you are using an Oracle database, put JDBC driver JAR files in domain-dir /lib/ext instead. This ensures that the JDBC driver classes are visible to EclipseLink.

If you do not want to take advantage of Oracle-specific extensions from EclipseLink or you cannot put JDBC driver JAR files in domain-dir /lib/ext , set the eclipselink.target-database property to the value org.eclipse.persistence.platform.database.OraclePlatform . For more information about the eclipselink.target-database property, see Specifying the Database for an Application.

Extended Persistence Context

The Java Persistence API specification does not specify how the container and persistence provider should work together to serialize an extended persistence context. This also prevents successful serialization of a reference to an extended persistence context in a stateful session bean.

Even in a single-instance environment, if a stateful session bean is passivated, its extended persistence context could be lost when the stateful session bean is activated.

Therefore, in Eclipse GlassFish, a stateful session bean with an extended persistence context is never passivated and cannot be failed over.

Using @OrderBy with a Shared Session Cache

Setting @OrderBy on a ManyToMany or OneToMany relationship field in which a List represents the Many side doesn’t work if the session cache is shared. Use one of the following workarounds:

 name="eclipselink.cache.shared.default" value="false"/>

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 .

Database Case Sensitivity

Mapping references to column or table names must be in accordance with the expected column or table name case, and ensuring this is the programmer’s responsibility. If column or table names are not explicitly specified for a field or entity, the Eclipse GlassFish uses upper case column names by default, so any mapping references to the column or table names must be in upper case. If column or table names are explicitly specified, the case of all mapping references to the column or table names must be in accordance with the case used in the specified names.

The following are examples of how case sensitivity affects mapping elements that refer to columns or tables. Keep case sensitivity in mind when writing these mappings.

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 Eclipse GlassFish uses the incorrect case, and the creation of the unique constraint fails.

Foreign Key Mapping

Use @OneToMany(mappedBy="COMPANY") or specify an explicit column name for the Company field on the Many side of the relationship.

SQL Result Set Mapping

Use the following elements:

 name="SRSMName">  entity-class="entities.someEntity" />  name="UPPERCASECOLUMNNAME" /> 

Or specify an explicit column name for the upperCaseColumnName field.

Named Native Queries and JDBC Queries

Column or table names specified in SQL queries must be in accordance with the expected case. For example, MySQL requires column names in the SELECT clause of JDBC queries to be uppercase, while PostgreSQL and Sybase require table names to be uppercase in all JDBC queries.

PostgreSQL Case Sensitivity

PostgreSQL stores column and table names in lower case. JDBC queries on PostgreSQL retrieve column or table names in lowercase unless the names are quoted. For example:

use aliases Select m.ID AS \"ID\" from Department m

Use the backslash as an escape character in the class file, but not in the persistence.xml file.

Sybase Finder Limitation

If a finder method with an input greater than 255 characters is executed and the primary key column is mapped to a VARCHAR column, Sybase attempts to convert type VARCHAR to type TEXT and generates the following error:

com.sybase.jdbc2.jdbc.SybSQLException: Implicit conversion from datatype 'TEXT' to 'VARCHAR' is not allowed. Use the CONVERT function to run this query.

To avoid this error, make sure the finder method input is less than 255 characters.

MySQL Database Restrictions

The following restrictions apply when you use a MySQL database with the Eclipse GlassFish for persistence.

) Engine=InnoDB;

InnoDB provides MySQL with a transaction-safe (ACID compliant) storage engine having commit, rollback, and crash recovery capabilities.

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 .

create table EMPLOYEE ( empId int NOT NULL, salary float(25,2) NULL, mgrId int NULL, PRIMARY KEY (empId), FOREIGN KEY (mgrId) REFERENCES EMPLOYEE (empId) ) ENGINE=InnoDB; insert into Employee values (1, 1234.34, 1); delete from Employee where empId = 1;
This example fails with the following error message.
ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails
To resolve this issue, change the table creation script to the following:
create table EMPLOYEE ( empId int NOT NULL, salary float(25,2) NULL, mgrId int NULL, PRIMARY KEY (empId), FOREIGN KEY (mgrId) REFERENCES EMPLOYEE (empId) ON DELETE SET NULL ) ENGINE=InnoDB; insert into Employee values (1, 1234.34, 1); delete from Employee where empId = 1;

This can be done only if the foreign key field is allowed to be null. For more information, see http://dev.mysql.com/doc/mysql/en/innodb-foreign-key-constraints.html .

12. Developing Web Applications

This chapter describes how web applications are supported in the Eclipse GlassFish.

The following topics are addressed here:

For general information about web applications, see " The Web Tier" in The Jakarta EE Tutorial.

The Web Profile of the Eclipse GlassFish supports the EJB 3.1 Lite specification, which allows enterprise beans within web applications, among other features. The full Eclipse GlassFish supports the entire EJB 3.1 specification. For details, see JSR 318 ( http://jcp.org/en/jsr/detail?id=318 ).

Using Servlets

Eclipse GlassFish supports the Java Servlet Specification version 4.0.

Servlet API version 4.0 is fully backward compatible with versions 3.0, 2.3, 2.4, and 2.5, so all existing servlets should work without modification or recompilation.

To develop servlets, use the Java Servlet API. For information about using the Java Servlet API, see the documentation at https://jakarta.ee/specifications/servlet/ .

The Eclipse GlassFish 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 Eclipse GlassFish Reference Manual.

This section describes how to create effective servlets to control application interactions running on a Eclipse GlassFish, including standard-based servlets. In addition, this section describes the Eclipse GlassFish features to use to augment the standards.

The following topics are addressed here:

Caching Servlet Results

The Eclipse GlassFish can cache the results of invoking a servlet, a JSP, or any URL pattern to make subsequent invocations of the same servlet, JSP, or URL pattern faster. The Eclipse GlassFish caches the request results for a specific amount of time. In this way, if another data call occurs, the Eclipse GlassFish can return the cached data instead of performing the operation again. For example, if your servlet returns a stock quote that updates every 5 minutes, you set the cache to expire after 300 seconds.

Whether to cache results and how to cache them depends on the data involved. For example, it makes no sense to cache the results of a quiz submission, because the input to the servlet is different each time. However, it makes sense to cache a high level report showing demographic data taken from quiz results that is updated once an hour.

To define how a Eclipse GlassFish web application handles response caching, you edit specific fields in the glassfish-web.xml file.

A servlet that uses caching is not portable.

For Javadoc tool pages relevant to caching servlet results, see the com.sun.appserv.web.cache package.

For information about JSP caching, see JSP Caching.

The following topics are addressed here:

Caching Features

The Eclipse GlassFish has the following web application response caching capabilities:

Default Cache Configuration

If you enable caching but do not provide any special configuration for a servlet or JSP, the default cache configuration is as follows:

Caching Example

Here is an example cache element in the glassfish-web.xml file:

 max-capacity="8192" timeout="60">  name="myHelper" class-name="MyCacheHelper"/>  myservlet  name="timefield">120 GET POST   /catalog/*   name='best' scope='request.parameter'/>  name='category' scope='request.parameter'> roses lilies   name='SKUnum' scope='request.parameter'>  match-expr='in-range'> 1000 - 2000   name="category" scope="request.parameter>  match-expr="equals" cache-on-match-failure="true"> bogus    InfoServlet myHelper  

For more information about the glassfish-web.xml caching settings, see "cache" in Eclipse GlassFish Application Deployment Guide.

The CacheKeyGenerator Interface

The built-in default CacheHelper implementation allows web applications to customize the key generation. An application component (in a servlet or JSP) can set up a custom CacheKeyGenerator implementation as an attribute in the ServletContext .

The name of the context attribute is configurable as the value of the cacheKeyGeneratorAttrName property in the default-helper element of the glassfish-web.xml deployment descriptor. For more information, see "default-helper" in Eclipse GlassFish Application Deployment Guide.

About the Servlet Engine

Servlets exist in and are managed by the servlet engine in the Eclipse GlassFish. The servlet engine is an internal object that handles all servlet meta functions. These functions include instantiation, initialization, destruction, access from other components, and configuration management.

The following topics are addressed here:

Instantiating and Removing Servlets

After the servlet engine instantiates the servlet, the servlet engine calls the servlet’s init method to perform any necessary initialization. You can override this method to perform an initialization function for the servlet’s life, such as initializing a counter.

When a servlet is removed from service, the servlet engine calls the destroy method in the servlet so that the servlet can perform any final tasks and deallocate resources. You can override this method to write log messages or clean up any lingering connections that won’t be caught in garbage collection.

Request Handling

When a request is made, the Eclipse GlassFish 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.

Using JavaServer Pages

The Eclipse GlassFish supports the following JSP features:

For information about creating JSP files, see the JavaServer Pages web site at https://jakarta.ee/specifications/pages/ .

This section describes how to use JavaServer Pages (JSP files) as page templates in a Eclipse GlassFish web application.

The following topics are addressed here:

JSP Tag Libraries and Standard Portable Tags

Eclipse GlassFish supports tag libraries and standard portable tags. For more information, see the JavaServer Pages Standard Tag Library (JSTL) page at https://jakarta.ee/specifications/tags/ .

Web applications don’t need to bundle copies of the jsf-impl.jar or appserv-jstl.jar JSP tag libraries (in as-install /lib ) to use JavaServer Faces technology or JSTL, respectively. These tag libraries are automatically available to all web applications.

However, the as-install /lib/jspcachtags.jar tag library for JSP caching is not automatically available to web applications. See JSP Caching, next.

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:

For more information about response caching as it pertains to servlets, see Caching Servlet Results.

Enabling JSP Caching

To globally enable JSP caching, set the jspCachingEnabled property to true . The default is false . For example:

asadmin set server-config.web-container.property.jspCachingEnabled="true"

For more information about the asadmin set command, see the Eclipse GlassFish 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.

Web applications that use JSP caching without bundling the tag library are not portable.

Refer to Eclipse GlassFish tags in JSP files as follows:

%@ taglib prefix="prefix" uri="http://glassfish.org/taglibs/cache" %>

Subsequently, the cache tags are available as ` and `. For example, if your prefix is mypfx , the cache tags are available as and .

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:

  com.sun.appserv.web.taglibs.cache.CacheRequestListener 

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:

  com.sun.appserv.web.taglibs.cache.CacheSessionListener 

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.

The cache Tag

The cache tag caches the body between the beginning and ending tags according to the attributes specified. The first time the tag is encountered, the body content is executed and cached. Each subsequent time it is run, the cached content is checked to see if it needs to be refreshed and if so, it is executed again, and the cached data is refreshed. Otherwise, the cached data is served.

Attributes of cache

The following table describes attributes for the cache tag.

Table 7-1 The cache Attributes

(optional) The name used by the container to access the cached entry. The cache key is suffixed to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page.

(optional) The time in seconds after which the body of the tag is executed and the cache is refreshed. By default, this value is interpreted in seconds. To specify a different unit of time, add a suffix to the timeout value as follows: s for seconds, m for minutes, h for hours, d for days. For example, 2h specifies two hours.

(optional) If set to true , the body content is executed and served as if there were no cache tag. This offers a way to programmatically decide whether the cached response is sent or whether the body has to be executed, though the response is not cached.

(optional) If set to true , the body content is executed and the response is cached again. This lets you programmatically refresh the cache immediately regardless of the timeout setting.

(optional) The scope of the cache. Can be request , session , or application . See Caching Scope.

Example of cache

The following example represents a cached JSP file:

%@ taglib prefix="mypfx" uri="http://glassfish.org/taglibs/cache" %> %@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  key="$ " nocache="$ " refresh="$ " timeout="10m">  test="$ "> %-- get headlines from database --%>  .    timeout="1h"> Local News %-- get the headline news and cache them --%> 
The flush Tag

Forces the cache to be flushed. If a key is specified, only the entry with that key is flushed. If no key is specified, the entire cache is flushed.

Attributes of flush

The following table describes attributes for the flush tag.

Table 7-2 The flush Attributes

(optional) The name used by the container to access the cached entry. The cache key is suffixed to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page.

(optional) The scope of the cache. Can be request , session , or application . See Caching Scope.

Examples of flush

To flush the entry with key="foobar" :

 key="foobar"/>