Sun GlassFish Enterprise Server v2.1.1 Developer's Guide

Part II Developing Applications and Application Components

Chapter 5 Securing Applications

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

For information about administrative security for the Enterprise Server, see Chapter 9, Configuring Security, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

For general information about Java EE security, see “Chapter 29: Introduction to Security in Java EE” in the Java EE 5 Tutorial.

This chapter contains the following sections:

Security Goals

In an enterprise computing environment, there are many security risks. The goal of the Sun GlassFish Enterprise Server is to provide highly secure, interoperable, and distributed component computing based on the Java EE security model. Security goals include:

Enterprise Server Specific Security Features

The Enterprise Server supports the Java EE security model, as well as the following features which are specific to the Enterprise Server:

Container Security

The component containers are responsible for providing Java 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 Java EE application’s security structure, including security roles, access control, and authentication requirements.

The Enterprise Server supports the deployment descriptors specified by Java EE and has additional security elements included in its own deployment descriptors. Declarative security is the application deployer’s responsibility. For more information about Sun-specific deployment descriptors, see the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

There are two levels of declarative security, as follows:

Application Level Security

For an application, roles used by any application container must be defined in @DeclareRoles annotations in the code or role-name elements in the application deployment descriptor (application.xml). The role names are scoped to the EJB XML deployment descriptors (ejb-jar.xml and sun-ejb-jar.xml files) and to the servlet XML deployment descriptors (web.xml and sun-web.xml files). For an individually deployed web or EJB module, you define roles using @DeclareRoles annotations or role-name elements in the Java 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 sun-application.xml, sun-ejb-jar.xml, or sun-web.xml file for each role-name used by the application. 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 sun-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 sun-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 Java EE security model, to make business logic decisions based on the caller or remote user’s security role. Programmatic security should only be used when declarative security alone is insufficient to meet the application’s security model.

The Java EE specification defines programmatic security as consisting of two methods of the EJB EJBContext interface and two methods of the servlet HttpServletRequest interface. The Enterprise Server supports these interfaces as specified in the specification.

For more information on programmatic security, see the following:

Roles, Principals, and Principal to Role Mapping

For applications, you define roles in @DeclareRoles annotations or the Java EE deployment descriptor file application.xml. You define the corresponding role mappings in the Enterprise Server deployment descriptor file sun-application.xml. For individually deployed web or EJB modules, you define roles in @DeclareRoles annotations or the Java EE deployment descriptor files web.xml or ejb-jar.xml. You define the corresponding role mappings in the Enterprise Server deployment descriptor files sun-web.xml or sun-ejb-jar.xml.

For more information regarding Java EE deployment descriptors, see the Java EE Specification. For more information regarding Enterprise Server deployment descriptors, see Appendix A, Deployment Descriptor Files, in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

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

<sun-web-app>
    <security-role-mapping>
        <role-name>manager</role-name>
        <principal-name>jgarcia</principal-name>
        <principal-name>mwebster</principal-name>
        <group-name>team-leads</group-name>
    </security-role-mapping>
    <security-role-mapping>
        <role-name>administrator</role-name>
        <principal-name>dsmith</principal-name>
    </security-role-mapping>
</sun-web-app>

A role can be mapped to either 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 Enterprise Server authorization process. For example:

<security-role-mapping>
    <role-name>administrator</role-name>
    <principal-name class-name="CustomPrincipalImplClass">
        dsmith
    </principal-name>
</security-role-mapping>

You can specify a default principal and a default principal to role mapping, each of which applies to the entire Enterprise Server instance. The default principal to role mapping maps group principals to 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:

Realm Configuration

This section covers the following topics:

Supported Realms

The following realms are supported in the Enterprise Server:

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 sun-application.xml is used, otherwise the domain’s default realm is used.

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

<sun-application>
    ...
    <realm>ldap</realm>
</sun-application>

For more information about the deployment descriptor files and elements, see Appendix A, Deployment Descriptor Files, in Sun GlassFish Enterprise Server v2.1.1 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 Enterprise Server.

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 Java EE security mechanisms. For more information about JAAS, refer to the JAAS specification for Java SDK, available at http://java.sun.com/products/jaas/.

For general information about realms and login modules, see “Chapter 29: Introduction to Security in Java EE” in the Java EE 5 Tutorial.

For Javadoc tool pages relevant to custom realms, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.security package.

Custom login modules must extend the 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 Enterprise Server infrastructure.

The custom login module can access the following protected object fields, which it inherits from AppservPasswordLoginModule. These contain the user name and password of the user to be authenticated:

protected String _username;
protected String _password;

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 in domain.xml. The realm can do any initialization it needs in this method. If the method returns without throwing an exception, the Enterprise Server assumes that the realm is ready to service authentication requests. If an exception is thrown, the realm is disabled.

public String getAuthType()

This method returns a descriptive string representing the type of authentication done by this realm.

public abstract Enumeration getGroupNames(String username) throws 
    InvalidOperationException, NoSuchUserException

This method returns an Enumeration (of String objects) enumerating the groups (if any) to which the given username belongs in this realm.

JACC Support

JACC (Java Authorization Contract for Containers) is part of the Java EE specification and defined by JSR 115. JACC defines an interface for pluggable authorization providers. Specifically, JACC is used to plug in the Java policy provider used by the container to perform Java EE caller access decisions. The Java policy provider performs Java policy decisions during application execution. This provides third parties with a mechanism to develop and plug in modules that are responsible for answering authorization decisions during Java EE application execution. The interfaces and rules used for developing JACC providers are defined in the JACC 1.0 specification.

The Enterprise Server provides a simple file-based JACC-compliant authorization engine as a default JACC provider. To configure an alternate provider using the Admin Console, open the Security component under the relevant configuration, and select the JACC Providers component. For details, click the Help button in the Admin 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. This section covers the following topics:

For additional information about audit modules, see Audit Callbacks.

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.appserv.security.AuditModule.

For Javadoc tool pages relevant to audit modules, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.security package.

The AuditModule class provides 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 in domain.xml. The module can do any initialization it needs in this method. If the method returns without throwing an exception, the Enterprise Server assumes the module realm is ready to service audit requests. If an exception is thrown, the module is disabled.

public void authentication(String user, String realm, boolean success)

This method is invoked when an authentication request has been processed by a realm for the given user. The success flag indicates whether the authorization was granted or denied.

public void webInvocation(String user, HttpServletRequest req, String type, boolean success)

This method is invoked when a web container call has been processed by authorization. The success flag indicates whether the authorization was granted or denied. The req object is the standard HttpServletRequest object for this request. The type string is one of hasUserDataPermission or hasResourcePermission (see JSR 115).

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 Enterprise Server domain has its own global J2SE policy file, located in domain-dir/config. The file is named server.policy.

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

This section covers the following topics:

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 Enterprise Server does not distinguish between EJB and web module permissions. All code is granted the minimal set of web component permissions (which is a superset of the EJB minimal set). Do not modify these entries.

A few permissions above the minimal set are also granted in the default server.policy file. These are necessary due to various internal dependencies of the server implementation. Java EE application developers must not rely on these additional permissions. In some cases, deleting these permissions might be appropriate. For example, one additional permission is granted specifically for using connectors. If connectors are not used in a particular domain, you should remove this permission, because it is not otherwise necessary.

Changing Permissions for an Application

The default policy for each domain limits the permissions of Java 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:${com.sun.aas.instanceRoot}/applications/j2ee-apps/-" {
...
}

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

grant codeBase "file:${com.sun.aas.instanceRoot}/generated/-" {
...
}

In general, you should add extra permissions only to the applications or modules that require them, not to all applications deployed to a domain. For example:

grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-apps/MyApp/-" {
...
}

For a module:

grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-modules/MyModule/-" {
...
}

An alternative way to add permissions to a 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 application server 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/j2ee-modules/cejug-clfds/ ... )
...

Granting the following permission eliminates the message:

grant codeBase "file:${com.sun.aas.instanceRoot}/applications/j2ee-modules/cejug-clfds/-" {
    permission java.util.PropertyPermission "java.security.manager", "write";
}

Note –

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 Java 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 --user adminuser -Djava.security.debug=failure

For more information about the asadmin create-jvm-options command, see the Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

You can use the J2SE standard policytool or any text editor to edit the server.policy file. For more information, see http://java.sun.com/docs/books/tutorial/security1.2/tour2/index.html.

For detailed information about policy file syntax, see http://java.sun.com/javase/6/docs/technotes/guides/security/PolicyFiles.html#FileSyntax.

For information about using system properties in the server.policy file, see http://java.sun.com/javase/6/docs/technotes/guides/security/PolicyFiles.html#PropertyExp. For information about Enterprise Server system properties, see system-property in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

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

The Javadoc for the Permission class is at http://java.sun.com/javase/6/docs/api/java/security/Permission.html.

Enabling and Disabling the Security Manager

The security manager is disabled in the developer and cluster profiles and enabled in the enterprise profile 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 disable the security manager, do one of the following:

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.


Note –

In this release of the Enterprise Server, message layer annotations are not supported.


For more information about message security, see the following:

The following web services security topics are discussed in this section:

Message Security Providers

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

The example described in Understanding and Running the Sample Application uses the ClientProvider and ServerProvider providers, which are enabled when the asant targets are run. You don’t need to enable these on the Enterprise Server prior to running the example.

If you install the Access Manager, you have these additional provider choices:

Liberty specifications can be viewed at http://www.projectliberty.org/resources/specifications.php. The WS-I BSP specification can be viewed at http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html.

For more information about the Sun-specific deployment descriptor files, see the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For information about configuring these providers in the Enterprise Server, see Chapter 10, Configuring Message Security, in Sun GlassFish Enterprise Server v2.1.1 Administration 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. For more information, see the property descriptions under provider-config in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

Message Security Responsibilities

In the Enterprise Server, 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 responsibilities of the various roles are defined in the following sections:

Application Developer

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

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

The system administrator is responsible for the following:

A system administrator uses the Admin 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 and you have selected the enterprise profile, certificates and private keys are stored in an NSS database, where they are managed using certutil. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide. System administrator tasks are discussed in Chapter 10, Configuring Message Security, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

Application-Specific Message Protection

When the Enterprise Server 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 Sun-specific 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 https://wsit.dev.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 Appendix A, Deployment Descriptor Files, in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

This section contains the following topics:

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 sun-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 Chapter 10, Configuring Message Security, in Sun GlassFish Enterprise Server v2.1.1 Administration 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.

ProcedureTo Enable Message Protection for All Methods Using Digital Signature

  1. In a text editor, open the application’s sun-ejb-jar.xml file.

    For the xms example, this file is located in the directory app-dir/xms-ejb/src/conf, where app-dir is defined in To Set Up the Sample Application.

  2. Modify the sun-ejb-jar.xml file by adding the message-security-binding element as shown:

    <sun-ejb-jar>
      <enterprise-beans>
        <unique-id>1</unique-id>
        <ejb>
          <ejb-name>HelloWorld</ejb-name>
          <jndi-name>HelloWorld</jndi-name>
          <webservice-endpoint>
            <port-component-name>HelloIF</port-component-name>
            <endpoint-address-uri>service/HelloWorld</endpoint-address-uri>
            <message-security-binding auth-layer="SOAP">
              <message-security>
                <request-protection auth-source="content" />
                <response-protection auth-source="content"/>
              </message-security>
            </message-security-binding>
          </webservice-endpoint>
        </ejb>
      </enterprise-beans>
    </sun-ejb-jar>
  3. Compile, deploy, and run the application as described in To Run the Sample Application.

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 sun-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 Chapter 10, Configuring Message Security, in Sun GlassFish Enterprise Server v2.1.1 Administration 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.

ProcedureTo Enable Message Protection for a Particular Method or Set of Methods Using Digital Signature

  1. In a text editor, open the application’s sun-ejb-jar.xml file.

    For the xms example, this file is located in the directory app-dir/xms-ejb/src/conf, where app-dir is defined in To Set Up the Sample Application.

  2. Modify the sun-ejb-jar.xml file by adding the message-security-binding element as shown:

    <sun-ejb-jar>
      <enterprise-beans>
      <unique-id>1</unique-id>
        <ejb>
          <ejb-name>HelloWorld</ejb-name>
          <jndi-name>HelloWorld</jndi-name>
          <webservice-endpoint>
            <port-component-name>HelloIF</port-component-name>
            <endpoint-address-uri>service/HelloWorld</endpoint-address-uri>
            <message-security-binding auth-layer="SOAP">
              <message-security>
                <message>
                  <java-method>
                    <method-name>ejbCreate</method-name>
                  </java-method>
                </message>
                <message>
                  <java-method>
                    <method-name>sayHello</method-name>
                  </java-method>
                </message>
                <request-protection auth-source="content" />
                <response-protection auth-source="content"/>
              </message-security>
            </message-security-binding>
          </webservice-endpoint>
        </ejb>
      </enterprise-beans>
    </sun-ejb-jar>
  3. Compile, deploy, and run the application as described in To Run the Sample Application.

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 Java 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 Enterprise Server 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.

This section includes the following topics:

ProcedureTo 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 in your browser.

  2. Click on the Download button for the Samples Bundle.

  3. Click on Accept License Agreement.

  4. Click on the J2EE SDK Samples link.

  5. Choose a location for the j2eesdk-1_4_03-samples.zip file.

    Saving the file to as-install is recommended.

  6. Unzip the file.

    Unzipping to the as-install/j2ee14–samples directory is recommended. For example, you can use the following command.


    unzip j2eesdk-1_4_03-samples.zip -d j2ee14-samples

ProcedureTo Run the Sample Application

  1. Make sure that the Enterprise Server is running.

    Message security providers are set up when the asant targets are run, so you do not need to configure these on the Enterprise Server 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:

    <service name="HelloWorld">
      <port name="HelloIFPort" binding="tns:HelloIFBinding">
        <soap:address location="http://localhost:8080/service/HelloWorld"/>
      </port>
    </service>

    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.

  3. Change to the app-dir directory.

  4. Run the following asant targets to compile, deploy, and run the example application:

    1. To compile samples:

      asant

    2. To deploy samples:

      asant deploy

    3. To run samples:

      asant run

    If the sample has compiled and deployed properly, you see the following response on your screen after the application has run:

    run:[echo] Running the xms program:[exec] Established message level security : Hello Duke!

  5. To undeploy the sample, run the following asant target:


    asant undeploy

    All of the web services security examples use the same web service name (HelloWorld) and web service ports. These examples show only the differences necessary for protecting web services using various mechanisms. Make sure to undeploy an application when you have completed running it. If you do not, you receive an Already in Use error and deployment failures when you try to deploy another web services example application.

Programmatic Login

Programmatic login allows a deployed Java EE application or module to invoke a login method. If the login is successful, a SecurityContext is established as if the client had authenticated using any of the conventional Java EE mechanisms. Programmatic login is supported for servlet and EJB components on the server side, and for stand-alone or application clients on the client side. Programmatic login is useful for an application having special needs that cannot be accommodated by any of the Java EE standard authentication mechanisms.


Note –

Programmatic login is specific to the Enterprise Server and not portable to other application servers.


This section contains the following topics:

Programmatic Login Precautions

The Enterprise Server 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 application server-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 Java 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, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on 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 Enterprise Server 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 properties in the virtual-server element of the domain.xml file:

Here is an example configuration with all default values:

<virtual-server id="server" ... >
     ...
    <property name="sso-enabled" value="true"/>
     <property name="sso-max-inactive-seconds" value="300"/>
     <property name="sso-reap-interval-seconds" value="60"/>
 </virtual-server>

Chapter 6 Developing Web Services

This chapter describes Enterprise Server support for web services. JavaTM API for XML-Based Web Services (JAX-WS) version 2.0 is supported. Java API for XML-Based Remote Procedure Calls (JAX-RPC) version 1.1 is supported for backward compatibility. This chapter contains the following sections:

“Part Two: Web Services” in the Java EE 5 Tutorial shows how to deploy simple web services to the Enterprise Server. “Chapter 20: Java API for XML Registries” explains how to set up a registry and create clients that access the registry.

For additional information about JAX-WS and web services, see Java Specification Request (JSR) 224 and JSR 109.

For information about web services security, see Configuring Message Security for Web Services.

For information about web services administration, monitoring, logging, and registries, see Chapter 14, Managing Web Services, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

The Fast Infoset standard specifies a binary format based on the XML Information Set. This format is an efficient alternative to XML. For information about using Fast Infoset, see the following links:

Creating Portable Web Service Artifacts

For a tutorial that shows how to use the wsimport and wsgen commands, see “Part Two: Web Services” in the Java EE 5 Tutorial. For reference information on these commands, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Deploying a Web Service

You deploy a web service endpoint to the Enterprise Server just as you would any servlet, stateless session bean (SLSB), or application. After you deploy the web service, the next step is to publish it. For more information about publishing a web service, see Web Services Registry.

You can use the autodeployment feature to deploy a simple JSR 181 annotated file. You can compile and deploy in one step, as in the following example:


javac -cp javaee.jar -d domain-dir/autodeploy MyWSDemo.java

Note –

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


The Sun-specific deployment descriptor files sun-web.xml and sun-ejb-jar.xml provide optional web service enhancements in their 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 Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide. For more information about the asadmin deploy command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Web Services Registry

You deploy a registry to the Enterprise Server just as you would any connector module, except that if you are using the Admin Console, you must select a Registry Type value. After deployment, you can configure a registry in one of the following ways:

After you deploy a web service, you can publish it to a registry in one of the following ways:

The Sun Java Enterprise System (Java ES) includes a Sun-specific ebXML registry. For more information about the Java ES registry and registries in general, see “Chapter 20: Java API for XML Registries” in the Java EE 5 Tutorial.

A connector module that accesses UDDI registries is provided with the Enterprise Server in the as-install/lib/install/applications/jaxr-ra directory.

You can also use the JWSDP registry available at http://java.sun.com/webservices/jwsdp/index.jsp or the SOA registry available at http://www.sun.com/products/soa/index.jsp.

The Web Service URI, WSDL File, and Test 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 sun-application.xml or sun-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 Admin 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 Admin Console.


Note –

The test page works only for WS-I compliant web services. This means that the tester servlet does not work for services with WSDL files that use RPC/encoded binding.


Generation of the test page is enabled by default. You can disable the test page for a web service by setting the value of the debugging-enabled element in the sun-web.xml and sun-ejb-jar.xml deployment descriptor to false. For more information, see the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

JBI Runtime

The Java Business Integration runtime (JBI runtime) provides a distributed infrastructure used for enterprise integration. It consists of a set of binding components and service engines, which integrate various types of information technology assets. The binding components and service engines are interconnected with a normalized message router. Binding components and service engines adapt information technology assets to a standard services model, based on XML message exchange using standardized message exchange patterns. The JBI runtime provides services for transforming and routing messages, as well as the ability to centrally administer the distributed system.

This JBI runtime incorporates the JSR 208 specification for JBI and other open standards. The JBI runtime allows you to integrate web services and enterprise applications as loosely coupled composite applications within a Service-Oriented Architecture (SOA).

The distribution of the JBI runtime includes a Java EE service engine, an HTTP SOAP binding component, a WSDL shared library, and Ant tasks described in JBI Tasks. For information about JBI administration in the Enterprise Server, see the Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

Additional components, tools, and documentation are available for download. Refer to Project Open ESB for more information on the additional components, tools, and documentation that are available.

The Java EE Service Engine acts as a bridge between the Java EE and JBI runtime environments for web service providers and web service consumers. The Java EE Service Engine provides better performance than a SOAP over HTTP binding component due to in-process communication between components and additional protocols provided by JBI binding components such as JMS, SMTP, and File.

The JSR 208 specification allows transactions to be propagated to other components using a message exchange property specified in the JTA_TRANSACTION_PROPERTY_NAME field. The Java EE Service Engine uses this property to set and get a transaction object from the JBI message exchange. It then uses the transaction object to take part in a transaction. This means a Java EE application or module can take part in a transaction started by a JBI application. Conversely, a JBI application can take part in a transaction started by a Java EE application or module.

Similarly, the JSR 208 specification allows a security subject to be propagated as a message exchange property named javax.jbi.security.subject. Thus a security subject can be propagated from a Java EE application or module to a JBI application or the reverse.

To deploy a Java EE application or module as a JBI service unit, use the Admin Console or the asadmin deploy-jbi-service-assembly command. For more information about the asadmin deploy-jbi-service-assembly command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Using the jbi.xml File

Section 6.3.1 of the JSR 208 specification describes the jbi.xml file. This is a deployment descriptor, located in the META-INF directory. To deploy a Java EE application or module as a JBI service unit, you need only specify a small subset of elements in the jbi.xml file. Here is an example provider:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jbi version="1.0" xmlns="http://java.sun.com/xml/ns/jbi" xmlns:ns0="http://ejbws.jbi.misc/">
  <services binding-component="false">
    <provides endpoint-name="MiscPort" interface-name="ns0:Misc" service-name="ns0:MiscService"/>
  </services>
</jbi>

Here is an example consumer:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jbi version="1.0" xmlns="http://java.sun.com/xml/ns/jbi" xmlns:ns0="http://message.hello.jbi/">
  <services binding-component="false">
    <consumes endpoint-name="MsgPort" interface-name="ns0:Msg" service-name="ns0:MsgService"/>
  </services>
</jbi>

The Java EE Service Engine enables the endpoints described in the provides section of the jbi.xml file in the JBI runtime. Similarly, the Java EE Service Engine routes invocations of the endpoints described in the consumes section from the Java EE web service consumer to the JBI runtime.

Using Application Server Descriptors

To determine whether a web service endpoint is enabled in the JBI runtime environment, you can set a jbi-enabled attribute in the Enterprise Server. This attribute is set to false (disabled) by default. To enable an endpoint for JBI, set the attribute to true using the asadmin set command. For example, if an endpoint is bundled as a WAR file named my-ws.war with an endpoint named simple, use the following command:


asadmin set --user adminuser server.applications.web-module.my-ws.web-service-endpoint.simple.jbi-enabled=true

Determining whether requests from a web service consumer are routed through the Java EE Service Engine is unnecessary and deprecated, but supported for backward compatibility. You can set a stub-property named jbi-enabled in the consumer's sun-web.xml or sun-ejb-jar.xml file. This property is set to true (enabled) by default. Here is an example of the sun-web.xml file:

<sun-web-app>
  <service-ref>
    <service-ref-name>sun-web.serviceref/calculator</service-ref-name>
    <port-info>
      <wsdl-port>
        <namespaceURI>http://example.web.service/Calculator</namespaceURI>
        <localpart>CalculatorPort</localpart>
      </wsdl-port>
      <service-endpoint-interface>service.web.example.calculator.Calculator</service-endpoint-interface>
      <stub-property name="jbi-enabled" value="true"/>
    </port-info>
  </service-ref>
</sun-web-app>

For more information about the sun-web.xml and sun-ejb-jar.xml deployment descriptor files, see the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Using the Woodstox Parser

The default XML parser in the Enterprise Server is the Sun GlassFish XML Parser (SJSXP). Using the Woodstox parser, which is bundled with the Enterprise Server, may improve performance. Woodstox and SJSXP both provide implementations of the StAX API. To enable the Woodstox parser, set the following system properties for the default server-config configuration in the domain.xml file, then restart the server:

<config name=server-config>
 ...
   <system-property name="javax.xml.stream.XMLEventFactory" 
      value="com.ctc.wstx.stax.WstxEventFactory"/>
   <system-property name="javax.xml.stream.XMLInputFactory" 
      value="com.ctc.wstx.stax.WstxInputFactory"/>
   <system-property name="javax.xml.stream.XMLOutputFactory" 
      value="com.ctc.wstx.stax.WstxOutputFactory"/>
</config>

In addition, set these properties for any other configurations referenced by server instances or clusters on which you want to use the Woodstox parser. For more information about the domain.xml file and system properties, see the Sun GlassFish Enterprise Server v2.1.1 Administration Reference.


Note –

If you are using a stand-alone client, you must set these same properties for the client on the java command line as follows:


-Djavax.xml.stream.XMLInputFactory=com.ctc.wstx.stax.WstxInputFactory
-Djavax.xml.stream.XMLOutputFactory=com.ctc.wstx.stax.WstxOutputFactory
-Djavax.xml.stream.XMLEventFactory=com.ctc.wstx.stax.WstxEventFactory

Setting these properties is not necessary if you are using an application client, which is recommended and supported.


For more information about the Woodstox parser, see http://woodstox.codehaus.org/. For more information about the StAX API, see Chapter 17: Streaming API for XML in the Java EE 5 Tutorial.

Chapter 7 Using the Java Persistence API

Sun GlassFish Enterprise Server support for the Java Persistence API includes all required features described in the Java Persistence Specification. Although officially part of the Enterprise JavaBeans Specification v3.0, also known as JSR 220, the Java Persistence API can also be used with non-EJB components outside the EJB container.

The Java Persistence API provides an object/relational mapping facility to Java developers for managing relational data in Java applications. For basic information about the Java Persistence API, see “Part Four: Persistence” in the Java EE 5 Tutorial.

This chapter contains Enterprise Server specific information on using the Java Persistence API in the following topics:


Note –

The default persistence provider in the Enterprise Server is based on Oracle's TopLink Essentials Java Persistence API implementation. All configuration options in TopLink Essentials are available to applications that use the Enterprise Server's default persistence provider.


Specifying the Database

The Enterprise Server uses the bundled Java DB (Derby) database by 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, Java DB 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, Java DB 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 based on the connection metadata. You can specify the optional toplink.platform.class.name property to guarantee that the database is correct. For example:

<?xml version="1.0" encoding="UTF-8"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence">
        <persistence-unit name ="em1">
            <jta-data-source>jdbc/MyDB2DB</jta-data-source>
            <properties>
                <property name="toplink.platform.class.name" 
                    value="oracle.toplink.essentials.platform.database.DB2Platform"/>
            </properties>
        </persistence-unit>
    </persistence>

The following toplink.platform.class.name property values are allowed. Supported platforms have been tested with the Enterprise Server and are found to be Java EE compatible.

//Supported platforms
oracle.toplink.essentials.platform.database.DerbyPlatform
oracle.toplink.essentials.platform.database.oracle.OraclePlatform
oracle.toplink.essentials.platform.database.SQLServerPlatform
oracle.toplink.essentials.platform.database.DB2Platform
oracle.toplink.essentials.platform.database.SybasePlatform
oracle.toplink.essentials.platform.database.CloudscapePlatform
oracle.toplink.essentials.platform.database.MySQL4Platform
oracle.toplink.essentials.platform.database.PointBasePlatform
oracle.toplink.essentials.platform.database.PostgreSQLPlatform

//Others available
oracle.toplink.essentials.platform.database.InformixPlatform
oracle.toplink.essentials.platform.database.TimesTenPlatform
oracle.toplink.essentials.platform.database.AttunityPlatform
oracle.toplink.essentials.platform.database.HSQLPlatform
oracle.toplink.essentials.platform.database.SQLAnyWherePlatform
oracle.toplink.essentials.platform.database.DBasePlatform
oracle.toplink.essentials.platform.database.DB2MainframePlatform
oracle.toplink.essentials.platform.database.AccessPlatform

To use the Java Persistence API outside the EJB container (in Java SE mode), do not specify the jta-data-source or non-jta-data-source elements if the DataSource is not available. Instead, specify the provider element and any additional properties required by the JDBC driver or the database. For example:

<?xml version="1.0" encoding="UTF-8"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence">
        <persistence-unit name ="em2">
            <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
            <transaction-type>RESOURCE_LOCAL<transaction-type>
            <non-jta-data-source>jdbc/MyDB2DB</non-jta-data-source>
            <properties>
                <property name="toplink.platform.class.name" 
                    value="oracle.toplink.essentials.platform.database.DB2Platform"/>
                <!-- JDBC connection properties -->
                <property name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
                <property name="toplink.jdbc.url" 
value="jdbc:derby://localhost:1527/testdb;retrieveMessagesFromServerOnGetMessage=true;create=true;"/>
                <property name="toplink.jdbc.user" value="APP"/>
                <property name="toplink.jdbc.password" value="APP"/>
            </properties>
        </persistence-unit>
    </persistence>

For more information about toplink properties, see Additional Database Properties.

For a list of the JDBC drivers currently supported by the Enterprise Server, see the Sun GlassFish Enterprise Server v2.1.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

To change the persistence provider, see Changing the Persistence Provider.

Additional Database Properties

If you are using the default persistence provider, you can specify in the persistence.xml file the database properties listed at Persistence Unit Extensions in TopLink JPA Extensions Reference.

For schema generation properties, see Generation Options. For query hints, see Query Hints.

Configuring the Cache

If you are using the default persistence provider, you can configure whether caching occurs, the type of caching, the size of the cache, and whether client sessions share the cache. Caching properties for the default persistence provider are described in detail at Extensions for Caching in TopLink JPA Extensions Reference.

Setting the Logging Level

One of the default persistence provider's database properties that you can set in the persistence.xml file is toplink.logging.level. For example, setting the logging level to FINE or higher logs all SQL statements. For details about this property, see Extensions for Logging inTopLink JPA Extensions Reference.

You can also set the TopLink Essentials logging level globally in the Application Server in any of the following ways:

Setting the logging level to OFF disables TopLink Essentials logging. A logging level set in the persistence.xml file takes precedence over the global logging level.

You can set the logging level for Java Persistence in general using the Admin Console. In the developer profile, select the Application Server component and the Logging tab. In the cluster profile, select the Logger Settings component under the relevant configuration. Select the Log Levels tab. Then set the logging level for Persistence. Setting the logging level to OFF disables Java Persistence logging.

Using Lazy Loading

The default persistence provider treats only OneToOne, ManyToOne, OneToMany, and ManyToMany mappings specially when they are annotated as LAZY. OneToMany and ManyToMany mappings are loaded lazily by default in compliance with the Java Persistence Specification. Other mappings are always loaded eagerly. For OneToOne and ManyToOne mappings, value holder indirection is used. For OneToMany and ManyToMany mappings, transparent indirection is used.

For basic information about lazy loading, see Lazy Loading in TopLink JPA Extensions Reference. For details about indirection, see Indirection in Mapping Concepts.

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 Enterprise Server 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. This section covers the following topics:


Note –

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.

Supported Data Types

The following table shows mappings of Java types to SQL types when the default persistence provider and automatic schema generation are used.

Table 7–1 Java Type to SQL Type Mappings

Java Type 

Java DB, Derby, CloudScape 

Oracle 

DB2 

Sybase 

MS-SQL Server 

MySQL Server 

boolean, java.lang.Boolean

SMALLINT

NUMBER(1)

SMALLINT

BIT

BIT

TINYINT(1)

int, java.lang.Integer

INTEGER

NUMBER(10)

INTEGER

INTEGER

INTEGER

INTEGER

long, java.lang.Long

BIGINT

NUMBER(19)

INTEGER

NUMERIC(19)

NUMERIC(19)

BIGINT

float, java.lang.Float

FLOAT

NUMBER(19,4)

FLOAT

FLOAT(16)

FLOAT(16)

FLOAT

double, java.lang.Double

FLOAT

NUMBER(19,4)

FLOAT

FLOAT(32)

FLOAT(32)

DOUBLE

short, java.lang.Short

SMALLINT

NUMBER(5)

SMALLINT

SMALLINT

SMALLINT

SMALLINT

byte, java.lang.Byte

SMALLINT

NUMBER(3)

SMALLINT

SMALLINT

SMALLINT

SMALLINT

java.lang.Number

DECIMAL

NUMBER(38)

DECIMAL(15)

NUMERIC(38)

NUMERIC(28)

DECIMAL(38)

java.math.BigInteger

BIGINT

NUMBER(38)

BIGINT

NUMERIC(38)

NUMERIC(28)

BIGINT

java.math.BigDecimal

DECIMAL

NUMBER(38)

DECIMAL(15)

NUMERIC(38)

NUMERIC(28)

DECIMAL(38)

java.lang.String

VARCHAR(255)

VARCHAR(255)

VARCHAR(255)

VARCHAR(255)

VARCHAR(255)

VARCHAR(255)

char, java.lang.Character

CHAR(1)

CHAR(1)

CHAR(1)

CHAR(1)

CHAR(1)

CHAR(1)

byte[], java.lang.Byte[], java.sql.Blob

BLOB(64000)

LONG RAW

BLOB(64000)

IMAGE

IMAGE

BLOB(64000)

char[], java.lang.Character[], java.sql.Clob

CLOB(64000)

LONG

CLOB(64000)

TEXT

TEXT

TEXT(64000)

java.sql.Date

DATE

DATE

DATE

DATETIME

DATETIME

DATE

java.sql.Time

TIME

DATE

TIME

DATETIME

DATETIME

TIME

java.sql.Timestamp

TIMESTAMP

DATE

TIMESTAMP

DATETIME

DATETIME

DATETIME

Generation Options

Schema generation properties or asadmin command line options can control automatic schema generation by the following:


Note –

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


The following optional schema generation properties control the automatic creation of database tables at deployment. You can specify them in the persistence.xml file.

Table 7–2 Schema Generation Properties

Property 

Default 

Description 

toplink.ddl-generation

none

Specifies whether tables and DDL files are created during deployment, and whether tables are dropped first if they already exist. Allowed values are create-tables, drop-and-create-tables, and none.

If create-tables is specified, database tables are created for entities that need them.

If drop-and-create-tables is specified, 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 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 none is specified, no tables are created or dropped.

The asadmin generation options listed in Table 7–3 and Table 7–4 override the value of this property.

If you are using persistence outside the EJB container and would like to create the DDL files without creating tables, additionally define a Java system property INTERACT_WITH_DB and set its value to false.

toplink.create-ddl-jdbc-file-name

createDDL.jdbc

Specifies the name of the JDBC file that contains the DDL statements required to create the required objects (tables, sequences, and constraints) in the database. 

toplink.drop-ddl-jdbc-file-name

dropDDL.jdbc

Specifies the name of the JDBC file that contains the DDL statements required to drop the required objects (tables, sequences, and constraints) from the database. 

toplink.application-location

. for the current working directory

Specifies the location where the DDL files are written. 

For persistence within the EJB container, if this property is not set, DDL files are written to one of the following locations, for applications and modules, respectively: 

domain-dir/generated/ejb/j2ee-apps/app-name

domain-dir/generated/ejb/j2ee-modules/mod-name

toplink.ddl-generation.output-mode

both

Specifies the DDL generation target if you are in Java SE mode, outside the EJB container. Values are as follows: 

  • both – Generates SQL files and executes them on the database. If toplink.ddl-generation is set to create-tables, then toplink.create-ddl-jdbc-file-name is written to toplink.application-location and executed on the database. If toplink.ddl-generation is set to drop-and-create-tables, then both toplink.create-ddl-jdbc-file-name and toplink.drop-ddl-jdbc-file-name are written to toplink.application-location and both SQL files are executed on the database.

  • database – Executes SQL on the database only (does not generate SQL files). If toplink.ddl-generation is set to create-tables, then toplink.create-ddl-jdbc-file-name is executed on the database. It is not written to toplink.application-location. If toplink.ddl-generation is set to drop-and-create-tables, then both toplink.create-ddl-jdbc-file-name and toplink.drop-ddl-jdbc-file-name are executed on the database. Neither is written to toplink.application-location.

  • sql-script – Generates SQL files only (does not execute them on the database). If toplink.ddl-generation is set to create-tables, then toplink.create-ddl-jdbc-file-name is written to toplink.application-location. It is not executed on the database. If toplink.ddl-generation is set to drop-and-create-tables, then both toplink.create-ddl-jdbc-file-name and toplink.drop-ddl-jdbc-file-name are written to toplink.application-location. Neither is executed on the database.

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

Table 7–3 The asadmin deploy and asadmin deploydir Generation Options

Option 

Default 

Description 

--createtables

none 

If true, causes database tables to be created for entities that need them. If false, does not create tables. If not specified, the value of the toplink.ddl-generation property in persistence.xml is used.

--dropandcreatetables

none 

If true, and if tables were automatically created when this application was last deployed, tables from the earlier deployment are dropped and fresh ones are created.

If true, and if tables were not automatically created when this application was last deployed, no attempt is made to drop any tables. If tables with the same names as those that would have been automatically created are found, the deployment proceeds, but a warning is thrown to indicate that tables could not be created.

If false, the toplink.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 7–4 The asadmin undeploy Generation Options

Option 

Default 

Description 

--droptables

none 

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 toplink.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 Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

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

The asant tasks sun-appserv-deploy and sun-appserv-undeploy are equivalent to asadmin deploy and asadmin undeploy, respectively. These asant tasks also override the persistence.xml options. For details, see Chapter 3, The asant Utility.

Query Hints

Query hints are additional, implementation-specific configuration settings. You can use hints in your queries in the following format:

setHint("hint-name", hint-value)

For example:

Customer customer = (Customer)entityMgr.
     createNamedQuery("findCustomerBySSN").
     setParameter("SSN", "123-12-1234").
     setHint("toplink.refresh", true).
     getSingleResult();

For more information about the query hints available with the default provider, see Query Hints in TopLink JPA Extensions Reference.

Changing the Persistence Provider


Note –

The previous sections in this chapter apply only to the default persistence provider. If you change the provider for a module or application, the provider-specific database properties, query hints, and schema generation features described in this chapter do not apply.

The verifier utility always uses the default provider to verify persistence settings. For information about the verifier utility, see The verifier Utility in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.


You can change the persistence provider for an application in the manner described in the Java Persistence API Specification.

First, install the provider. Copy the provider JAR files to the domain-dir/lib directory, and restart the Enterprise Server. For more information about the domain-dir/lib directory, see Using the Common Class Loader. The new persistence provider is now available to all modules and applications deployed on servers that share the same configuration. However, the default provider remains the same.

In your persistence unit, specify the provider and any properties the provider requires in the persistence.xml file. For example:

<?xml version="1.0" encoding="UTF-8"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence">
        <persistence-unit name ="em3">
            <provider>com.company22.persistence.PersistenceProviderImpl</provider>
            <properties>
                <property name="company22.database.name" value="MyDB"/>
            </properties>
        </persistence-unit>
    </persistence>

Restrictions and Optimizations

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

Extended Persistence Context Failover

A reference to an extended persistence context in a stateful session bean or an HttpSession may not fail over successfully.

The Java Persistence API specification is not clear how the container and persistence provider should work together to passivate a stateful session bean with an extended persistence context in a stand-alone server instance. This also prevents successful serialization and storage of a reference to an extended persistence context in an HttpSession.

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. In this environment, it is safe to store an extended persistence context in a stateful session bean only if you can safely disable stateful session bean passivation altogether. This is possible, but trade-offs in memory utilization must be carefully examined before choosing this option.

In a single-instance environment, it is safe to store a reference to an extended persistence context in an HttpSession.

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:

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 Enterprise Server 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. Programmers must 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 Enterprise Server 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:

<sql-result-set-mapping name="SRSMName" >
   <entity-result entity-class="entities.someEntity" />
   <column-result name="UPPERCASECOLUMNNAME" />
</sql-result-set-mapping>

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 Enterprise Server for persistence.

Chapter 8 Developing Web and SIP Applications

This chapter describes how web applications are supported in the Sun GlassFish Enterprise Server and includes the following sections:

For general information about web applications, see “Part One: The Web Tier” in the Java EE 5 Tutorial.

Using Servlets

Enterprise Server supports the Java Servlet Specification version 2.5.


Note –

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


To develop servlets, use Sun Microsystems’ Java Servlet API. For information about using the Java Servlet API, see the documentation provided by Sun Microsystems at http://java.sun.com/products/servlet/index.html.

The Enterprise Server provides the wscompile and wsdeploy tools to help you implement a web service endpoint as a servlet. For more information about these tools, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

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

This section contains the following topics:

Invoking a Servlet With a URL

You can call a servlet deployed to the Enterprise Server by using a URL in a browser or embedded as a link in an HTML or JSP file. The format of a servlet invocation URL is as follows:

http://server:port/context-root/servlet-mapping?name=value

The following table describes each URL section.

Table 8–1 URL Fields for Servlets Within an Application

URL element 

Description 

server:port

The IP address (or host name) and optional port number. 

To access the default web module for a virtual server, specify only this URL section. You do not need to specify the context-root or servlet-name unless you also wish to specify name-value parameters.

context-root

For an application, the context root is defined in the context-root element of the application.xml, sun-application.xml, or sun-web.xml file. For an individually deployed web module, the context root is specified during deployment.

For both applications and individually deployed web modules, the default context root is the name of the WAR file minus the .war suffix.

servlet-mapping

The servlet-mapping as configured in the web.xml file.

?name=value...

Optional request parameters. 

In this example, localhost is the host name, MortPages is the context root, and calcMortgage is the servlet mapping:

http://localhost:8080/MortPages/calcMortgage?rate=8.0&per=360&bal=180000

When invoking a servlet from within a JSP file, you can use a relative path. For example:

<jsp:forward page="TestServlet"/>
<jsp:include page="TestServlet"/>

Servlet Output

ServletContext.log messages are sent to the server log.

By default, the System.out and System.err output of servlets are sent to the server log, and during startup, server log messages are echoed to the System.err output. Also by default, there is no Windows-only console for the System.err output.

You can change these defaults using the Admin Console. In the developer profile, select the Enterprise Server component and the Logging tab. In the cluster profile, select the Logger Settings component under the relevant configuration. Then check or uncheck Write to System Log. If this box is checked, System.out output is sent to the server log. If it is unchecked, System.out output is sent to the system default location only.

For more information, click the Help button in the Admin Console from the Logging page.

Caching Servlet Results

The Enterprise Server 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 Enterprise Server caches the request results for a specific amount of time. In this way, if another data call occurs, the Enterprise Server 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 an Enterprise Server web application handles response caching, you edit specific fields in the sun-web.xml file.


Note –

A servlet that uses caching is not portable.


For Javadoc tool pages relevant to caching servlet results, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.web.cache package.

For information about JSP caching, see JSP Caching.

The rest of this section covers the following topics:

Caching Features

The Enterprise Server 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 sun-web.xml file:

<cache max-capacity="8192" timeout="60">
<cache-helper name="myHelper" class-name="MyCacheHelper"/>
<cache-mapping>
	<servlet-name>myservlet</servlet-name>
	<timeout name="timefield">120</timeout>
	<http-method>GET</http-method>
	<http-method>POST</http-method>
</cache-mapping>
<cache-mapping>
	<url-pattern> /catalog/* </url-pattern>
	<!-- cache the best selling category; cache the responses to
	   -- this resource only when the given parameters exist. Cache
	   -- only when the catalog parameter has 'lilies' or 'roses'
	   -- but no other catalog varieties:
	  -- /orchard/catalog?best&category='lilies'
	  -- /orchard/catalog?best&category='roses'
	  -- but not the result of
	   -- /orchard/catalog?best&category='wild'
	-->
	<constraint-field name='best' scope='request.parameter'/>
	<constraint-field name='category' scope='request.parameter'>
		<value> roses </value>
		<value> lilies </value>
	</constraint-field>
	 <!-- Specify that a particular field is of given range but the
	   -- field doesn't need to be present in all the requests -->
	<constraint-field name='SKUnum' scope='request.parameter'>
		<value match-expr='in-range'> 1000 - 2000 </value>
	</constraint-field>
	<!-- cache when the category matches with any value other than
	   -- a specific value -->
	<constraint-field name="category" scope="request.parameter>
		<value match-expr="equals" cache-on-match-failure="true">
       bogus
		</value>
	</constraint-field>
</cache-mapping>
<cache-mapping>
	<servlet-name> InfoServlet </servlet-name>
	<cache-helper-ref>myHelper</cache-helper-ref>
</cache-mapping>
</cache>

For more information about the sun-web.xml caching settings, see cache in Sun GlassFish Enterprise Server v2.1.1 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 sun-web.xml deployment descriptor. For more information, see default-helper in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

About the Servlet Engine

Servlets exist in and are managed by the servlet engine in the Enterprise Server. 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. This section covers the following topics:

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 Enterprise Server hands the incoming data to the servlet engine. The servlet engine processes the request’s input data, such as form data, cookies, session information, and URL name-value pairs, into an HttpServletRequest request object type.

The servlet engine also creates an HttpServletResponse response object type. The engine then passes both as parameters to the servlet’s service() method.

In an HTTP servlet, the default service() method routes requests to another method based on the HTTP transfer method: POST, GET, DELETE, HEAD, OPTIONS, PUT, or TRACE. For example, HTTP POST requests are sent to the doPost() method, HTTP GET requests are sent to the doGet() method, and so on. This enables the servlet to process request data differently, depending on which transfer method is used. Since the routing takes place in the service method, you generally do not override service() in an HTTP servlet. Instead, override doGet(), doPost(), and so on, depending on the request type you expect.

To perform the tasks to answer a request, override the service() method for generic servlets, and the doGet() or doPost() methods for HTTP servlets. Very often, this means accessing EJB components to perform business transactions, then collating the information in the request object or in a JDBC ResultSet object.

Using JavaServer Pages

The Enterprise Server supports the following JSP features:

For information about creating JSP files, see Sun Microsystem’s JavaServer Pages web site at http://java.sun.com/products/jsp/index.html.

For information about Java Beans, see Sun Microsystem’s JavaBeans web page at http://java.sun.com/beans/index.html.

This section describes how to use JavaServer Pages (JSP files) as page templates in an Enterprise Server web application. This section contains the following topics:

JSP Tag Libraries and Standard Portable Tags

Enterprise Server supports tag libraries and standard portable tags. For more information, see the JavaServer Pages Standard Tag Library (JSTL) page at http://java.sun.com/products/jsp/jstl/index.jsp.

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 JavaServerTM Faces technology or JSTL, respectively. These tag libraries are automatically available to all web applications.

However, the as-install/lib/appserv-tags.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. JSP caching is described in the following topics:

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

The appserv-tags.jar File

JSP caching is implemented by a tag library packaged into the as-install/lib/appserv-tags.jar file, which you can copy into the WEB-INF/lib directory of your web application. The appserv-tags.tld tag library descriptor file is in the META-INF directory of this JAR file.


Note –

Web applications that use this tag library without bundling it are not portable.


To allow all web applications to share this tag library, change the following elements in the domain.xml file. Change this:

<jvm-options>
-Dcom.sun.enterprise.taglibs=appserv-jstl.jar,jsf-impl.jar
</jvm-options>

to this:

<jvm-options>
-Dcom.sun.enterprise.taglibs=appserv-jstl.jar,jsf-impl.jar,appserv-tags.jar
</jvm-options>

and this:

<jvm-options>
-Dcom.sun.enterprise.taglisteners=jsf-impl.jar
</jvm-options>

to this:

<jvm-options>
-Dcom.sun.enterprise.taglisteners=jsf-impl.jar,appserv-tags.jar
</jvm-options>

For more information about the domain.xml file, see the Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

Refer to these tags in JSP files as follows:

<%@ taglib prefix="prefix" uri="Sun ONE Application Server Tags" %>

Subsequently, the cache tags are available as <prefix:cache> and <prefix:flush>. For example, if your prefix is mypfx, the cache tags are available as <mypfx:cache> and <mypfx:flush>.

Caching Scope

JSP caching is available in three different scopes: request, session, and application. The default is application. To use a cache in request scope, a web application must specify the com.sun.appserv.web.taglibs.cache.CacheRequestListener in its web.xml deployment descriptor, as follows:

<listener>
   <listener-class>
      com.sun.appserv.web.taglibs.cache.CacheRequestListener
   </listener-class>
</listener>

Likewise, for a web application to utilize a cache in session scope, it must specify the com.sun.appserv.web.taglibs.cache.CacheSessionListener in its web.xml deployment descriptor, as follows:

<listener>
   <listener-class>
      com.sun.appserv.web.taglibs.cache.CacheSessionListener
   </listener-class>
</listener>

To utilize a cache in application scope, a web application need not specify any listener. The com.sun.appserv.web.taglibs.cache.CacheContextListener is already specified in the appserv-tags.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 8–2 The cache Attributes

Attribute 

Default 

Description 

key

ServletPath_Suffix

(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. 

timeout

60s

(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.

nocache

false

(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.

refresh

false

(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.

scope

application

(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="Sun ONE Application Server Tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<mypfx:cache                 key="${sessionScope.loginId}"
			nocache="${param.nocache}"
			refresh="${param.refresh}"
			timeout="10m">
<c:choose>
	<c:when test="${param.page == 'frontPage'}">
		<%-- get headlines from database --%>
	</c:when>
	<c:otherwise>
		...
	</c:otherwise>
</c:choose>
</mypfx:cache>
<mypfx:cache timeout="1h">
<h2> Local News </h2>
	<%-- get the headline news and cache them --%>
</mypfx:cache>

The flush Tag

Forces the cache to be 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 8–3 The flush Attributes

Attribute 

Default 

Description 

key

ServletPath_Suffix

(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. 

scope

application

(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":

<mypfx:flush key="foobar"/>

To flush the entire cache:

<c:if test="${empty sessionScope.clearCache}">
   <mypfx:flush />
</c:if>

Options for Compiling JSP Files

Enterprise Server provides the following ways of compiling JSP 2.1 compliant source files into servlets:

Creating and Managing Sessions

This chapter describes how to create and manage HTTP sessions that allows users and transaction information to persist between interactions.

This chapter contains the following sections:

Configuring Sessions

This section covers the following topics:

HTTP Sessions, Cookies, and URL Rewriting

To configure whether and how HTTP sessions use cookies and URL rewriting, edit the session-properties and cookie-properties elements in the sun-web.xml file for an individual web application. For more about the properties you can configure, see session-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide and cookie-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For information about configuring default session properties for the entire web container, see Chapter 8, SIP, Web, and EJB Containers, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide and the Sun GlassFish Enterprise Server v2.1.1 High Availability Administration Guide.

Coordinating Session Access

Make sure that multiple threads don’t simultaneously modify the same session object in conflicting ways. If the persistence type is ha (see The ha Persistence Type), the following message in the log file indicates that this might be happening:

Primary Key Constraint violation while saving session session_id

This is especially likely to occur in SIP applications where multiple SIP sessions share a SIP application session, and in converged applications where requests for the same session occur through HTTP and SIP protocols. It is likely to occur in pure web applications that use HTML frames where multiple servlets are executing simultaneously on behalf of the same client. A good solution is to ensure that one of the servlets modifies the session and the others have read-only access.

Distributed Sessions and Persistence


Note –

Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.


A distributed HTTP session can run in multiple Enterprise Server instances, provided the following criteria are met:


Note –

Contrary to the Servlet 2.5 specification, Enterprise Server does not throw an IllegalArgumentException if an object type not supported for failover is bound into a distributed session.

Keep the distributed session size as small as possible. Session size has a direct impact on overall system throughput.


In the event of an instance or hardware failure, another server instance can take over a distributed session, with the following limitations:

For information about how to work around these limitations, see the Sun GlassFish Enterprise Server v2.1.1 Deployment Planning Guide.

In the following table, No indicates that failover for the object type might not work in all cases and that no failover support is provided. However, failover might work in some cases for that object type. For example, failover might work because the class implementing that type is serializable.

For more information about the InitialContext, see Accessing the Naming Context. For more information about transaction recovery, see Chapter 16, Using the Transaction Service. For more information about Administered Objects, see Creating Physical Destinations.

Table 8–4 Object Types Supported for Java EE Web Application Session State Failover

Java Object Type 

Failover Support 

Colocated or distributed stateless session, stateful session, or entity bean reference 

Yes 

JNDI context 

Yes, InitialContext and java:comp/env

UserTransaction 

Yes, but if the instance that fails is never restarted, any prepared global transactions are lost and might not be correctly rolled back or committed. 

JDBC DataSource 

No 

Java Message Service (JMS) ConnectionFactory, Destination 

No 

JavaMail Session 

No 

Connection Factory 

No 

Administered Object 

No 

Web service reference 

No 

Serializable Java types 

Yes 

Extended persistence context 

No 

Session Managers

A session manager automatically creates new session objects whenever a new session starts. In some circumstances, clients do not join the session, for example, if the session manager uses cookies and the client does not accept cookies.

Enterprise Server offers these session management options, determined by the session-manager element’s persistence-type attribute in the sun-web.xml file:


Note –

If the session manager configuration contains an error, the error is written to the server log and the default (memory) configuration is used.


For more information, see session-manager in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The memory Persistence Type

This persistence type is not designed for a production environment that requires session persistence. It provides no session persistence. However, you can configure it so that the session state in memory is written to the file system prior to server shutdown.

To specify the memory persistence type for the entire web container, use the configure-ha-persistence command. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

To specify the memory persistence type for a specific web application, edit the sun-web.xml file as in the following example. The persistence-type property is optional, but must be set to memory if included. This overrides the web container availability settings for the web application.

<sun-web-app>
...
<session-config>
	<session-manager persistence-type="memory" />
		<manager-properties>
			<property name="sessionFilename" value="sessionstate" />
		</manager-properties>
	</session-manager>
	...
</session-config>
...
</sun-web-app>

The only manager property that the memory persistence type supports is sessionFilename, which is listed under manager-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The file Persistence Type

This persistence type provides session persistence to the local file system, and allows a single server domain to recover the session state after a failure and restart. The session state is persisted in the background, and the rate at which this occurs is configurable. The store also provides passivation and activation of the session state to help control the amount of memory used. This option is not supported in a production environment. However, it is useful for a development system with a single server instance.


Note –

Make sure the delete option is set in the server.policy file, or expired file-based sessions might not be deleted properly. For more information about server.policy, see The server.policy File.


To specify the file persistence type for the entire web container, use the configure-ha-persistence command. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

To specify the file persistence type for a specific web application, edit the sun-web.xml file as in the following example. Note that persistence-type must be set to file. This overrides the web container availability settings for the web application.

<sun-web-app>
...
<session-config>
	<session-manager persistence-type="file">
		<store-properties>
			<property name="directory" value="sessiondir" />
		</store-properties>
	</session-manager>
	...
</session-config>
...
</sun-web-app>

The file persistence type supports all the manager properties listed under manager-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide except sessionFilename, and supports the directory store property listed under store-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The replicated Persistence Type

The replicated persistence type uses other servers in the cluster for session persistence. Clustered server instances replicate session state in a predictive manner so that the state is saved where it is most likely to be needed. Each backup instance stores the replicated data in memory. This allows sessions to be distributed. For details, see Distributed Sessions and Persistence. In addition, you can configure the frequency and scope of session persistence. The other servers are also used as the passivation and activation store. Use this option in a production environment that requires session persistence.


Note –

Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.


To use the replicated persistence type, you must first enable availability. Select the Availability Service component under the relevant configuration in the Admin Console. Check the Availability Service box. To enable availability for the web container, select the Web Container Availability tab, then check the Availability Service box. All instances in a Enterprise Server cluster should have the same availability settings to ensure consistent behavior. For details, see the Sun GlassFish Enterprise Server v2.1.1 High Availability Administration Guide.

To change settings such as persistence frequency and persistence scope for the entire web container, use the Persistence Frequency and Persistence Scope drop-down lists on the Web Container Availability tab in the Admin Console, or use the asadmin set command. For example:


asadmin set 
server-config.availability-service.web-container-availability.persistence-frequency=time-based

For more information, see the description of the asadmin set command in the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

To specify the replicated persistence type for a specific web application, edit the sun-web.xml file as in the following example. Note that persistence-type must be set to replicated. This overrides the web container availability settings for the web application.

<sun-web-app>
...
<session-config>
	<session-manager persistence-type="replicated">
		<manager-properties>
			<property name="persistenceFrequency" value="web-method" />
		</manager-properties>
		<store-properties>
			<property name="persistenceScope" value="session" />
		</store-properties>
	</session-manager>
	...
</session-config>
...
</sun-web-app>

The replicated persistence type supports all the manager properties listed under manager-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide except sessionFilename, and supports the persistenceScope store property listed under store-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The ha Persistence Type

The ha persistence type uses the high-availability database (HADB) for session persistence. The HADB must be installed and the enterprise profile must be selected. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

The HADB allows sessions to be distributed. For details, see Distributed Sessions and Persistence. In addition, you can configure the frequency and scope of session persistence. The HADB is also used as the passivation and activation store. Use this option in a production environment that requires session persistence.

The HADB must be configured and enabled before you can use distributed sessions. For configuration details, see the description of the configure-ha-cluster command in the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

To enable the HADB, select the Availability Service component under the relevant configuration in the Admin Console. Check the Instance Level Availability box. To enable availability for the web container, select the Web Container Availability tab, then check the Availability Service box. All instances in an Enterprise Server cluster should have the same availability settings to ensure consistent behavior. For details, see the Sun GlassFish Enterprise Server v2.1.1 High Availability Administration Guide.

To change settings such as persistence frequency and persistence scope for the entire web container, see the description of the configure-ha-persistence command in the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

To specify the ha persistence type for a specific web application, edit the sun-web.xml file as in the following example. Note that persistence-type must be set to ha. This overrides the web container availability settings for the web application.

<sun-web-app>
...
<session-config>
	<session-manager persistence-type="ha">
		<manager-properties>
			<property name="persistenceFrequency" value="web-method" />
		</manager-properties>
		<store-properties>
			<property name="persistenceScope" value="session" />
		</store-properties>
	</session-manager>
	...
</session-config>
...
</sun-web-app>

The ha persistence type supports all the manager properties listed under manager-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide except sessionFilename, and supports the persistenceScope store property listed under store-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Advanced Web Application Features

This section includes summaries of the following topics:

Internationalization Issues

This section covers internationalization as it applies to the following:

The Server's Default Locale

To set the default locale of the entire Enterprise Server, which determines the locale of the Admin Console, the logs, and so on, use the Admin Console. In the developer profile, select the Enterprise Server component, the Advanced tab, and the Domain Attributes tab. In the cluster profile, select the domain component. Then type a value in the Locale field. For details, click the Help button in the Admin Console.

Servlet Character Encoding

This section explains how the Enterprise Server determines the character encoding for the servlet request and the servlet response. For encodings you can use, see http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html.

Servlet Request

When processing a servlet request, the server uses the following order of precedence, first to last, to determine the request character encoding:

For details about the parameter-encoding element, see parameter-encoding in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Servlet Response

When processing a servlet response, the server uses the following order of precedence, first to last, to determine the response character encoding:

Virtual Servers

A virtual server, also called a virtual host, is a virtual web server that serves content targeted for a specific URL. Multiple virtual servers can serve content using the same or different host names, port numbers, or IP addresses. The HTTP service directs incoming web requests to different virtual servers based on the URL.

When you first install the Enterprise Server, a default virtual server is created. You can also assign a default virtual server to each new HTTP listener you create.

Web applications and Java EE applications containing web components (web modules) can be assigned to virtual servers during deployment. A web module can be assigned to more than one virtual server, and a virtual server can have more than one web module assigned to it.

For more information about virtual servers, see virtual-server in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

ProcedureTo Assign a Default Virtual Server

  1. In the Admin Console, open the HTTP Service component under the relevant configuration.

  2. Open the HTTP Listeners component under the HTTP Service component.

  3. Select or create a new HTTP listener.

  4. Select from the Default Virtual Server drop-down list.

    For more information, see Default Web Modules.

See Also

For details, click the Help button in the Admin Console from the HTTP Listeners page.

ProcedureTo Assign Virtual Servers

  1. Deploy the application or web module and assign the desired virtual servers to it.

    For more information, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

  2. In the Admin Console, open the HTTP Service component under the relevant configuration.

  3. Open the Virtual Servers component under the HTTP Service component.

  4. Select the virtual server to which you want to assign a default web module.

  5. Select the application or web module from the Default Web Module drop-down list.

    For more information, see Default Web Modules.

See Also

For details, click the Help button in the Admin Console from the Virtual Servers page.

Default Web Modules

A default web module can be assigned to the default virtual server and to each new virtual server. For details, see Virtual Servers. To access the default web module for a virtual server, point the browser to the URL for the virtual server, but do not supply a context root. For example:

http://myvserver:3184/

A virtual server with no default web module assigned serves HTML or JavaServer PagesTM (JSPTM) content from its document root, which is usually domain-dir/docroot. To access this HTML or JSP content, point your browser to the URL for the virtual server, do not supply a context root, but specify the target file.

For example:

http://myvserver:3184/hellothere.jsp

Class Loader Delegation

The Servlet specification recommends that the Web class loader look in the local class loader before delegating to its parent. To make the Web class loader follow the delegation model in the Servlet specification, set delegate="false" in the class-loader element of the sun-web.xml file. It’s safe to do this only for a web module that does not interact with any other modules.

The default value is delegate="true", which causes the Web class loader to delegate in the same manner as the other class loaders. Use delegate="true" for a web application that accesses EJB components or that acts as a web service client or endpoint. For details about sun-web.xml, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For general information about class loaders, see Chapter 2, Class Loaders.

Using the default-web.xml File

You can use the default-web.xml file to define features such as filters and security constraints that apply to all web applications.

For example, you can disable directory listings for added security. In your domain's default-web.xml file, search for the definition of the servlet whose servlet-name is equal to default, and set the value of the init-param named listings to false. Then redeploy your web application if it has already been deployed.

<init-param>
   <param-name>listings</param-name>
   <param-value>false</param-value>
</init-param>

The mime-mapping elements in default-web.xml are global and inherited by all web applications. You can override these mappings or define your own using mime-mapping elements in your web application's web.xml file. For more information about mime-mapping elements, see the Servlet specification.

You can use the Admin Console to edit the default-web.xml file. For details, click the Help button in the Admin Console. As an alternative, you can edit the file directly using the following steps.

ProcedureTo Use the default-web.xml File

  1. Place the JAR file for the filter, security constraint, or other feature in the domain-dir/lib directory.

  2. Edit the domain-dir/config/default-web.xml file to refer to the JAR file.

  3. Restart the server.

Configuring Logging and Monitoring in the Web Container

For information about configuring logging and monitoring in the web container using the Admin Console, click the Help button in the Admin Console. In the developer profile, Logging and Monitor tabs are accessible from the Application Server page. In the Cluster profile, select Logger Settings under the relevant configuration, or select the Stand-Alone Instances component, select the instance from the table, and select the Monitor tab.

Configuring Idempotent URL Requests

An idempotent request is one that does not cause any change or inconsistency in an application when retried. To enhance the availability of your applications deployed on an Enterprise Server cluster, configure the load balancer to retry failed idempotent HTTP requests on all the Enterprise Server instances in a cluster. This option can be used for read-only requests, for example, to retry a search request.

This section describes the following topics:

Specifying an Idempotent URL

To configure idempotent URL response, specify the URLs that can be safely retried in idempotent-url-pattern elements in the sun-web.xml file. For example:

<idempotent-url-pattern url-pattern="sun_java/*" no-of-retries="10"/>

For details, see idempotent-url-pattern in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

If none of the server instances can successfully serve the request, an error page is returned.

Characteristics of an Idempotent URL

Since all requests for a given session are sent to the same application server instance, and if that Enterprise Server instance is unreachable, the load balancer returns an error message. Normally, the request is not retried on another Enterprise Server instance. However, if the URL pattern matches that specified in the sun-web.xml file, the request is implicitly retried on another Enterprise Server instance in the cluster.

In HTTP, some methods (such as GET) are idempotent, while other methods (such as POST) are not. In effect, retrying an idempotent URL should not cause values to change on the server or in the database. The only difference should be a change in the response received by the user.

Examples of idempotent requests include search engine queries and database queries. The underlying principle is that the retry does not cause an update or modification of data.

A search engine, for example, sends HTTP requests with the same URL pattern to the load balancer. Specifying the URL pattern of the search request to the load balancer ensures that HTTP requests with the specified URL pattern are implicitly retried on another Enterprise Server instance.

For example, if the request URL sent to the Enterprise Server is of the type /search/something.html, then the URL pattern can be specified as /search/*.

Examples of non-idempotent requests include banking transactions and online shopping. If you retry such requests, money might be transferred twice from your account.

Header Management

In all Editions of the Enterprise Server, the Enumeration from request.getHeaders() contains multiple elements (one element per request header) instead of a single, aggregated value.

The header names used in HttpServletResponse.addXXXHeader() and HttpServletResponse.setXXXHeader() are returned as they were created.

Configuring Valves and Catalina Listeners

You can configure custom valves and Catalina listeners for web modules or virtual servers by defining properties. In the domain.xml file, valve and listener properties look like this:

<web-module ...>
   <property name="valve_1" value="org.glassfish.extension.Valve"/>
   <property name="listener_1" value="org.glassfish.extension.MyLifecycleListener"/>
</web-module>

You can define these properties in one of the following ways, then restart the server:

Alternate Document Roots

An alternate document root (docroot) allows a web application to serve requests for certain resources from outside its own docroot, based on whether those requests match one (or more) of the URI patterns of the web application's alternate docroots.

To specify an alternate docroot for a web application or a virtual server, use the alternatedocroot_n property, where n is a positive integer that allows specification of more than one. This property can be a subelement of a sun-web-app element in the sun-web.xml file or a virtual-server element in the domain.xml file. For more information about these elements, see sun-web-app in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide and virtual-server in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

A virtual server's alternate docroots are considered only if a request does not map to any of the web modules deployed on that virtual server. A web module's alternate docroots are considered only once a request has been mapped to that web module.

If a request matches an alternate docroot's URI pattern, it is mapped to the alternate docroot by appending the request URI (minus the web application's context root) to the alternate docroot's physical location (directory). If a request matches multiple URI patterns, the alternate docroot is determined according to the following precedence order:

For example, the following properties specify three docroots. The URI pattern of the first alternate docroot uses an exact match, whereas the URI patterns of the second and third alternate docroots use extension and longest path prefix matches, respectively.

<property name="alternatedocroot_1" value="from=/my.jpg dir=/srv/images/jpg"/>
<property name="alternatedocroot_2" value="from=*.jpg dir=/srv/images/jpg"/>
<property name="alternatedocroot_3" value="from=/jpg/* dir=/src/images"/>

The value of each alternate docroot has two components: The first component, from, specifies the alternate docroot's URI pattern, and the second component, dir, specifies the alternate docroot's physical location (directory).

Suppose the above examples belong to a web application deployed at http://company22.com/myapp. The first alternate docroot maps any requests with this URL:


http://company22.com/myapp/my.jpg

To this resource:


/svr/images/jpg/my.jpg

The second alternate docroot maps any requests with a *.jpg suffix, such as:


http://company22.com/myapp/*.jpg

To this physical location:


/svr/images/jpg

The third alternate docroot maps any requests whose URI starts with /myapp/jpg/, such as:


http://company22.com/myapp/jpg/*

To the same directory as the second alternate docroot.

For example, the second alternate docroot maps this request:


http://company22.com/myapp/abc/def/my.jpg

To:


/srv/images/jpg/abc/def/my.jpg

The third alternate docroot maps:


http://company22.com/myapp/jpg/abc/resource

To:


/srv/images/jpg/abc/resource

If a request does not match any of the target web application's alternate docroots, or if the target web application does not specify any alternate docroots, the request is served from the web application's standard docroot, as usual.

Redirecting URLs

You can specify that a request for an old URL is treated as a request for a new URL. This is called redirecting a URL.

To specify a redirected URL for a virtual server, use the redirect_n property, where n is a positive integer that allows specification of more than one. This property is a subelement of a virtual-server element in the domain.xml file. For more information about this element, see virtual-server in Sun GlassFish Enterprise Server v2.1.1 Administration Reference. Each of these redirect_n properties is inherited by all web applications deployed on the virtual server.

The value of each redirect_n property has two components, which may be specified in any order:

The first component, from, specifies the prefix of the requested URI to match.

The second component, url-prefix, specifies the new URL prefix to return to the client. The from prefix is simply replaced by this URL prefix.

For example:

<property name="redirect_1" value="from=/dummy url-prefix=http://etude"/>

Enabling Comet Support

To enable Comet support for an HTTP listener and all its associated web applications, set the cometSupport property to true. For more information, see http-listener in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

If your servlet or JSP page uses Comet technology, make sure it is initialized when the Enterprise Server starts up by adding the load-on-startup element to your web.xml file. For example:

<servlet>
   <servlet-name>CheckIn</servlet-name>
   <servlet-class>CheckInServlet</servlet-class>
   <load-on-startup>0</load-on-startup>
</servlet>

Using a context.xml File

Use the contextXmlDefault property to specify the location, relative to domain-dir, of the context.xml file for a virtual server. For more information about virtual servers, see Virtual Servers. For more information about the context.xml file, see The Context Container.

Enabling WebDav

To enable WebDav in the Enterprise Server, you edit the web.xml and sun-web.xml files as follows.

First, enable the WebDav servlet in your web.xml file:

<servlet>
   <servlet-name>webdav</servlet-name>
   <servlet-class>org.apache.catalina.servlets.WebdavServlet</servlet-class>
   <init-param>
      <param-name>debug</param-name>
      <param-value>0</param-value>
   </init-param>
   <init-param>
      <param-name>listings</param-name>
      <param-value>true</param-value>
   </init-param>
   <init-param>
      <param-name>readonly</param-name>
      <param-value>false</param-value>
   </init-param>
</servlet>

Then define the servlet mapping associated with your WebDav servlet in your web.xml file:

<servlet-mapping>
   <servlet-name>webdav</servlet-name>
   <url-pattern>/webdav/*</url-pattern>
</servlet-mapping>

To protect the WebDav servlet so other users can't modify it, add a security constraint in your web.xml file:

<security-constraint>
   <web-resource-collection>
      <web-resource-name>Login Resources</web-resource-name>
      <url-pattern>/webdav/*</url-pattern>
   </web-resource-collection>
   <auth-constraint>
      <role-name>Admin</role-name>
   </auth-constraint>
   <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
   </user-data-constraint>
   <login-config>
      <auth-method>BASIC</auth-method>
      <realm-name>default</realm-name>
   </login-config>
   <security-role>
      <role-name>Admin</role-name>
   </security-role>
</security-constraint>

Then define a security role mapping in your sun-web.xml file:

<security-role-mapping>
   <role-name>Admin</role-name>
   <group-name>Admin</group-name>
</security-role-mapping>

If you are using the file realm, create a user and password. For example:


asadmin create-file-user --user admin --host localhost --port 4848 --terse=true 
--groups Admin --authrealmname default admin

You can now use any WebDav client by connecting to the WebDav servlet URL, which has this format:


http://host:port/context-root/webdav/file

For example:


http://localhost:80/glassfish-webdav/webdav/index.html

You can add the WebDav servlet to your default-web.xml file to enable it for all applications, but you can't set up a security role mapping to protect it.

Using mod_jk

To set up mod_jk, follow these steps:

  1. Obtain the following software:

  2. Install mod_jk as described at http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html.

  3. Copy the following Tomcat and Jakarta Commons files to as-install/lib:

    • tomcat-ajp.jar

    • commons-logging.jar

    • commons-modeler.jar

  4. Create and configure the following files:

    Examples of these files are shown after these steps. If you use both worker.properties and glassfish-jk.properties files, the file referenced by httpd.conf, or referenced by httpd.conf first, takes precedence.

  5. Start httpd.

  6. Enable mod_jk using the following command:


    asadmin create-jvm-options -Dcom.sun.enterprise.web.connector.enableJK=8009
  7. If you are using the glassfish-jk.properties file and not referencing it in httpd.conf, point to it using the following command:


    asadmin create-jvm-options 
    -Dcom.sun.enterprise.web.connector.enableJK.propertyFile=domain-dir/config/glassfish-jk.properties
  8. Restart the Enterprise Server.

Here is an example httpd.conf file:

LoadModule jk_module /usr/lib/httpd/modules/mod_jk.so
JkWorkersFile /etc/httpd/conf/worker.properties
# Where to put jk logs
JkLogFile /var/log/httpd/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel debug
# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"
# Send all jsp requests to GlassFish
JkMount /*.jsp worker1
# Send all glassfish-test requests to GlassFish
JkMount /glassfish-test/* worker1

Here is an example worker.properties or glassfish-jk.properties file:

# Define 1 real worker using ajp13
worker.list=worker1
# Set properties for worker1 (ajp13)
worker.worker1.type=ajp13
worker.worker1.host=localhost.localdomain
worker.worker1.port=8009
worker.worker1.lbfactor=50
worker.worker1.cachesize=10
worker.worker1.cache_timeout=600
worker.worker1.socket_keepalive=1
worker.worker1.socket_timeout=300

Chapter 9 Using Enterprise JavaBeans Technology

This chapter describes how Enterprise JavaBeansTM (EJBTM) technology is supported in the Sun GlassFish Enterprise Server. This chapter addresses the following topics:

For general information about enterprise beans, see “Part Three: Enterprise Beans” in the Java EE 5 Tutorial.

Summary of EJB 3.0 Changes

The Enterprise Server supports and is compliant with the Sun Microsystems Enterprise JavaBeans (EJB) architecture as defined by the Enterprise JavaBeans Specification, v3.0, also known as JSR 220.


Note –

The Enterprise Server is backward compatible with 1.1, 2.0, and 2.1 enterprise beans. However, to take advantage of version 3.0 features, you should develop new beans as 3.0 enterprise beans.


The main changes in the Enterprise JavaBeans Specification, v3.0 that impact enterprise beans in the Enterprise Server environment are as follows:

Value Added Features

The Enterprise Server provides a number of value additions that relate to EJB development. These capabilities are discussed in the following sections. References to more in-depth material are included.

Read-Only Beans

Another feature that the Enterprise Server provides is the read-only bean, an EJB 2.1 entity bean that is never modified by an EJB client. Read-only beans avoid database updates completely.


Note –

Read-only beans are specific to the Enterprise Server and are not part of the Enterprise JavaBeans Specification, v2.1. Use of this feature for an EJB 2.1 bean results in a non-portable application.

To make an EJB 3.0 entity read-only, use @Column annotations to mark its columns insertable=false and updatable=false.


A read-only bean can be used to cache a database entry that is frequently accessed but rarely updated (externally by other beans). When the data that is cached by a read-only bean is updated by another bean, the read-only bean can be notified to refresh its cached data.

The Enterprise Server provides a number of ways by which a read-only bean’s state can be refreshed. By setting the refresh-period-in-seconds element in the sun-ejb-jar.xml file and the trans-attribute element (or @TransactionAttribute annotation) in the ejb-jar.xml file, it is easy to configure a read-only bean that is one of the following:

Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. For further information and usage guidelines, see Using Read-Only Beans.

The pass-by-reference Element

The pass-by-reference element in the sun-ejb-jar.xml file allows you to specify the parameter passing semantics for colocated remote EJB invocations. This is an opportunity to improve performance. However, use of this feature results in non-portable applications. See pass-by-reference in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Pooling and Caching

The EJB container of the Enterprise Server pools anonymous instances (message-driven beans, stateless session beans, and entity beans) to reduce the overhead of creating and destroying objects. The EJB container maintains the free pool for each bean that is deployed. Bean instances in the free pool have no identity (that is, no primary key associated) and are used to serve method calls. The free beans are also used to serve all methods for stateless session beans.

Bean instances in the free pool transition from a Pooled state to a Cached state after ejbCreate and the business methods run. The size and behavior of each pool is controlled using pool-related properties in the EJB container or the sun-ejb-jar.xml file.

In addition, the Enterprise Server supports a number of tunable parameters that can control the number of “stateful” instances (stateful session beans and entity beans) cached as well as the duration they are cached. Multiple bean instances that refer to the same database row in a table can be cached. The EJB container maintains a cache for each bean that is deployed.

To achieve scalability, the container selectively evicts some bean instances from the cache, usually when cache overflows. These evicted bean instances return to the free bean pool. The size and behavior of each cache can be controlled using the cache-related properties in the EJB container or the sun-ejb-jar.xml file.

Pooling and caching parameters for the sun-ejb-jar.xml file are described in bean-cache in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Pooling Parameters

One of the most important parameters of Enterprise Server pooling is steady-pool-size. When steady-pool-size is set to greater than 0, the container not only pre-populates the bean pool with the specified number of beans, but also attempts to ensure that this number of beans is always available in the free pool. This ensures that there are enough beans in the ready to serve state to process user requests.

This parameter does not necessarily guarantee that no more than steady-pool-size instances exist at a given time. It only governs the number of instances that are pooled over a long period of time. For example, suppose an idle stateless session container has a fully-populated pool with a steady-pool-size of 10. If 20 concurrent requests arrive for the EJB component, the container creates 10 additional instances to satisfy the burst of requests. The advantage of this is that it prevents the container from blocking any of the incoming requests. However, if the activity dies down to 10 or fewer concurrent requests, the additional 10 instances are discarded.

Another parameter, pool-idle-timeout-in-seconds, allows the administrator to specify the amount of time a bean instance can be idle in the pool. When pool-idle-timeout-in-seconds is set to greater than 0, the container removes or destroys any bean instance that is idle for this specified duration.

Caching Parameters

Enterprise Server provides a way that completely avoids caching of entity beans, using commit option C. Commit option C is particularly useful if beans are accessed in large number but very rarely reused. For additional information, refer to Commit Options.

The Enterprise Server caches can be either bounded or unbounded. Bounded caches have limits on the number of beans that they can hold beyond which beans are passivated. For stateful session beans, there are three ways (LRU, NRU and FIFO) of picking victim beans when cache overflow occurs. Caches can also passivate beans that are idle (not accessed for a specified duration).

Bean-Level Container-Managed Transaction Timeouts

The default transaction timeout for the domain is specified using the Transaction Timeout setting of the Transaction Service. A transaction started by the container must commit (or rollback) within this time, regardless of whether the transaction is suspended (and resumed), or the transaction is marked for rollback.

To override this timeout for an individual bean, use the optional cmt-timeout-in-seconds element in sun-ejb-jar.xml. The default value, 0, specifies that the default Transaction Service timeout is used. The value of cmt-timeout-in-seconds is used for all methods in the bean that start a new container-managed transaction. This value is not used if the bean joins a client transaction.

Priority Based Scheduling of Remote Bean Invocations

You can create multiple thread pools, each having its own work queues. An optional element in the sun-ejb-jar.xml file, use-thread-pool-id, specifies the thread pool that processes the requests for the bean. The bean must have a remote interface, or use-thread-pool-id is ignored. You can create different thread pools and specify the appropriate thread pool ID for a bean that requires a quick response time. If there is no such thread pool configured or if the element is absent, the default thread pool is used.

Immediate Flushing

Normally, all entity bean updates within a transaction are batched and executed at the end of the transaction. The only exception is the database flush that precedes execution of a finder or select query.

Since a transaction often spans many method calls, you might want to find out if the updates made by a method succeeded or failed immediately after method execution. To force a flush at the end of a method’s execution, use the flush-at-end-of-method element in the sun-ejb-jar.xml file. Only non-finder methods in an entity bean can be flush-enabled. (For an EJB 2.1 bean, these methods must be in the Local, Local Home, Remote, or Remote Home interface.) See flush-at-end-of-method in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Upon completion of the method, the EJB container updates the database. Any exception thrown by the underlying data store is wrapped as follows:

All normal end-of-transaction database synchronization steps occur regardless of whether the database has been flushed during the transaction.

EJB Timer Service

The EJB Timer Service uses a database to store persistent information about EJB timers. In the developer profile, the EJB Timer Service in Enterprise Server is preconfigured to use an embedded version of the Java DB database. The EJB Timer Service configuration can store persistent timer information in any database supported by the Enterprise Server for persistence.

For a list of the JDBC drivers currently supported by the Enterprise Server, see the Sun GlassFish Enterprise Server v2.1.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

To change the database used by the EJB Timer Service, set the EJB Timer Service’s Timer DataSource setting to a valid JDBC resource. You must also create the timer database table. DDL files are located in as-install/lib/install/databases. Ideally, each cluster should have its own timer table.

Using the EJB Timer Service is equivalent to interacting with a single JDBC resource manager. If an EJB component or application accesses a database either directly through JDBC or indirectly (for example, through an entity bean’s persistence mechanism), and also interacts with the EJB Timer Service, its data source must be configured with an XA JDBC driver.

You can change the following EJB Timer Service settings. You must restart the server for the changes to take effect.

For information about configuring EJB Timer Service settings, see Chapter 8, SIP, Web, and EJB Containers, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide. For information about the asadmin list-timers and asadmin migrate-timers commands, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Using Session Beans

This section provides guidelines for creating session beans in the Enterprise Server environment. This section addresses the following topics:

Extensive information on session beans is contained in Chapters 3 and 4 of the Enterprise JavaBeans Specification, v3.0, EJB Core Contracts and Requirements.

About the Session Bean Containers

Like an entity bean, a session bean can access a database through Java Database Connectivity (JDBC) calls. A session bean can also provide transaction settings. These transaction settings and JDBC calls are referenced by the session bean’s container, allowing it to participate in transactions managed by the container.

A container managing stateless session beans has a different charter from a container managing stateful session beans. This section addresses the following topics:

Stateless Container

The stateless container manages stateless session beans, which, by definition, do not carry client-specific states. All session beans (of a particular type) are considered equal.

A stateless session bean container uses a bean pool to service requests. The Enterprise Server specific deployment descriptor file, sun-ejb-jar.xml, contains the properties that define the pool:

For more information about sun-ejb-jar.xml, see The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The Enterprise Server provides the wscompile and wsdeploy tools to help you implement a web service endpoint as a stateless session bean. For more information about these tools, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Stateful Container

The stateful container manages the stateful session beans, which, by definition, carry the client-specific state. There is a one-to-one relationship between the client and the stateful session beans. At creation, each stateful session bean (SFSB) is given a unique session ID that is used to access the session bean so that an instance of a stateful session bean is accessed by a single client only.

Stateful session beans are managed using cache. The size and behavior of stateful session beans cache are controlled by specifying the following sun-ejb-jar.xml parameters:

The max-cache-size element specifies the maximum number of session beans that are held in cache. If the cache overflows (when the number of beans exceeds max-cache-size), the container then passivates some beans or writes out the serialized state of the bean into a file. The directory in which the file is created is obtained from the EJB container using the configuration APIs.

For more information about sun-ejb-jar.xml, see The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The passivated beans are stored on the file system. The Session Store Location setting in the EJB container allows the administrator to specify the directory where passivated beans are stored. By default, passivated stateful session beans are stored in application-specific subdirectories created under domain-dir/session-store.


Note –

Make sure the delete option is set in the server.policy file, or expired file-based sessions might not be deleted properly. For more information about server.policy, see The server.policy File.


The Session Store Location setting also determines where the session state is persisted if it is not highly available; see Choosing a Persistence Store.

Stateful Session Bean Failover

An SFSB’s state can be saved in a persistent store in case a server instance fails. The state of an SFSB is saved to the persistent store at predefined points in its life cycle. This is called checkpointing. If SFSB checkpointing is enabled, checkpointing generally occurs after any transaction involving the SFSB is completed, even if the transaction rolls back.

However, if an SFSB participates in a bean-managed transaction, the transaction might be committed in the middle of the execution of a bean method. Since the bean’s state might be undergoing transition as a result of the method invocation, this is not an appropriate instant to checkpoint the bean’s state. In this case, the EJB container checkpoints the bean’s state at the end of the corresponding method, provided the bean is not in the scope of another transaction when that method ends. If a bean-managed transaction spans across multiple methods, checkpointing is delayed until there is no active transaction at the end of a subsequent method.

The state of an SFSB is not necessarily transactional and might be significantly modified as a result of non-transactional business methods. If this is the case for an SFSB, you can specify a list of checkpointed methods. If SFSB checkpointing is enabled, checkpointing occurs after any checkpointed methods are completed.


Note –

Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.


The following table lists the types of references that SFSB failover supports. All objects bound into an SFSB must be one of the supported types. In the table, No indicates that failover for the object type might not work in all cases and that no failover support is provided. However, failover might work in some cases for that object type. For example, failover might work because the class implementing that type is serializable.

Table 9–1 Object Types Supported for Java EE Stateful Session Bean State Failover

Java Object Type 

Failover Support 

Colocated or distributed stateless session, stateful session, or entity bean reference 

Yes 

JNDI context 

Yes, InitialContext and java:comp/env

UserTransaction 

Yes, but if the instance that fails is never restarted, any prepared global transactions are lost and might not be correctly rolled back or committed. 

JDBC DataSource 

No 

Java Message Service (JMS) ConnectionFactory, Destination 

No 

JavaMail Session 

No 

Connection Factory 

No 

Administered Object 

No 

Web service reference 

No 

Serializable Java types 

Yes 

Extended persistence context 

No 

For more information about the InitialContext, see Accessing the Naming Context. For more information about transaction recovery, see Chapter 16, Using the Transaction Service. For more information about Administered Objects, see Creating Physical Destinations.


Note –

Idempotent URLs are supported along the HTTP path, but not the RMI-IIOP path. For more information, see Configuring Idempotent URL Requests.

If a server instance to which an RMI-IIOP client request is sent crashes during the request processing (before the response is prepared and sent back to the client), an error is sent to the client. The client must retry the request explicitly. When the client retries the request, the request is sent to another server instance in the cluster, which retrieves session state information for this client.

HTTP sessions can also be saved in a persistent store in case a server instance fails. In addition, if a distributable web application references an SFSB, and the web application’s session fails over, the EJB reference is also failed over. For more information, see Distributed Sessions and Persistence.

If an SFSB that uses session persistence is undeployed while the Enterprise Server instance is stopped, the session data in the persistence store might not be cleared. To prevent this, undeploy the SFSB while the Enterprise Server instance is running.


Configure SFSB failover by:

Choosing a Persistence Store

The following types of persistent storage are supported for passivation and checkpointing of the SFSB state:

Choose the persistence store in one of the following ways:

For more information, see the Sun GlassFish Enterprise Server v2.1.1 High Availability Administration Guide.

Enabling Checkpointing

The following sections describe how to enable SFSB checkpointing:

Server Instance and EJB Container Levels

To enable SFSB checkpointing at the server instance or EJB container level, see Choosing a Persistence Store.

Application and EJB Module Levels

To enable SFSB checkpointing at the application or EJB module level during deployment, use the asadmin deploy or asadmin deploydir command with the --availabilityenabled option set to true. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

SFSB Level

To enable SFSB checkpointing at the SFSB level, set availability-enabled="true" in the ejb element of the SFSB’s sun-ejb-jar.xml file as follows:

<sun-ejb-jar>
   ...
   <enterprise-beans>
      ...
      <ejb availability-enabled="true">
         <ejb-name>MySFSB</ejb-name>
      </ejb>
   ...
   </enterprise-beans>
</sun-ejb-jar>

Specifying Methods to Be Checkpointed

If SFSB checkpointing is enabled, checkpointing generally occurs after any transaction involving the SFSB is completed, even if the transaction rolls back.

To specify additional optional checkpointing of SFSBs at the end of non-transactional business methods that cause important modifications to the bean’s state, use the checkpoint-at-end-of-method element within the ejb element in sun-ejb-jar.xml.

For example:

<sun-ejb-jar>
   ...
   <enterprise-beans>
      ...
      <ejb availability-enabled="true">
         <ejb-name>ShoppingCartEJB</ejb-name>
         <checkpoint-at-end-of-method>
            <method>
               <method-name>addToCart</method-name>
            </method>
         </checkpoint-at-end-of-method>
      </ejb>
      ...
   </enterprise-beans>
</sun-ejb-jar>

For details, see checkpoint-at-end-of-method in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The non-transactional methods in the checkpoint-at-end-of-method element can be the following:

Any other methods mentioned in this list are ignored. At the end of invocation of each of these methods, the EJB container saves the state of the SFSB to persistent store.


Note –

If an SFSB does not participate in any transaction, and if none of its methods are explicitly specified in the checkpoint-at-end-of-method element, the bean’s state is not checkpointed at all even if availability-enabled="true" for this bean.

For better performance, specify a small subset of methods. The methods chosen should accomplish a significant amount of work in the context of the Java EE application or should result in some important modification to the bean’s state.


Session Bean Restrictions and Optimizations

This section discusses restrictions on developing session beans and provides some optimization guidelines:

Optimizing Session Bean Performance

For stateful session beans, colocating the stateful beans with their clients so that the client and bean are executing in the same process address space improves performance.

Restricting Transactions

The following restrictions on transactions are enforced by the container and must be observed as session beans are developed:

Using Read-Only Beans

A read-only bean is an EJB 2.1 entity bean that is never modified by an EJB client. The data that a read-only bean represents can be updated externally by other enterprise beans, or by other means, such as direct database updates.


Note –

Read-only beans are specific to the Enterprise Server and are not part of the Enterprise JavaBeans Specification, v2.1. Use of this feature for an EJB 2.1 bean results in a non-portable application.

To make an EJB 3.0 entity bean read-only, use @Column annotations to mark its columns insertable=false and updatable=false.


Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. The following topics are addressed in this section:

Read-Only Bean Characteristics and Life Cycle

Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. For example, a read-only bean can be used to represent a stock quote for a particular company, which is updated externally. In such a case, using a regular entity bean might incur the burden of calling ejbStore, which can be avoided by using a read-only bean.

Read-only beans have the following characteristics:

A read-only bean comes into existence using the appropriate find methods.

Read-only beans are cached and have the same cache properties as entity beans. When a read-only bean is selected as a victim to make room in the cache, ejbPassivate is called and the bean is returned to the free pool. When in the free pool, the bean has no identity and is used only to serve any finder requests.

Read-only beans are bound to the naming service like regular read-write entity beans, and clients can look up read-only beans the same way read-write entity beans are looked up.

Read-Only Bean Good Practices

For best results, follow these guidelines when developing read-only beans:

Refreshing Read-Only Beans

There are several ways of refreshing read-only beans as addressed in the following sections:

Invoking a Transactional Method

Invoking any transactional method invokes ejbLoad.

Refreshing Periodically

Use the refresh-period-in-seconds element in the sun-ejb-jar.xml file to refresh a read-only bean periodically.


Note –

This is the only way to refresh the bean state if the data can be modified external to the Enterprise Server.


By default, a single timer is used for all instances of a read-only bean. When that timer fires, all bean instances are marked as expired and are refreshed from the database the next time they are used.

Use the -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true flag to refresh each bean instance independently upon access if its refresh period has expired. The default is false. Note that each instance still has the same refresh period. This additional level of granularity can improve the performance of read-only beans that do not need to be refreshed at the same time.

To set this flag, use the asadmin create-jvm-options command. For example:


asadmin create-jvm-options --user adminuser -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true

Refreshing Programmatically

Typically, beans that update any data that is cached by read-only beans need to notify the read-only beans to refresh their state. Use ReadOnlyBeanNotifier to force the refresh of read-only beans.

To do this, invoke the following methods on the ReadOnlyBeanNotifier bean:

public interface ReadOnlyBeanNotifier extends java.rmi.Remote {
   refresh(Object PrimaryKey) throws RemoteException;
 }

The implementation of the ReadOnlyBeanNotifier interface is provided by the container. The bean looks up ReadOnlyBeanNotifier using a fragment of code such as the following example:

com.sun.appserv.ejb.ReadOnlyBeanHelper helper = 
  new com.sun.appserv.ejb.ReadOnlyBeanHelper();
com.sun.appserv.ejb.ReadOnlyBeanNotifier notifier = 
  helper.getReadOnlyBeanNotifier("java:comp/env/ejb/ReadOnlyCustomer");
notifier.refresh(PrimaryKey);

For a local read-only bean notifier, the lookup has this modification:

helper.getReadOnlyBeanLocalNotifier("java:comp/env/ejb/LocalReadOnlyCustomer");

Beans that update any data that is cached by read-only beans need to call the refresh methods. The next (non-transactional) call to the read-only bean invokes ejbLoad.

For Javadoc tool pages relevant to read-only beans, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.ejb package.

Deploying Read-Only Beans

Read-only beans are deployed in the same manner as other entity beans. However, in the entry for the bean in the sun-ejb-jar.xml file, the is-read-only-bean element must be set to true. That is:

<is-read-only-bean>true</is-read-only-bean>

Also, the refresh-period-in-seconds element in the sun-ejb-jar.xml file can be set to some value that specifies the rate at which the bean is refreshed. If this element is missing, no refresh occurs.

All requests in the same transaction context are routed to the same read-only bean instance. Set the allow-concurrent-access element to either true (to allow concurrent accesses) or false (to serialize concurrent access to the same read-only bean). The default is false.

For further information on these elements, refer to The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Using Message-Driven Beans

This section describes message-driven beans and explains the requirements for creating them in the Enterprise Server environment. This section contains the following topics:

Message-Driven Bean Configuration

This section addresses the following configuration topics:

For information about setting up load balancing for message-driven beans, see Load-Balanced Message Inflow.

Connection Factory and Destination

A message-driven bean is a client to a Connector inbound resource adapter. The message-driven bean container uses the JMS service integrated into the Enterprise Server for message-driven beans that are JMS clients. JMS clients use JMS Connection Factory- and Destination-administered objects. A JMS Connection Factory administered object is a resource manager Connection Factory object that is used to create connections to the JMS provider.

The mdb-connection-factory element in the sun-ejb-jar.xml file for a message-driven bean specifies the connection factory that creates the container connection to the JMS provider.

The jndi-name element of the ejb element in the sun-ejb-jar.xml file specifies the JNDI name of the administered object for the JMS Queue or Topic destination that is associated with the message-driven bean.

Message-Driven Bean Pool

The container manages a pool of message-driven beans for the concurrent processing of a stream of messages. The sun-ejb-jar.xml file contains the elements that define the pool (that is, the bean-pool element):

For more information about sun-ejb-jar.xml, see The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Domain-Level Settings

You can control the following domain-level message-driven bean settings in the EJB container:

For information on monitoring message-driven beans, click the Help button in the Admin Console. In the developer profile, the Monitor tab is accessible from the Application Server page. In the Cluster profile, select the Stand-Alone Instances component, select the instance from the table, and select the Monitor tab.


Note –

Running monitoring when it is not needed might impact performance, so you might choose to turn monitoring off when it is not in use. For details, see Chapter 18, Monitoring Components and Services, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.


Message-Driven Bean Restrictions and Optimizations

This section discusses the following restrictions and performance optimizations that pertain to developing message-driven beans:

Pool Tuning and Monitoring

The message-driven bean pool is also a pool of threads, with each message-driven bean instance in the pool associating with a server session, and each server session associating with a thread. Therefore, a large pool size also means a high number of threads, which impacts performance and server resources.

When configuring message-driven bean pool properties, make sure to consider factors such as message arrival rate and pattern, onMessage method processing time, overall server resources (threads, memory, and so on), and any concurrency requirements and limitations from other resources that the message-driven bean accesses.

When tuning performance and resource usage, make sure to consider potential JMS provider properties for the connection factory used by the container (the mdb-connection-factory element in the sun-ejb-jar.xml file). For example, you can tune the Sun GlassFish Message Queue flow control related properties for connection factory in situations where the message incoming rate is much higher than max-pool-size can handle.

Refer to Chapter 18, Monitoring Components and Services, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide for information on how to get message-driven bean pool statistics.

The onMessage Runtime Exception

Message-driven beans, like other well-behaved MessageListeners, should not, in general, throw runtime exceptions. If a message-driven bean’s onMessage method encounters a system-level exception or error that does not allow the method to successfully complete, the Enterprise JavaBeans Specification, v3.0 provides the following guidelines:

Under container-managed transaction demarcation, upon receiving a runtime exception from a message-driven bean’s onMessage method, the container rolls back the container-started transaction and the message is redelivered. This is because the message delivery itself is part of the container-started transaction. By default, the Enterprise Server container closes the container’s connection to the JMS provider when the first runtime exception is received from a message-driven bean instance’s onMessage method. This avoids potential message redelivery looping and protects server resources if the message-driven bean’s onMessage method continues misbehaving. To change this default container behavior, use the cmt-max-runtime-exceptions property of the mdb-container element in the domain.xml file.

The cmt-max-runtime-exceptions property specifies the maximum number of runtime exceptions allowed from a message-driven bean’s onMessage method before the container starts to close the container’s connection to the message source. By default this value is 1; -1 disables this container protection.

A message-driven bean’s onMessage method can use the javax.jms.Message getJMSRedelivered method to check whether a received message is a redelivered message.


Note –

The cmt-max-runtime-exceptions property might be deprecated in the future.


Handling Transactions With Enterprise Beans

This section describes the transaction support built into the Enterprise JavaBeans programming model for the Enterprise Server.

As a developer, you can write an application that updates data in multiple databases distributed across multiple sites. The site might use EJB servers from different vendors. This section provides overview information on the following topics:

Flat Transactions

The Enterprise JavaBeans Specification, v3.0 requires support for flat (as opposed to nested) transactions. In a flat transaction, each transaction is decoupled from and independent of other transactions in the system. Another transaction cannot start in the same thread until the current transaction ends.

Flat transactions are the most prevalent model and are supported by most commercial database systems. Although nested transactions offer a finer granularity of control over transactions, they are supported by far fewer commercial database systems.

Global and Local Transactions

Understanding the distinction between global and local transactions is crucial in understanding the Enterprise Server support for transactions. See Transaction Scope.

Both local and global transactions are demarcated using the javax.transaction.UserTransaction interface, which the client must use. Local transactions bypass the transaction manager and are faster. For more information, see The Transaction Manager, the Transaction Synchronization Registry, and UserTransaction.

Commit Options

The EJB protocol is designed to give the container the flexibility to select the disposition of the instance state at the time a transaction is committed. This allows the container to best manage caching an entity object’s state and associating an entity object identity with the EJB instances.

There are three commit-time options:

The Enterprise Server deployment descriptor has an element, commit-option, that specifies the commit option to be used. Based on the specified commit option, the appropriate handler is instantiated.

Administration and Monitoring

An administrator can control a number of domain-level Transaction Service settings. For details, see Configuring the Transaction Service.

The Transaction Timeout setting can be overridden by a bean. See Bean-Level Container-Managed Transaction Timeouts.

In addition, the administrator can monitor transactions using statistics from the transaction manager that provide information on such activities as the number of transactions completed, rolled back, or recovered since server startup, and transactions presently being processed.

For information on administering and monitoring transactions, select the Transaction Service component under the relevant configuration in the Admin Console and click the Help button. Also see Chapter 12, Transactions, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

Chapter 10 Using Container-Managed Persistence

This chapter contains information on how EJB 2.1 container-managed persistence (CMP) works in the Sun GlassFish Enterprise Server in the following topics:

Enterprise Server Support for CMP

Enterprise Server support for EJB 2.1 CMP beans includes:

CMP Mapping

Implementation for entity beans that use CMP is mostly a matter of mapping CMP fields and CMR fields (relationships) to the database. This section addresses the following topics:

Mapping Capabilities

Mapping refers to the ability to tie an object-based model to a relational model of data, usually the schema of a relational database. The CMP implementation provides the ability to tie a set of interrelated beans containing data and associated behaviors to the schema. This object representation of the database becomes part of the Java application. You can also customize this mapping to optimize these beans for the particular needs of an application. The result is a single data model through which both persistent database information and regular transient program data are accessed.

The mapping capabilities provided by the Enterprise Server include:

The Mapping Deployment Descriptor File

Each module with CMP beans must have the following files:

The sun-cmp-mappings.xml file can be automatically generated and does not have to exist prior to deployment. For details, see Generation Options for CMP.

The sun-cmp-mappings.xml file maps CMP fields and CMR fields (relationships) to the database. A primary table must be selected for each CMP bean, and optionally, multiple secondary tables. CMP fields are mapped to columns in either the primary or secondary table(s). CMR fields are mapped to pairs of column lists (normally, column lists are the lists of columns associated with primary and foreign keys).


Note –

Table names in databases can be case-sensitive. Make sure that the table names in the sun-cmp-mappings.xml file match the names in the database.

Relationships should always be mapped to the primary key field(s) of the related table.


The sun-cmp-mappings.xml file conforms to the sun-cmp-mapping_1_2.dtd file and is packaged with the user-defined bean classes in the EJB JAR file under the META-INF directory.

The Enterprise Server creates the mappings in the sun-cmp-mappings.xml file automatically during deployment if the file is not present.

To map the fields and relationships of your entity beans manually, edit the sun-cmp-mappings.xml deployment descriptor. Only do this if you are proficient in editing XML.

The mapping information is developed in conjunction with the database schema (.dbschema) file, which can be automatically captured when you deploy the bean (see Automatic Database Schema Capture). You can manually generate the schema using the capture-schema utility (Using the capture-schema Utility).

Mapping Considerations

This section addresses the following topics:

The data types used in automatic schema generation are also suggested for manual mapping. These data types are described in Supported Data Types for CMP.

Join Tables and Relationships

Use of join tables in the database schema is supported for all types of relationships, not just many-to-many relationships. For general information about relationships, see section 10.3.7 of the Enterprise JavaBeans Specification, v2.1.

Automatic Primary Key Generation

The Enterprise Server supports automatic primary key generation for EJB 1.1, 2.0, and 2.1 CMP beans. To specify automatic primary key generation, give the prim-key-class element in the ejb-jar-xml file the value java.lang.Object. CMP beans with automatically generated primary keys can participate in relationships with other CMP beans. The Enterprise Server does not support database-generated primary key values.

If the database schema is created during deployment, the Enterprise Server creates the schema with the primary key column, then generates unique values for the primary key column at runtime.

If the database schema is not created during deployment, the primary key column in the mapped table must be of type NUMERIC with a precision of 19 or more, and must not be mapped to any CMP field. The Enterprise Server generates unique values for the primary key column at runtime.

Fixed Length CHAR Primary Keys

If an existing database table has a primary key column in which the values vary in length, but the type is CHAR instead of VARCHAR, the Enterprise Server automatically trims any extra spaces when retrieving primary key values. It is not a good practice to use a fixed length CHAR column as a primary key. Use this feature with schemas that cannot be changed, such as a schema inherited from a legacy application.

Managed Fields

A managed field is a CMP or CMR field that is mapped to the same database column as another CMP or CMR field. CMP fields mapped to the same column and CMR fields mapped to exactly the same column lists always have the same value in memory. For CMR fields that share only a subset of their mapped columns, changes to the columns affect the relationship fields in memory differently. Basically, the Enterprise Server always tries to keep the state of the objects in memory synchronized with the database.

A managed field can have any fetched-with subelement. If the fetched-with subelement is <default/>, the -DAllowManagedFieldsInDefaultFetchGroup flag must be set to true. See Default Fetch Group Flags and fetched-with in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

BLOB Support

Binary Large Object (BLOB) is a data type used to store values that do not correspond to other types such as numbers, strings, or dates. Java fields whose types implement java.io.Serializable or are represented as byte[] can be stored as BLOBs.

If a CMP field is defined as Serializable, it is serialized into a byte[] before being stored in the database. Similarly, the value fetched from the database is deserialized. However, if a CMP field is defined as byte[], it is stored directly instead of being serialized and deserialized when stored and fetched, respectively.

To enable BLOB support in the Enterprise Server environment, define a CMP field of type byte[] or a user-defined type that implements the java.io.Serializable interface. If you map the CMP bean to an existing database schema, map the field to a column of type BLOB.

To use BLOB or CLOB data types larger than 4 KB for CMP using the Inet Oraxo JDBC Driver for Oracle Databases, you must set the streamstolob property value to true.

For a list of the JDBC drivers currently supported by the Enterprise Server, see the Sun GlassFish Enterprise Server v2.1.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

For automatic mapping, you might need to change the default BLOB column length for the generated schema using the schema-generator-properties element in sun-ejb-jar.xml. See your database vendor documentation to determine whether you need to specify the length. For example:

<schema-generator-properties>
   <property>
      <name>Employee.voiceGreeting.jdbc-type</name>
      <value>BLOB</value>
   </property>
   <property>
      <name>Employee.voiceGreeting.jdbc-maximum-length</name>
      <value>10240</value>
   </property>
   ...
</schema-generator-properties>

CLOB Support

Character Large Object (CLOB) is a data type used to store and retrieve very long text fields. CLOBs translate into long strings.

To enable CLOB support in the Enterprise Server environment, define a CMP field of type java.lang.String. If you map the CMP bean to an existing database schema, map the field to a column of type CLOB.

To use BLOB or CLOB data types larger than 4 KB for CMP using the Inet Oraxo JDBC Driver for Oracle Databases, you must set the streamstolob property value to true.

For a list of the JDBC drivers currently supported by the Enterprise Server, see the Sun GlassFish Enterprise Server v2.1.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

For automatic mapping, you might need to change the default CLOB column length for the generated schema using the schema-generator-properties element in sun-ejb-jar.xml. See your database vendor documentation to determine whether you need to specify the length. For example:

<schema-generator-properties>
   <property>
      <name>Employee.resume.jdbc-type</name>
      <value>CLOB</value>
   </property>
   <property>
      <name>Employee.resume.jdbc-maximum-length</name>
      <value>10240</value>
   </property>
   ...
</schema-generator-properties>

Automatic Schema Generation for CMP

The automatic schema generation feature provided in the Enterprise Server defines database tables based on the fields in entity beans and the relationships between the fields. This insulates developers from many of the database related aspects of development, allowing them to focus on entity bean 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.

This section addresses the following topics:


Note –

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


Supported Data Types for CMP

CMP supports a set of JDBC data types that are used in mapping Java data fields to SQL types. Supported JDBC data types are as follows: BIGINT, BIT, BLOB, CHAR, CLOB, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER, NUMERIC, REAL, SMALLINT, TIME, TIMESTAMP, TINYINT, VARCHAR.

The following table contains the mappings of Java types to JDBC types when automatic mapping is used.

Table 10–1 Java Type to JDBC Type Mappings for CMP

Java Type 

JDBC Type 

Nullability 

boolean

BIT

No 

java.lang.Boolean

BIT

Yes 

byte

TINYINT

No 

java.lang.Byte

TINYINT

Yes 

double

DOUBLE

No 

java.lang.Double

DOUBLE

Yes 

float

REAL

No 

java.lang.Float

REAL

Yes 

int

INTEGER

No 

java.lang.Integer

INTEGER

Yes 

long

BIGINT

No 

java.lang.Long

BIGINT

Yes 

short

SMALLINT

No 

java.lang.Short

SMALLINT

Yes 

java.math.BigDecimal

DECIMAL

Yes 

java.math.BigInteger

DECIMAL

Yes 

char

CHAR

No 

java.lang.Character

CHAR

Yes 

java.lang.String

VARCHAR or CLOB

Yes 

Serializable

BLOB

Yes 

byte[]

BLOB

Yes 

java.util.Date

DATE (Oracle only)

TIMESTAMP (all other databases)

Yes 

java.sql.Date

DATE

Yes 

java.sql.Time

TIME

Yes 

java.sql.Timestamp

TIMESTAMP

Yes 


Note –

Java types assigned to CMP fields must be restricted to Java primitive types, Java Serializable types, java.util.Date, java.sql.Date, java.sql.Time, or java.sql.Timestamp. An entity bean local interface type (or a collection of such) can be the type of a CMR field.


The following table contains the mappings of JDBC types to database vendor-specific types when automatic mapping is used. For a list of the JDBC drivers currently supported by the Enterprise Server, see the Sun GlassFish Enterprise Server v2.1.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

Table 10–2 Mappings of JDBC Types to Database Vendor Specific Types for CMP

JDBC Type 

Java DB, Derby, CloudScape 

Oracle  

DB2 

Sybase ASE 12.5 

MS-SQL Server 

BIT

SMALLINT

SMALLINT

SMALLINT

TINYINT

BIT

TINYINT

SMALLINT

SMALLINT

SMALLINT

TINYINT

TINYINT

SMALLINT

SMALLINT

SMALLINT

SMALLINT

SMALLINT

SMALLINT

INTEGER

INTEGER

INTEGER

INTEGER

INTEGER

INTEGER

BIGINT

BIGINT

NUMBER

BIGINT

NUMERIC

NUMERIC

REAL

REAL

REAL

FLOAT

FLOAT

REAL

DOUBLE

DOUBLE PRECISION

DOUBLE PRECISION

DOUBLE

DOUBLE PRECISION

FLOAT

DECIMAL(p,s)

DECIMAL(p,s)

NUMBER(p,s)

DECIMAL(p,s)

DECIMAL(p,s)

DECIMAL(p,s)

VARCHAR

VARCHAR

VARCHAR2

VARCHAR

VARCHAR

VARCHAR

DATE

DATE

DATE

DATE

DATETIME

DATETIME

TIME

TIME

DATE

TIME

DATETIME

DATETIME

TIMESTAMP

TIMESTAMP

TIMESTAMP(9)

TIMESTAMP

DATETIME

DATETIME

BLOB

BLOB

BLOB

BLOB

IMAGE

IMAGE

CLOB

CLOB

CLOB

CLOB

TEXT

NTEXT

Generation Options for CMP

Deployment descriptor elements or asadmin command line options can control automatic schema generation by the following:


Note –

Before using these options, make sure you have a properly configured CMP resource. See Configuring the CMP Resource.

For a read-only bean, do not create the database schema during deployment. Instead, work with your database administrator to populate the data into the tables. See Using Read-Only Beans.

Automatic schema generation is not supported for beans with version column consistency checking. Instead, work with your database administrator to create the schema and add the required triggers. See Version Column Consistency Checking.


The following optional data subelements of the cmp-resource element in the sun-ejb-jar.xml file control the automatic creation of database tables at deployment. For more information about the cmp-resource element, see cmp-resource in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide and Configuring the CMP Resource.

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

Element 

Default 

Description 

create-tables-at-deploy

false

If true, causes database tables to be created for beans that are automatically mapped by the EJB container. If false, does not create tables.

drop-tables-at-undeploy

false

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

database-vendor-name

none 

Specifies the name of the database vendor for which tables are created. Allowed values are javadb, db2, mssql, oracle, postgresql, pointbase, derby (also for CloudScape), and sybase, case-insensitive.

If no value is specified, a connection is made to the resource specified by the jndi-name subelement of the cmp-resource element in the sun-ejb-jar.xml file, and the database vendor name is read. If the connection cannot be established, or if the value is not recognized, SQL-92 compliance is presumed.

schema-generator-properties

none 

Specifies field-specific column attributes in property subelements. Each property name is of the following format:

bean-name.field-name.attribute

For example: 

Employee.firstName.jdbc-type

Also allows you to set the use-unique-table-names property. If true, this property specifies that generated table names are unique within each application server domain. The default is false.

For further information and an example, see schema-generator-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

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

Table 10–4 The asadmin deploy and asadmin deploydir Generation Options for CMP

Option 

Default 

Description 

--createtables

none 

If true, causes database tables to be created for beans that need them. If false, does not create tables. If not specified, the value of the create-tables-at-deploy attribute in sun-ejb-jar.xml is used.

--dropandcreatetables

none 

If true, and if tables were automatically created when this application was last deployed, tables from the earlier deployment are dropped and fresh ones are created.

If true, and if tables were not automatically created when this application was last deployed, no attempt is made to drop any tables. If tables with the same names as those that would have been automatically created are found, the deployment proceeds, but a warning indicates that tables could not be created.

If false, settings of create-tables-at-deploy or drop-tables-at-undeploy in the sun-ejb-jar.xml file are overridden.

--uniquetablenames

none 

If true, specifies that table names are unique within each application server domain. If not specified, the value of the use-unique-table-names property in sun-ejb-jar.xml is used.

--dbvendorname

none 

Specifies the name of the database vendor for which tables are created. Allowed values are javadb, db2, mssql, oracle, postgresql, pointbase, derby (also for CloudScape), and sybase, case-insensitive.

If not specified, the value of the database-vendor-name attribute in sun-ejb-jar.xml is used.

If no value is specified, a connection is made to the resource specified by the jndi-name subelement of the cmp-resource element in the sun-ejb-jar.xml file, and the database vendor name is read. If the connection cannot be established, or if the value is not recognized, SQL-92 compliance is presumed.

If one or more of the beans in the module are manually mapped and you use any of the asadmin deploy or asadmin deploydir options, the deployment is not harmed in any way, but the options have no effect, and a warning is written to the server log.

The following options of the asadmin undeploy command control the automatic removal of database tables at undeployment.

Table 10–5 The asadmin undeploy Generation Options for CMP

Option 

Default 

Description 

--droptables

none 

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

If not specified, the value of the drop-tables-at-undeploy attribute in sun-ejb-jar.xml is used.

For more information about the asadmin deploy, asadmin deploydir, and asadmin undeploy commands, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

When command line and sun-ejb-jar.xml options are both specified, the asadmin options take precedence.

The asant tasks sun-appserv-deploy and sun-appserv-undeploy are equivalent to asadmin deploy and asadmin undeploy, respectively. These asant tasks also override the sun-ejb-jar.xml options. For details, see Chapter 3, The asant Utility.

Schema Capture

This section addresses the following topics:

Automatic Database Schema Capture

You can configure a CMP bean in Enterprise Server to automatically capture the database metadata and save it in a .dbschema file during deployment. If the sun-cmp-mappings.xml file contains an empty <schema/> entry, the cmp-resource entry in the sun-ejb-jar.xml file is used to get a connection to the database, and automatic generation of the schema is performed.


Note –

Before capturing the database schema automatically, make sure you have a properly configured CMP resource. See Configuring the CMP Resource.


Using the capture-schema Utility

You can use the capture-schema command to manually generate the database metadata (.dbschema) file. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

The capture-schema utility does not modify the schema in any way. Its only purpose is to provide the persistence engine with information about the structure of the database (the schema).

Keep the following in mind when using the capture-schema command:

Configuring the CMP Resource

An EJB module that contains CMP beans requires the JNDI name of a JDBC resource in the jndi-name subelement of the cmp-resource element in the sun-ejb-jar.xml file. Set PersistenceManagerFactory properties as properties of the cmp-resource element in the sun-ejb-jar.xml file. See cmp-resource in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

In the Admin Console, open the Resources component, then select JDBC. Click the Help button in the Admin Console for information on creating a new JDBC resource.

For a list of the JDBC drivers currently supported by the Enterprise Server, see the Sun GlassFish Enterprise Server v2.1.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

For example, if the JDBC resource has the JNDI name jdbc/MyDatabase, set the CMP resource in the sun-ejb-jar.xml file as follows:

<cmp-resource>
   <jndi-name>jdbc/MyDatabase</jndi-name>
</cmp-resource>

Performance-Related Features

The Enterprise Server provides the following features to enhance performance or allow more fine-grained data checking. These features are supported only for entity beans with container managed persistence.


Note –

Use of any of these features results in a non-portable application.


Version Column Consistency Checking

The version consistency feature saves the bean state at first transactional access and caches it between transactions. The state is copied from the cache instead of being read from the database. The bean state is verified by primary key and version column values at flush for custom queries (for dirty instances only) and at commit (for clean and dirty instances).

ProcedureTo Use Version Consistency

  1. Create the version column in the primary table.

  2. Give the version column a numeric data type.

  3. Provide appropriate update triggers on the version column.

    These triggers must increment the version column on each update of the specified row.

  4. Specify the version column.

    This is specified in the check-version-of-accessed-instances subelement of the consistency element in the sun-cmp-mappings.xml file. See consistency in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

  5. Map the CMP bean to an existing schema.

    Automatic schema generation is not supported for beans with version column consistency checking. Instead, work with your database administrator to create the schema and add the required triggers.

Relationship Prefetching

In many cases when an entity bean’s state is fetched from the database, its relationship fields are always accessed in the same transaction. Relationship prefetching saves database round trips by fetching data for an entity bean and those beans referenced by its CMR fields in a single database round trip.

To enable relationship prefetching for a CMR field, use the default subelement of the fetched-with element in the sun-cmp-mappings.xml file. By default, these CMR fields are prefetched whenever findByPrimaryKey or a custom finder is executed for the entity, or when the entity is navigated to from a relationship. (Recursive prefetching is not supported, because it does not usually enhance performance.) See fetched-with in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

To disable prefetching for specific custom finders, use the prefetch-disabled element in the sun-ejb-jar.xml file. See prefetch-disabled in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Multilevel relationship prefetching is supported for CMP 2.1 entity beans. To enable multilevel relationship prefetching, set the following property using the asadmin create-jvm-options command:


asadmin create-jvm-options -Dcom.sun.jdo.spi.persistence.support.sqlstore.MULTILEVEL_PREFETCH=true

Read-Only Beans

Another feature that the Enterprise Server provides is the read-only bean, an entity bean that is never modified by an EJB client. Read-only beans avoid database updates completely.


Note –

Read-only beans are specific to the Enterprise Server and are not part of the Enterprise JavaBeans Specification, v2.1. Use of this feature for an EJB 2.1 bean results in a non-portable application.


A read-only bean can be used to cache a database entry that is frequently accessed but rarely updated (externally by other beans). When the data that is cached by a read-only bean is updated by another bean, the read-only bean can be notified to refresh its cached data.

The Enterprise Server provides a number of ways by which a read-only bean’s state can be refreshed. By setting the refresh-period-in-seconds element in the sun-ejb-jar.xml file and the trans-attribute element (or @TransactionAttribute annotation) in the ejb-jar.xml file, it is easy to configure a read-only bean that is one of the following:

Access to CMR fields of read-only beans is not supported. Deployment will succeed, but an exception will be thrown at runtime if a get or set method is invoked.

Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. For further information and usage guidelines, see Using Read-Only Beans.

Default Fetch Group Flags

Using the following flags can improve performance.

Setting -DAllowManagedFieldsInDefaultFetchGroup=true allows CMP fields that by default cannot be placed into the default fetch group to be loaded along with all other fields that are fetched when the CMP state is loaded into memory. These could be multiple fields mapped to the same column in the database table, for example, an instance field and a CMR. By default this flag is set to false.

For additional information, see level in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Setting -DAllowMediatedWriteInDefaultFetchGroup specifies how updated CMP fields are written back to the database. If the flag is false, all fields in the CMP bean are written back to the database if at least one field in the default fetch group has been changed in a transaction. If the flag is true, only fields modified by the bean are written back to the database. Specifying true can improve performance, particularly on database tables with many columns that have not been updated. By default this flag is set to false.

To set one of these flags, use the asadmin create-jvm-options command. For example:


asadmin create-jvm-options --user adminuser -DAllowManagedFieldsInDefaultFetchGroup=true

Configuring Queries for 1.1 Finders

This section contains the following topics:

About JDOQL Queries

The Enterprise JavaBeans Specification, v1.1 does not specify the format of the finder method description. The Enterprise Server uses an extension of Java Data Objects Query Language (JDOQL) queries to implement finder and selector methods. You can specify the following elements of the underlying JDOQL query:

The Enterprise Server specific deployment descriptor (sun-ejb-jar.xml) provides the following elements to store the EJB 1.1 finder method settings:

query-filter
query-params
query-variables
query-ordering

The bean developer uses these elements to construct a query. When the finder method that uses these elements executes, the values of these elements are used to execute a query in the database. The objects from the JDOQL query result set are converted into primary key instances to be returned by the EJB 1.1 ejbFind method.

The JDO specification, JSR 12, provides a comprehensive description of JDOQL. The following information summarizes the elements used to define EJB 1.1 finders.

Query Filter Expression

The filter expression is a String containing a Boolean expression evaluated for each instance of the candidate class. If the filter is not specified, it defaults to true. Rules for constructing valid expressions follow the Java language, with the following differences:


Note –

Comparisons between floating point values are by nature inexact. Therefore, equality comparisons (== and !=) with floating point values should be used with caution. Identifiers in the expression are considered to be in the name space of the candidate class, with the addition of declared parameters and variables. As in the Java language, this is a reserved word, and refers to the current instance being evaluated.


The following expressions are supported.

The rules for promotion follow the Java rules extended by BigDecimal, BigInteger, and numeric wrapper classes. See the numeric promotions of the Java language specification.

Query Parameters

The parameter declaration is a String containing one or more parameter type declarations separated by commas. This follows the Java syntax for method signatures.

Query Variables

The type declarations follow the Java syntax for local variable declarations.

JDOQL Examples

This section provides a few query examples.

Example 1

The following query returns all players called Michael. It defines a filter that compares the name field with a string literal:

name == "Michael"

The finder element of the sun-ejb-jar.xml file looks like this:

<finder>
   <method-name>findPlayerByName</method-name>
   <query-filter>name == "Michael"</query-filter>
</finder>

Example 2

This query returns all products in a specified price range. It defines two query parameters which are the lower and upper bound for the price: double low, double high. The filter compares the query parameters with the price field:

low < price && price < high

Query ordering is set to price ascending.

The finder element of the sun-ejb-jar.xml file looks like this:

<finder>
   <method-name>findInRange</method-name>
   <query-params>double low, double high</query-params>
   <query-filter>low &lt; price &amp;&amp; price &lt high</query-filter>
   <query-ordering>price ascending</query-ordering>
</finder>

Example 3

This query returns all players having a higher salary than the player with the specified name. It defines a query parameter for the name java.lang.String name. Furthermore, it defines a variable to which the player’s salary is compared. It has the type of the persistence capable class that corresponds to the bean:

    mypackage.PlayerEJB_170160966_JDOState player

The filter compares the salary of the current player denoted by the this keyword with the salary of the player with the specified name:

    (this.salary > player.salary) && (player.name == name)

The finder element of the sun-ejb-jar.xml file looks like this:

<finder>
   <method-name>findByHigherSalary</method-name>
   <query-params>java.lang.String name</query-params>
   <query-filter>
      (this.salary &gt; player.salary) &amp;&amp; (player.name == name)
   </query-filter>
   <query-variables>
      mypackage.PlayerEJB_170160966_JDOState player
   </query-variables>
</finder>

CMP Restrictions and Optimizations

This section discusses restrictions and performance optimizations that pertain to using CMP.

Disabling ORDER BY Validation

EJB QL as defined in the EJB 2.1 Specification defines certain restrictions for the SELECT clause of an ORDER BY query (see section 11.2.8 ORDER BY Clause). This ensures that a query does not order by a field that is not returned by the query. By default, the EJB QL compiler checks the above restriction and throws an exception if the query does not conform.

However, some databases support SQL statements with an ORDER BY column that is not included in the SELECT clause. To disable the validation of the ORDER BY clause against the SELECT clause, set the DISABLE_ORDERBY_VALIDATION JVM option as follows:

asadmin create-jvm-options --user adminuser 
-Dcom.sun.jdo.spi.persistence.support.ejb.ejbqlc.DISABLE_ORDERBY_VALIDATION=true

The DISABLE_ORDERBY_VALIDATION option is set to false by default. Setting it to true results in a non-portable module or application.

Setting the Heap Size on DB2

On DB2, the database configuration parameter APPLHEAPSZ determines the heap size. If you are using the Sun GlassFish or DataDirect database driver, set this parameter to at least 2048 for CMP. For more information, see http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/opt/tsbp2024.htm.

Eager Loading of Field State

By default, the EJB container loads the state for all persistent fields (excluding relationship, BLOB, and CLOB fields) before invoking the ejbLoad method of the abstract bean. This approach might not be optimal for entity objects with large state if most business methods require access to only parts of the state.

Use the fetched-with element in sun-cmp-mappings.xml for fields that are used infrequently. See fetched-with in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Restrictions on Remote Interfaces

The following restrictions apply to the remote interface of an EJB 2.1 bean that uses CMP:

Dependent value classes can be exposed in the remote interface or remote home interface, and can be included in the client EJB JAR file.

PostgreSQL Case Insensitivity

Case-sensitive behavior cannot be achieved for PostgresSQL databases. PostgreSQL databases internally convert all names to lower case, which makes the following workarounds necessary:

No Support for lock-when-loaded on Sybase

For EJB 2.1 beans, the lock-when-loaded consistency level is implemented by placing update locks on the data corresponding to a bean when the data is loaded from the database. There is no suitable mechanism available on Sybase databases to implement this feature. Therefore, the lock-when-loaded consistency level is not supported on Sybase databases. See consistency in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

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.

Date and Time Fields

If a field type is a Java date or time type (java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp), make sure that the field value exactly matches the value in the database.

For example, the following code uses a java.sql.Date type as a primary key field:

java.sql.Date myDate = new java.sql.Date(System.currentTimeMillis())
BeanA.create(myDate, ...);

For some databases, this code results in only the year, month, and date portion of the field value being stored in the database. Later if the client tries to find this bean by primary key as follows, the bean is not found in the database because the value does not match the one that is stored in the database.

myBean = BeanA.findByPrimaryKey(myDate);

Similar problems can happen if the database truncates the timestamp value while storing it, or if a custom query has a date or time value comparison in its WHERE clause.

For automatic mapping to an Oracle database, fields of type java.util.Date, java.sql.Date, and java.sql.Time are mapped to Oracle’s DATE data type. Fields of type java.sql.Timestamp are mapped to Oracle’s TIMESTAMP(9) data type.

Set RECURSIVE_TRIGGERS to false on MSSQL

For version consistency triggers on MSSQL, the property RECURSIVE_TRIGGERS must be set to false, which is the default. If set to true, triggers throw a java.sql.SQLException.

Set this property as follows:

EXEC sp_dboption 'database-name', 'recursive triggers', 'FALSE'
go

You can test this property as follows:

SELECT DATABASEPROPERTYEX('database-name', 'IsRecursiveTriggersEnabled')
go

MySQL Database Restrictions

The following restrictions apply when you use a MySQL database with the Enterprise Server for persistence.

Chapter 11 Developing Java Clients

This chapter describes how to develop, assemble, and deploy Java clients in the following sections:

Introducing the Application Client Container

The Application Client Container (ACC) includes a set of Java classes, libraries, and other files that are required for and distributed with Java client programs that execute in their own Java Virtual Machine (JVM). The ACC manages the execution of Java EE application client components (application clients), which are used to access a variety of Java EE services (such as JMS resources, EJB components, web services, security, and so on.) from a JVM outside the Sun GlassFish Enterprise Server.

The ACC communicates with the Enterprise Server using RMI-IIOP protocol and manages the details of RMI-IIOP communication using the client ORB that is bundled with it. Compared to other Java EE containers, the ACC is lightweight.

For information about debugging application clients, see Application Client Debugging.


Note –

Interoperability between application clients and Enterprise Servers running under different major versions is not supported.


ACC Security

The ACC determines when authentication is needed. This typically occurs when the client refers to an EJB component or when annotations in the client's main class trigger injection which, in turn, requires contact with the Enterprise Server's naming service. To authenticate the end user, the ACC prompts for any required information, such as a username and password. The ACC itself provides a very simple dialog box to prompt for and read these values.

The ACC integrates with the Enterprise Server’s authentication system. It also supports SSL (Secure Socket Layer)/IIOP if configured and when necessary; see Using RMI/IIOP Over SSL.

You can provide an alternate implementation to gather authentication information, tailored to the needs of the application client. To do so, include the class to perform these duties in the application client and identify the fully-qualified name of this class in the callback-handler element of the application-client.xml descriptor for the client. The ACC uses this class instead of its default class for asking for and reading the authentication information. The class must implement the javax.security.auth.callback.CallbackHandler interface. See the Java EE specification, section 9.2, Application Clients: Security, for more details.

Application clients can use Programmatic Login.

For more information about security for application clients, see the Java EE 5 Specification, Section EE.9.7, “Java EE Application Client XML Schema.”

ACC Naming

The client container enables the application clients to use the Java Naming and Directory Interface (JNDI) to look up Java EE services (such as JMS resources, EJB components, web services, security, and so on.) and to reference configurable parameters set at the time of deployment.

ACC Annotation

Annotation is supported for application clients. For more information, see section 9.4 of the Java EE 5 Specification and Java EE Standard Annotation in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Java Web Start

Java Web Start allows your application client to be easily launched and automatically downloaded and updated. It is enabled for all application clients by default. For more information, see Using Java Web Start.

Developing Clients Using the ACC

This section describes the procedure to develop, assemble, and deploy client applications using the ACC. This section describes the following topics:

ProcedureTo Access an EJB Component From an Application Client

  1. In your client code, reference the EJB component by using an @EJB annotation or by looking up the JNDI name as defined in the ejb-jar.xml file.

    For more information about annotations in application clients, see section 9.4 of the Java EE 5 Specification.

    For more information about naming and lookups, see Accessing the Naming Context.

    If load balancing is enabled as in Step 7 and the EJB components being accessed are in a different cluster, the endpoint list must be included in the lookup, as follows:

    corbaname:host1:port1,host2:port2,.../NameService#ejb/jndi-name
    
  2. Define the @EJB annotations or the ejb-ref elements in the application-client.xml file. Define the corresponding ejb-ref elements in the sun-application-client.xml file.

    For more information on the application-client.xml file, see the Java EE 5 Specification, Section EE.9.7, “Java EE Application Client XML Schema.”

    For more information on the sun-application-client.xml file, see The sun-application-client.xml file in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide. For a general explanation of how to map JNDI names using reference elements, see Mapping References.

  3. Deploy the application client and EJB component together in an application.

    For more information on deployment, see the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide. To get the client JAR file, use the --retrieve option of the asadmin deploy command.

    To retrieve the stubs and ties whether or not you requested their generation during deployment, use the asadmin get-client-stubs command. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

  4. Ensure that the client JAR file includes the following files:

    • A Java class to access the bean.

    • application-client.xml - (optional) Java EE application client deployment descriptor. For information on the application-client.xml file, see the Java EE 5 Specification, Section EE.9.7, “Java EE Application Client XML Schema.”

    • sun-application-client.xml - (optional) Enterprise Server specific client deployment descriptor. For information on the sun-application-client.xml file, see The sun-application-client.xml file in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

    • The MANIFEST.MF file. This file contains a reference to the main class, which states the complete package prefix and class name of the Java client.

  5. Prepare the client machine. This step is not needed for Java Web Start.

    If you are using the appclient script, either package the application client to run on a remote client system using the package-appclient script, or copy the following JAR files to the client machine manually and include them in the classpath on the client side:

    • appserv-rt.jar - available at as-install/lib

    • javaee.jar - available at as-install/lib

    • The client JAR file

    For more information, see Using the package-appclient Script.

  6. To access EJB components that are residing in a remote system, make the following changes to the sun-acc.xml file. This step is not needed for Java Web Start.

    This information can be obtained from the domain.xml file on the remote system. For more information on domain.xml file, see the Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

  7. To set up load balancing and failover of remote EJB references, define at least two target-server elements in the sun-acc.xml file. This step is not needed for Java Web Start.


    Note –

    Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.


    If the Enterprise Server instance on which the application client is deployed participates in a cluster, the ACC finds all currently active IIOP endpoints in the cluster automatically. However, a client should have at least two endpoints specified for bootstrapping purposes, in case one of the endpoints has failed.

    The target-server elements specify one or more IIOP endpoints used for load balancing. The address attribute is an IPv4 address or host name, and the port attribute specifies the port number. See client-container in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

  8. Run the application client.

    See Using Java Web Start or Running an Application Client Using the appclient Script.

ProcedureTo Access a JMS Resource From an Application Client

  1. Create a JMS client.

    For detailed instructions on developing a JMS client, see “Chapter 33: The Java Message Service API” in the Java EE 5 Tutorial.

  2. Next, configure a JMS resource on the Enterprise Server.

    For information on configuring JMS resources, see Creating JMS Resources: Destinations and Connection Factories.

  3. Define the @Resource or @Resources annotations or the resource-ref elements in the application-client.xml file. Define the corresponding resource-ref elements in the sun-application-client.xml file.

    For more information on the application-client.xml file, see the Java EE 5 Specification, Section EE.9.7, “Java EE Application Client XML Schema.”

    For more information on the sun-application-client.xml file, see The sun-application-client.xml file in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide. For a general explanation of how to map JNDI names using reference elements, see Mapping References.

  4. Ensure that the client JAR file includes the following files:

    • A Java class to access the resource.

    • application-client.xml - (optional) Java EE application client deployment descriptor. For information on the application-client.xml file, see the Java EE 5 Specification, Section EE.9.7, “Java EE Application Client XML Schema.”

    • sun-application-client.xml - (optional) Enterprise Server specific client deployment descriptor. For information on the sun-application-client.xml file, see The sun-application-client.xml file in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

    • The MANIFEST.MF file. This file contains a reference to the main class, which states the complete package prefix and class name of the Java client.

  5. Prepare the client machine. This step is not needed for Java Web Start.

    If you are using the appclient script, either package the application client to run on a remote client system using the package-appclient script, or copy the following JAR files to the client machine manually and include them in the classpath on the client side:

    • appserv-rt.jar - available at as-install/lib

    • javaee.jar - available at as-install/lib

    • imqjmsra.jar - available at as-install/lib/install/aplications/jmsra

    • The client JAR file

    For more information, see Using the package-appclient Script.

  6. Run the application client.

    See Using Java Web Start or Running an Application Client Using the appclient Script.

Using Java Web Start

Java Web Start allows your application client to be easily launched and automatically downloaded and updated. General information about Java Web Start is available at http://java.sun.com/products/javawebstart/reference/api/index.html.

Java Web Start is discussed in the following topics:

Enabling and Disabling Java Web Start

Java Web Start is enabled for all application clients by default.

The application developer or deployer can specify that Java Web Start is always disabled for an application client by setting the value of the eligible element to false in the sun-application-client.xml file. See the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The Enterprise Server administrator can disable Java Web Start for a previously deployed eligible application client using the asadmin set command.

To disable Java Web Start for all eligible application clients in an application, use the following command:


asadmin set --user adminuser 
domain1.applications.j2ee-application.app-name.java-web-start-enabled="false"

To disable Java Web Start for a stand-alone eligible application client, use the following command:


asadmin set --user adminuser 
domain1.applications.appclient-module.module-name.java-web-start-enabled="false"

Setting java-web-start-enabled="true" re-enables Java Web Start for an eligible application client. For more information about the asadmin set command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Downloading and Launching an Application Client

If Java Web Start is enabled for your deployed application client, you can launch it for testing. Simply click on the Launch button next to the application client or application's listing on the App Client Modules page in the Admin Console.

On other machines, you can download and launch the application client using Java Web Start in the following ways:

When you launch an application client, Java Web Start contacts the server to see if a newer client version is available. This means you can redeploy an application client without having to worry about whether client machines have the latest version.

The Application Client URL

The default URL for an application or module generally is as follows:


http://host:port/context-root

The default URL for a stand-alone application client module is as follows:


http://host:port/appclient-module-id

The default URL for an application client module embedded within an application is as follows. Note that the relative path to the application client JAR file is included.


http://host:port/application-id/appclient-path

If the context-root, appclient-module-id, or application-id is not specified during deployment, the name of the JAR or EAR file without the extension is used. If the application client module or application is not in JAR or EAR file format, an appclient-module-id or application-id is generated.

Regardless of how the context-root or id is determined, it is written to the server log. For details about naming, see Naming Standards in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

To set a different URL for an application client, use the context-root subelement of the java-web-start-access element in the sun-application-client.xml file. This overrides the appclient-module-id or application-id. See Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

You can also pass arguments to the ACC or to the application client's main method as query parameters in the URL. If multiple application client arguments are specified, they are passed in the order specified.

A question mark separates the context root from the arguments. Ampersands (&) separate the arguments and their values. Each argument and each value must begin with arg=. Here is an example URL with a -color argument for a stand-alone application client. The -color argument is passed to the application client's main method.


http://localhost:8080/testClient?arg=-color&arg=red

Note –

If you are using the javaws URL command to launch Java Web Start with a URL that contains arguments, enclose the URL in double quotes (") to avoid breaking the URL at the ampersand (&) symbol.


Ideally, you should build your production application clients with user-friendly interfaces that collect information which might otherwise be gathered as command-line arguments. This minimizes the degree to which users must customize the URLs that launch application clients using Java Web Start. Command-line argument support is useful in a development environment and for existing application clients that depend on it.

Signing JAR Files Used in Java Web Start

Java Web Start enforces a security sandbox. By default it grants any application, including application clients, only minimal privileges. Because Java Web Start applications can be so easily downloaded, Java Web Start provides protection from potentially harmful programs that might be accessible over the network. If an application requires a higher privilege level than the sandbox permits, the code that needs privileges must be in a JAR file that was signed. When Java Web Start downloads such a signed JAR file, it displays information about the certificate that was used to sign the JAR, and it asks you whether you want to trust that signed code. If you agree, the code receives elevated permissions and runs. If you reject the signed code, Java Web Start does not start the downloaded application.

The Enterprise Server serves two types of signed JAR files in response to Java Web Start requests. One type is a JAR file installed as part of the Enterprise Server, which starts an application client during a Java Web Start launch: as-install/lib/appserv-jwsacc.jar.

The other type is a generated application client JAR file. As part of deployment, the Enterprise Server generates a new application client JAR file that contains classes, resources, and descriptors needed to run the application client on end-user systems. When you deploy an application with the asadmin deploy command's --retrieve option, use the asadmin get-client-stubs command, or select the Generate RMIStubs option from the EJB Modules deployment page in the Admin Console, this is the JAR file retrieved to your system. Because application clients need access beyond the minimal sandbox permissions to work in the Java Web Start environment, the generated application client JAR file must be signed before it can be downloaded to and executed on an end-user system.

A JAR file can be signed automatically or manually. The following sections describe the ways of signing JAR files.

Automatically Signing JAR Files

The Enterprise Server automatically creates a signed version of the required JAR file if none exists. When a Java Web Start request for the appserv-jwsacc.jar file arrives, the Enterprise Server looks for domain-dir/java-web-start/appserv-jwsacc.jar. When a request for an application's generated application client JAR file arrives, the Enterprise Server looks in the directory domain-dir/java-web-start/app-name for a file with the same name as the generated JAR file created during deployment.

In either case, if the requested signed JAR file is absent or older than its unsigned counterpart, the Enterprise Server creates a signed version of the JAR file automatically and deposits it in the relevant directory. Whether the Enterprise Server just signed the JAR file or not, it serves the file from the domain-dir/java-web-start directory tree in response to the Java Web Start request.

To sign these JAR files, the Enterprise Server uses its self-signed certificate. When you create a new domain, either by installing the Enterprise Server or by using the asadmin create-domain command, the Enterprise Server creates a self-signed certificate and adds it to the domain's key store.

A self-signed certificate is generally untrustworthy because no certification authority vouches for its authenticity. The automatic signing feature uses the same certificate to create all required signed JAR files. To sign different JAR files with different certificates, do the signing manually.

Manually Signing appserv-jwsacc.jar

You can sign the appserv-jwsacc.jar file manually any time after you have installed the Enterprise Server. Copy the unsigned file from as-install/lib to a different working directory and use the jarsigner command provided with the JDK to create a signed version of exactly the same name using your certificate. Then manually copy the signed file into domain-dir/java-web-start. From then on, the Enterprise Server serves the JAR file signed with your certificate whenever a Java Web Start request asks that domain for the appserv-jwsacc.jar file. Note that you can sign each domain's appserv-jwsacc.jar file differently.

Remember that if you create a new domain and do not sign appserv-jwsacc.jar manually for that domain, the Enterprise Server creates an auto-signed version of it for use by the new domain. Also, if you create a domain-specific signed appserv-jwsacc.jar, delete the domain, and then create a new domain with the same name as the just-deleted domain, the Enterprise Server does not remember the earlier signed appserv-jwsacc.jar. You must recreate the manually signed version.

Manually Signing the Generated Application Client JAR File

You can sign the generated application client JAR file for an application any time after you have deployed the application. As you deploy the application, you can specify the asadmin deploy command's --retrieve option or select the Generate RMIStubs option on the EJB Modules deployment page in the Admin Console. Doing either of these tasks returns a copy of the generated application client JAR file to a directory you specify. Or, after you have deployed an application, you can download the generated application client JAR file using the asadmin get-client-stubs command.

Once you have a copy of the generated application client JAR file, you can sign it using the jarsigner tool and your certificate. Then place the signed JAR file in the domain-dir/java-web-start/app-name directory. You do not need to restart the server to start using the new signed JAR file.

Error Handling

When an application client is launched using Java Web Start, any error that the application client logic does not catch and handle is written to System.err and displayed in a dialog box. This display appears if an error occurs even before the application client logic receives control. It also appears if the application client code does not catch and handle errors itself.

Vendor Icon, Splash Screen, and Text

To specify a vendor-specific icon, splash screen, text string, or a combination of these for Java Web Start download and launch screens, use the vendor element in the sun-application-client.xml file. The complete format of this element's data is as follows:

<vendor>icon-image-URI::splash-screen-image-URI::vendor-text</vendor>

The following example vendor element contains an icon, a splash screen, and a text string:

<vendor>images/icon.jpg::otherDir/splash.jpg::MyCorp, Inc.</vendor>

The following example vendor element contains an icon and a text string:

<vendor>images/icon.jpg::MyCorp, Inc.</vendor>

The following example vendor element contains a splash screen and a text string; note the initial double colon:

<vendor>::otherDir/splash.jpg::MyCorp, Inc.</vendor>

The following example vendor element contains only a text string:

<vendor>MyCorp, Inc.</vendor>

The default value is the text string Application Client.

For more information about the sun-application-client.xml file, see the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Running an Application Client Using the appclient Script

To run an application client that does not have Java Web Start enabled, you can launch the ACC using the appclient script. This is optional. This script is located in the as-install/bin directory. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Using the package-appclient Script

You can package an application client that does not have Java Web Start enabled into a single appclient.jar file using the package-appclient script. This is optional. This script is located in the as-install/bin directory. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

The client.policy File

The client.policy file is the J2SE policy file used by the application client. Each application client has a client.policy file. The default policy file limits the permissions of Java EE deployed application clients to the minimal set of permissions required for these applications to operate correctly. If an application client requires more than this default set of permissions, edit the client.policy file to add the custom permissions that your application client needs. Use the J2SE standard policy tool or any text editor to edit this file.

For more information on using the J2SE policy tool, see http://java.sun.com/docs/books/tutorial/security1.2/tour2/index.html.

For more information about the permissions you can set in the client.policy file, see http://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html.

Using RMI/IIOP Over SSL

You can configure RMI/IIOP over SSL in two ways: using a username and password, or using a client certificate.

To use a username and password, configure the ior-security-config element in the sun-ejb-jar.xml file. The following configuration establishes SSL between an application client and an EJB component using a username and password. The user has to login to the ACC using either the sun-acc.xml mechanism or the Programmatic Login mechanism.

<ior-security-config>
  <transport-config>
    <integrity>required</integrity>
    <confidentiality>required</confidentiality>
    <establish-trust-in-target>supported</establish-trust-in-target>
    <establish-trust-in-client>none</establish-trust-in-client>
  </transport-config>
  <as-context>
    <auth-method>username_password</auth-method>
    <realm>default</realm>
    <required>true</required>
  </as-context>
 <sas-context>
    <caller-propagation>none</caller-propagation>
 </sas-context>
</ior-security-config>

For more information about the sun-ejb-jar.xml and sun-acc.xml files, see the Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

To use a client certificate, configure the ior-security-config element in the sun-ejb-jar.xml file. The following configuration establishes SSL between an application client and an EJB component using a client certificate.

<ior-security-config>
  <transport-config>
    <integrity>required</integrity>
    <confidentiality>required</confidentiality>
    <establish-trust-in-target>supported</establish-trust-in-target>
    <establish-trust-in-client>required</establish-trust-in-client>
  </transport-config>
  <as-context>
    <auth-method>none</auth-method>
    <realm>default</realm>
    <required>false</required>
  </as-context>
  <sas-context>
    <caller-propagation>none</caller-propagation>
  </sas-context>
</ior-security-config>

To use a client certificate, you must also specify the system properties for the keystore and truststore to be used in establishing SSL. To use SSL with the Application Client Container (ACC), you need to set VMARGS environment variable in one of the following ways:

Connecting to a Remote EJB Module Through a Firewall

To deploy and run an application client that connects to an EJB module on a Enterprise Server instance that is behind a firewall, you must set ORB Virtual Address Agent Implementation (ORBVAA) options. Use the asadmin create-jvm-options command as follows:


asadmin create-jvm-options --user adminuser -Dcom.sun.corba.ee.ORBVAAHost=public-IP-adress
asadmin create-jvm-options --user adminuser -Dcom.sun.corba.ee.ORBVAAPort=public-port
asadmin create-jvm-options --user adminuser 
-Dcom.sun.corba.ee.ORBUserConfigurators.com.sun.corba.ee.impl.plugin.hwlb.VirtualAddressAgentImpl=x

Set the ORBVAAHost and ORBVAAPort options to the host and port of the public address. The ORBUserConfigurators option tells the ORB to create an instance of the VirtualAddressAgentImpl class and invoke the configure method on the resulting object, which must implement the com.sun.corba.ee.spi.orb.ORBConfigurator interface. The ORBUserConfigurators value doesn't matter. Together, these options create an ORB that in turn creates Object references (the underlying implementation of remote EJB references) containing the public address, while the ORB listens on the private address specified for the IIOP port in the Enterprise Server configuration.

Chapter 12 Developing Connectors

This chapter describes Sun GlassFish Enterprise Server support for the J2EETM 1.5 Connector Architecture (CA).

The J2EE Connector Architecture provides a Java solution to the problem of connectivity between multiple application servers and existing enterprise information systems (EISs). By using the J2EE Connector architecture, EIS vendors no longer need to customize their product for each application server. Application server vendors who conform to the J2EE Connector architecture do not need to write custom code to add connectivity to a new EIS.

This chapter uses the terms connector and resource adapter interchangeably. Both terms refer to a resource adapter module that is developed in conformance with the J2EE Connector Specification.

For more information about connectors, see J2EE Connector Architecture and “Chapter 37: J2EE Connector Architecture” in the Java EE 5 Tutorial.

For connector examples, see http://developers.sun.com/prodtech/appserver/reference/techart/as8_connectors.

This chapter includes the following topics:

Connector Support in the Enterprise Server

The Enterprise Server supports the development and deployment of resource adapters that are compatible with Connector specification (and, for backward compatibility, the Connector 1.0 specification).

The Connector 1.0 specification defines the outbound connectivity system contracts between the resource adapter and the Enterprise Server. The Connector 1.5 specification introduces major additions in defining system level contracts between the Enterprise Server and the resource adapter with respect to the following:

Connector Architecture for JMS and JDBC

In the Admin Console, connector, JMS, and JDBC resources are handled differently, but they use the same underlying Connector architecture. In the Enterprise Server, all communication to an EIS, whether to a message provider or an RDBMS, happens through the Connector architecture. To provide JMS infrastructure to clients, the Enterprise Server uses the Sun GlassFish Message Queue software. To provide JDBC infrastructure to clients, the Enterprise Server uses its own JDBC system resource adapters. The application server automatically makes these system resource adapters available to any client that requires them.

For more information about JMS in the Enterprise Server, see Chapter 18, Using the Java Message Service. For more information about JDBC in the Enterprise Server, see Chapter 15, Using the JDBC API for Database Access.

Connector Configuration

The Enterprise Server does not need to use sun-ra.xml, which previous Enterprise Server versions used, to store server-specific deployment information inside a Resource Adapter Archive (RAR) file. (However, the sun-ra.xml file is still supported for backward compatibility.) Instead, the information is stored in the server configuration. As a result, you can create multiple connector connection pools for a connection definition in a functional resource adapter instance, and you can create multiple user-accessible connector resources (that is, registering a resource with a JNDI name) for a connector connection pool. In addition, dynamic changes can be made to connector connection pools and the connector resource properties without restarting the Enterprise Server.

Deploying and Configuring a Stand-Alone Connector Module

You can deploy a stand-alone connector module using the Admin Console or the asadmin command. For information about using the Admin Console, click the Help button in the Admin Console. For information about using the asadmin command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Deploying a stand-alone connector module allows multiple deployed Java EE applications to share the connector module. A resource adapter configuration is automatically created for the connector module.

ProcedureTo Deploy and Configure a Stand-Alone Connector Module

  1. Deploy the connector module in one of the following ways.

    • In the Admin Console, open the Applications component and select Connector Modules. When you deploy the connector module, a resource adapter configuration is automatically created for the connector module.

    • Use the asadmin deploy or asadmin deploydir command. To override the default configuration properties of a resource adapter, if necessary, use the asadmin create-resource-adapter-config command.

  2. Configure connector connection pools for the deployed connector module in one of the following ways:

    • In the Admin Console, open the Resources component, select Connectors, and select Connector Connection Pools.

    • Use the asadmin create-connector-connection-pool command.

  3. Configure connector resources for the connector connection pools in one of the following ways.

    • In the Admin Console, open the Resources component, select Connectors, and select Connector Resources.

    • Use the asadmin create-connector-resource command.

    This associates a connector resource with a JNDI name.

  4. Create an administered object for an inbound resource adapter, if necessary, in one of the following ways:

    • In the Admin Console, open the Resources component, select Connectors, and select Admin Object Resources.

    • Use the asadmin create-admin-object command.

Redeploying a Stand-Alone Connector Module

Redeployment of a connector module maintains all connector connection pools, connector resources, and administered objects defined for the previously deployed connector module. You need not reconfigure any of these resources.

However, you should redeploy any dependent modules. A dependent module uses or refers to a connector resource of the redeployed connector module. Redeployment of a connector module results in the shared class loader reloading the new classes. Other modules that refer to the old resource adapter classes must be redeployed to gain access to the new classes. For more information about class loaders, see Chapter 2, Class Loaders.

During connector module redeployment, the server log provides a warning indicating that all dependent applications should be redeployed. Client applications or application components using the connector module’s resources may throw class cast exceptions if dependent applications are not redeployed after connector module redeployment.

To disable automatic redeployment, set the --force option to false. In this case, if the connector module has already been deployed, the Enterprise Server provides an error message.

Deploying and Configuring an Embedded Resource Adapter

A connector module can be deployed as a Java EE component in a Java EE application. Such connectors are only visible to components residing in the same Java EE application. Simply deploy this Java EE application as you would any other Java EE application.

You can create new connector connection pools and connector resources for a connector module embedded within a Java EE application by prefixing the connector name with app-name#. For example, if an application appX.ear has jdbcra.rar embedded within it, the connector connection pools and connector resources refer to the connector module as appX#jdbcra.

However, an embedded connector module cannot be undeployed using the name app-name#connector-name. To undeploy the connector module, you must undeploy the application in which it is embedded.

The association between the physical JNDI name for the connector module in the Enterprise Server and the logical JNDI name used in the application component is specified in the Enterprise Server specific XML descriptor sun-ejb-jar.xml.

Advanced Connector Configuration Options

You can use these advanced connector configuration options:

Thread Pools

Connectors can submit work instances to the Enterprise Server for execution. By default, the Enterprise Server services work requests for all connectors from its default thread pool. However, you can associate a specific user-created thread pool to service work requests from a connector. A thread pool can service work requests from multiple resource adapters. To create a thread pool:

To associate a connector with a thread pool:

If you create a resource adapter configuration for a connector module that is already deployed, the connector module deployment is restarted with the new configuration properties.

Security Maps

Create a security map for a connector connection pool to map an application principal or a user group to a back end EIS principal. The security map is usually used in situations where one or more EIS back end principals are used to execute operations (on the EIS) initiated by various principals or user groups in the application.

To create or update security maps for a connector connection pool:

If a security map already exists for a connector connection pool, the new security map is appended to the previous one. The connector security map configuration supports the use of the wildcard asterisk (*) to indicate all users or all user groups.

When an application principal initiates a request to an EIS, the Enterprise Server first checks for an exact match to a mapped back end EIS principal using the security map defined for the connector connection pool. If there is no exact match, the Enterprise Server uses the wild card character specification, if any, to determined the mapped back end EIS principal.

Overriding Configuration Properties

You can override the properties (config-property elements) specified in the ra.xml file of a resource adapter. Use the asadmin create-resource-adapter-config command to create a configuration for a resource adapter. Use this command’s --property option to specify a name-value pair for a resource adapter property.

You can use the asadmin create-resource-adapter-config command either before or after resource adapter deployment. If it is executed after deploying the resource adapter, the existing resource adapter is restarted with the new properties. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

You can also use token replacement for overriding resource adapter configuration properties in individual server instances when the resource adapter is deployed to a cluster. For example, for a property called inboundPort, you can assign the value ${inboundPort}. You can then assign a different value to this property for each server instance. Changes to system properties take effect upon server restart.

Testing a Connector Connection Pool

After configuring a connector connection pool, use the asadmin ping-connection-pool command to test the health of the underlying connections. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Handling Invalid Connections

If a resource adapter generates a ConnectionErrorOccured event, the Enterprise Server considers the connection invalid and removes the connection from the connection pool. Typically, a resource adapter generates a ConnectionErrorOccured event when it finds a ManagedConnection object unusable. Reasons can be network failure with the EIS, EIS failure, fatal problems with resource adapter, and so on. If the fail-all-connections property in the connection pool configuration is set to true, all connections are destroyed and the pool is recreated.

The is-connection-validation-required property specifies whether connections have to be validated before being given to the application. If a resource’s validation fails, it is destroyed, and a new resource is created and returned.

You can set the fail-all-connections and is-connection-validation-required configuration properties during creation of a connector connection pool. Or, you can use the asadmin set command to dynamically reconfigure a previously set property. For details, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

The interface ValidatingManagedConnectionFactory exposes the method getInvalidConnections to allow retrieval of the invalid connections. The Enterprise Server checks if the resource adapter implements this interface, and if it does, invalid connections are removed when the connection pool is resized.

Setting the Shutdown Timeout

According to the Connector specification, while an application server shuts down, all resource adapters should be stopped. A resource adapter might hang during shutdown, since shutdown is typically a resource intensive operation. To avoid such a situation, you can set a timeout that aborts resource adapter shutdown if exceeded. The default timeout is 30 seconds per resource adapter module. To configure this timeout:

The Enterprise Server deactivates all message-driven bean deployments before stopping a resource adapter.

Using Last Agent Optimization of Transactions

Transactions that involve multiple resources or multiple participant processes are distributed or global transactions. A global transaction can involve one non-XA resource if last agent optimization is enabled. Otherwise, all resources must be XA. For more information about transactions in the Enterprise Server, see Chapter 16, Using the Transaction Service.

The Connector specification requires that if a resource adapter supports XATransaction, the ManagedConnection created from that resource adapter must support both distributed and local transactions. Therefore, even if a resource adapter supports XATransaction, you can configure its connector connection pools as non-XA or without transaction support for better performance. A non-XA resource adapter becomes the last agent in the transactions in which it participates.

The value of the connection pool configuration property transaction-support defaults to the value of the transaction-support property in the ra.xml file. The connection pool configuration property can override the ra.xml file property if the transaction level in the connection pool configuration property is lower. If the value in the connection pool configuration property is higher, it is ignored.

Inbound Communication Support

The Connector specification defines the transaction and message inflow system contracts for achieving inbound connectivity from an EIS. The message inflow contract also serves as a standard message provider pluggability contract, thereby allowing various message providers to seamlessly plug in their products with any application server that supports the message inflow contract. In the inbound communication model, the EIS initiates all communication to an application. An application can be composed of enterprise beans (session, entity, or message-driven beans), which reside in an EJB container.

Incoming messages are received through a message endpoint, which is a message-driven bean. This message-driven bean asynchronously consumes messages from a message provider. An application can also synchronously send and receive messages directly using messaging style APIs.

A resource adapter supporting inbound communication provides an instance of an ActivationSpec JavaBean class for each supported message listener type. Each class contains a set of configurable properties that specify endpoint activation configuration information during message-driven bean deployment. The required config-property element in the ra.xml file provides a list of configuration property names required for each activation specification. An endpoint activation fails if the required property values are not specified. Values for the properties that are overridden in the message-driven bean’s deployment descriptor are applied to the ActivationSpec JavaBean when the message-driven bean is deployed.

Administered objects can also be specified for a resource adapter, and these JavaBeans are specific to a messaging style or message provider. For example, some messaging styles may need applications to use special administered objects (such as Queue and Topic objects in JMS). Applications use these objects to send and synchronously receive messages using connection objects using messaging style APIs. For more information about administered objects, see Chapter 18, Using the Java Message Service.

Configuring a Message Driven Bean to Use a Resource Adapter

The Connectors specification’s message inflow contract provides a generic mechanism to plug in a wide-range of message providers, including JMS, into a Java-EE-compatible application server. Message providers use a resource adapter and dispatch messages to message endpoints, which are implemented as message-driven beans.

The message-driven bean developer provides activation configuration information in the message-driven bean’s ejb-jar.xml file. Configuration information includes messaging-style-specific configuration details, and possibly message-provider-specific details as well. The message-driven bean deployer uses this configuration information to set up the activation specification JavaBean. The activation configuration properties specified in ejb-jar.xml override configuration properties in the activation specification definition in the ra.xml file.

According to the EJB specification, the messaging-style-specific descriptor elements contained within the activation configuration element are not specified because they are specific to a messaging provider. In the following sample message-driven bean ejb-jar.xml, a message-driven bean has the following activation configuration property names: destinationType, SubscriptionDurability, and MessageSelector.

<!--  A sample MDB that listens to a JMS Topic -->
<!-- message-driven bean deployment descriptor -->
...
 <activation-config>
   <activation-config-property>
     <activation-config-property-name>
       destinationType
     </activation-config-property-name>
     <activation-config-property-value>
       javax.jms.Topic
     </activation-config-property-value>
  </activation-config-property>
  <activation-config-property>
     <activation-config-property-name>
       SubscriptionDurability
     </activation-config-property-name>
     <activation-config-property-value>
       Durable
     </activation-config-property-value>
  </activation-config-property>
  <activation-config-property>
     <activation-config-property-name>
       MessageSelector
     </activation-config-property-name>
     <activation-config-property-value>
       JMSType = 'car' AND color = 'blue'
     </activation-config-property-value>
  </activation-config-property>
 ...
 </activation-config>
...

When the message-driven bean is deployed, the value for the resource-adapter-mid element in the sun-ejb-jar.xml file is set to the resource adapter module name that delivers messages to the message endpoint (to the message-driven bean). In the following example, the jmsra JMS resource adapter, which is the bundled resource adapter for the Sun GlassFish Message Queue message provider, is specified as the resource adapter module identifier for the SampleMDB bean.

<sun-ejb-jar>
<enterprise-beans>
	<unique-id>1</unique-id>
	<ejb>
	   <ejb-name>SampleMDB</ejb-name>
	   <jndi-name>SampleQueue</jndi-name>
    <!-- JNDI name of the destination from which messages would be 
         delivered from MDB needs to listen to -->
    ...
    <mdb-resource-adapter>
       <resource-adapter-mid>jmsra</resource-adapter-mid>
       <!-- Resource Adapter Module Id that would deliver messages to 
            this message endpoint -->
	   </mdb-resource-adapter>
    ...
 </ejb>
 ...
</enterprise-beans>
...
</sun-ejb-jar>

When the message-driven bean is deployed, the Enterprise Server uses the resourceadapter-mid setting to associate the resource adapter with a message endpoint through the message inflow contract. This message inflow contract with the application server gives the resource adapter a handle to the MessageEndpointFactory and the ActivationSpec JavaBean, and the adapter uses this handle to deliver messages to the message endpoint instances (which are created by the MessageEndpointFactory).

When a message-driven bean first created for use on the Enterprise Server 7 is deployed, the Connector runtime transparently transforms the previous deployment style to the current connector-based deployment style. If the deployer specifies neither a resource-adapter-mid property nor the Message Queue resource adapter’s activation configuration properties, the Connector runtime maps the message-driven bean to the jmsra system resource adapter and converts the JMS-specific configuration to the Message Queue resource adapter’s activation configuration properties.

Chapter 13 Developing Lifecycle Listeners

Lifecycle listener modules provide a means of running short or long duration Java-based tasks within the application server environment, such as instantiation of singletons or RMI servers. These modules are automatically initiated at server startup and are notified at various phases of the server life cycle.

All lifecycle module classes and interfaces are in the as-install/lib/appserv-ext.jar file.

For Javadoc tool pages relevant to lifecycle modules, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.server package.

The following sections describe how to create and use a lifecycle listener module:

Server Life Cycle Events

A lifecycle module listens for and performs its tasks in response to the following events in the server life cycle:

These events are defined in the LifecycleEvent class.

The lifecycle modules that listen for these events implement the LifecycleListener interface.

The LifecycleListener Interface

To create a lifecycle module is to configure a customized class that implements the com.sun.appserv.server.LifecycleListener interface. You can create and simultaneously execute multiple lifecycle modules.

The LifecycleListener interface defines this method:

public void handleEvent(com.sun.appserv.server.LifecycleEvent event) 
throws ServerLifecycleException

This method responds to a lifecycle event and throws a com.sun.appserv.server.ServerLifecycleException if an error occurs.

A sample implementation of the LifecycleListener interface is the LifecycleListenerImpl.java file, which you can use for testing lifecycle events.

The LifecycleEvent Class

The com.sun.appserv.server.LifecycleEvent class defines a server life cycle event. The following methods are associated with the event:

A LifecycleEvent instance is passed to the LifecycleListener.handleEvent method.

The Server Lifecycle Event Context

The com.sun.appserv.server.LifecycleEventContext interface exposes runtime information about the server. The lifecycle event context is created when the LifecycleEvent class is instantiated at server initialization. The LifecycleEventContext interface defines these methods:

If a lifecycle module needs to look up resources, it can do so after the READY_EVENT. It can use the getInitialContext() method to get the initial context to which all the resources are bound.

Deploying a Lifecycle Module

You can deploy a lifecycle module using the following tools:

You do not need to specify a classpath for the lifecycle module if you place it in the domain-dir/lib or domain-dir/lib/classes directory for the Domain Administration Server. Do not place it in the lib directory for a particular instance, or it will be deleted when that instance synchronizes with the Domain Administration Server.

After you deploy a lifecycle module, you must restart the server to activate it. The server instantiates it and registers it as a lifecycle event listener at server initialization.


Note –

If the is-failure-fatal setting is set to true (the default is false), lifecycle module failure prevents server initialization or startup, but not shutdown or termination.


Considerations for Lifecycle Modules

The resources allocated at initialization or startup should be freed at shutdown or termination. The lifecycle module classes are called synchronously from the main server thread, therefore it is important to ensure that these classes don’t block the server. Lifecycle modules can create threads if appropriate, but these threads must be stopped in the shutdown and termination phases.

The LifeCycleModule class loader is the parent class loader for lifecycle modules. Each lifecycle module’s classpath in domain.xml is used to construct its class loader. All the support classes needed by a lifecycle module must be available to the LifeCycleModule class loader or its parent, the Connector class loader.

You must ensure that the server.policy file is appropriately set up, or a lifecycle module trying to perform a System.exec() might cause a security access violation. For details, see The server.policy File.

The configured properties for a lifecycle module are passed as properties after the INIT_EVENT. The JNDI naming context is not available before the STARTUP_EVENT. If a lifecycle module requires the naming context, it can get this after the STARTUP_EVENT, READY_EVENT, or SHUTDOWN_EVENT.

Chapter 14 Developing Custom MBeans

An MBean is a managed Java object, similar to a JavaBeanTM, that follows the design patterns set forth in the instrumentation level of the JavaTM Management Extensions (JMXTM) specification. An MBean can represent a device, an application, or any resource that needs to be managed. MBeans expose a management interface: a set of readable and/or writable attributes and a set of invokable operations, along with a self-description. The actual runtime interface of an MBean depends on the type of that MBean. MBeans can also emit notifications when certain defined events occur. Unlike other components, MBeans have no annotations or deployment descriptors.

The Sun GlassFish Enterprise Server supports the development of custom MBeans as part of the self-management infrastructure or as separate applications. All types of MBeans (standard, dynamic, open, and model) are supported. For more about self-management, see Chapter 20, Using the Application Server Management Extensions and Chapter 19, Configuring Management Rules, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

For general information about JMX technology, including how to download the JMX specification, see http://java.sun.com/products/JavaManagement/index.jsp.

For a useful overview of JMX technology, see http://java.sun.com/javase/6/docs/technotes/guides/jmx/overview/JMXoverviewTOC.html.

For a tutorial of JMX technology, see http://java.sun.com/javase/6/docs/technotes/guides/jmx/tutorial/tutorialTOC.html.

This chapter includes the following topics:

The MBean Life Cycle

The MBean life cycle proceeds as follows:

  1. The MBean's class files are installed in the Enterprise Server. See MBean Class Loading.

  2. The MBean is deployed using the asadmin create-mbean command or the Admin Console. See Creating, Deleting, and Listing MBeans.

  3. The MBean class is loaded. This also results in loading of other classes. The delegation model is used. See the class loader diagram in The Class Loader Hierarchy.

  4. The MBean is instantiated. Its default constructor is invoked reflectively. This is why the MBean class must have a default constructor.

  5. The MBean's ObjectName is determined according to the following algorithm.

    • If you specify the ObjectName, it is used as is. The domain must be user:. The property name server is reserved and cannot be used.

      The Enterprise Server automatically appends server=target to the ObjectName when the MBean is registered, where the target is the name of the server instance or cluster to which the MBean is deployed.

    • If the MBean implements the MBeanRegistration interface, it must provide an ObjectName in its preregister() method that follows the same rules.

    • If the ObjectName is not specified directly or through the MBeanRegistration interface, the default is user:type=impl-class-name.

  6. All attributes are set using setAttribute calls in the order in which the attributes are specified. Attempting to specify a read-only attribute results in an error.

    If attribute values are set during MBean deployment, these values are passed in as String objects. Therefore, attribute types must be Java classes having constructors that accept String objects. If you specify an attribute that does not have such a constructor, an error is reported.

    Attribute values specified during MBean deployment are persisted to the Enterprise Server configuration. Changes to attributes after registration through a JMX connector such as JConsole do not affect the Enterprise Server configuration. To change an attribute value in the Enterprise Server configuration, use the asadmin set command. See Handling MBean Attributes.

  7. If the MBean is enabled, the MBeanServer.registerMBean(Object, ObjectName) method is used to register the MBean in the MBeanServer. This is the only method called by the Enterprise Server runtime. See The MBeanServer in the Enterprise Server.

    MBeans are enabled by default. Disabling an MBean deregisters it. See Enabling and Disabling MBeans.

  8. The MBean is automatically loaded, instantiated, and registered upon each server restart.

  9. When the MBean is deleted using the asadmin delete-mbean command or the Admin Console, the MBean is first deregistered if it is enabled, then the MBean definition is deleted from the configuration. The class files are not deleted, however.

MBean Class Loading

After you develop a custom MBean, copy its class files (or JAR file) into the MBean class loader directory, domain-dir/applications/mbeans. You have two choices of where to place any dependent classes:

After copying the classes, register the MBean using the asadmin create-mbean command. See The asadmin create-mbean Command.

For general information about Enterprise Server class loaders, see Chapter 2, Class Loaders.

Creating, Deleting, and Listing MBeans

This section describes the following commands:

To perform these tasks using the Admin Console, open the Custom MBeans component. For details, click the Help button in the Admin Console.

The asadmin create-mbean Command

After installing the MBean classes as explained in MBean Class Loading, use the asadmin create-mbean command to deploy the MBean. This registers the MBean in the MBeanServer that is part of the Enterprise Server runtime environment. For more information about the MBeanServer, see The MBeanServer in the Enterprise Server.

Here is a simple example of an asadmin create-mbean command in which TextPatterns is the implementation class. The --attributes and --target options are not required.


asadmin create-mbean --user adminuser --target server1 --attributes color=red:font=Times TextPatterns

Other options not included in the example are as follows:

All options must precede the implementation class.

For full details on the asadmin create-mbean command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

For more information about MBean attributes, see Handling MBean Attributes.


Note –

To redeploy an MBean, simply install its new classes into the Enterprise Server as described in MBean Class Loading. Then either restart the server or use asadmin delete-mbean followed by asadmin create-mbean.


The asadmin delete-mbean Command

To undeploy an MBean, use the asadmin delete-mbean command. This removes its registration from the MBeanServer, but does not delete its code. Here is an example asadmin delete-mbean command in which TextPatterns is the implementation class. The --target option is not required.


asadmin delete-mbean --user adminuser --target server1 TextPatterns

For full details on the asadmin delete-mbean command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

The asadmin list-mbeans Command

To list MBeans that have been deployed, use the asadmin list-mbeans command. Note that this command only lists the MBean definitions and not the MBeans registered in the MBeanServer. Here is an example asadmin list-mbeans command. The --target option is not required.


asadmin list-mbeans --user adminuser --target server1

The output of the asadmin list-mbeans command lists the following information:

For full details on the asadmin list-mbeans command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

The MBeanServer in the Enterprise Server

Custom MBeans are registered in the PlatformMBeanServer returned by the java.lang.management.ManagementFactory.getPlatformMBeanServer() method. This MBeanServer is associated with a standard JMX connector server.

You can use any JMX connector to look up MBeans in this MBeanServer just as you would any other MBeanServer. If your JMX connector is remote, you can connect to this MBeanServer using the following information:

For example, if you use JConsole, you can enter this information under the Remote tab. JConsole is a generic JMX connector you can use to look up and manage MBeans. For more information about JConsole, see http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html, the JMX tutorial at http://java.sun.com/javase/6/docs/technotes/guides/jmx/tutorial/tutorialTOC.html, and Using JConsole in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

The connection to this MBeanServer is non-SSL by default for the developer profile and SSL by default for the cluster profile.

If SSL is enabled, you must provide the location of the truststore that contains the server certificate that the JMX connector should trust. For example, if you are using JConsole, you supply this location at the command line as follows:


jconsole -J-Djavax.net.ssl.trustStore=home-directory/.asadmintruststore

Look up the MBean by its name. By default, the name is the same as the implementation class.

You can reconfigure the JMX connector server's naming service port in one of the following ways:

Enabling and Disabling MBeans

A custom MBean is enabled by default. You can disable an MBean during deployment by using the asadmin create-mbean command's optional --enabled=false option. See The asadmin create-mbean Command.

After deployment, you can disable an MBean using the asadmin set command. For example:


asadmin set --user adminuser server1.applications.mbean.TextPatterns.enabled=false

If the MBean name is different from the implementation class, you must use the name in the asadmin set command. In this example, the name is TextPatterns.

For full details on the asadmin set command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

Handling MBean Attributes

You can set MBean attribute values that are not read-only in the following ways:

In the Enterprise Server configuration, MBean attributes are stored as properties. Therefore, using the asadmin set command means editing properties. For example:


asadmin set --user adminuser server1.applications.mbean.TextPatterns.property.color=blue

If the MBean name is different from the implementation class, you must use the MBean name in the asadmin set command. In this example, the name is TextPatterns.

For full details on the asadmin set command, see the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.