Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  JavaServer Faces Technology

5.  Introduction to Facelets

6.  Expression Language

7.  Using JavaServer Faces Technology in Web Pages

8.  Using Converters, Listeners, and Validators

9.  Developing with JavaServer Faces Technology

10.  JavaServer Faces Technology: Advanced Concepts

11.  Using Ajax with JavaServer Faces Technology

12.  Composite Components: Advanced Topics and Example

13.  Creating Custom UI Components and Other Custom Objects

14.  Configuring JavaServer Faces Applications

15.  Java Servlet Technology

16.  Uploading Files with Java Servlet Technology

17.  Internationalizing and Localizing Web Applications

Part III Web Services

18.  Introduction to Web Services

19.  Building Web Services with JAX-WS

20.  Building RESTful Web Services with JAX-RS

21.  JAX-RS: Advanced Topics and Example

Part IV Enterprise Beans

22.  Enterprise Beans

23.  Getting Started with Enterprise Beans

24.  Running the Enterprise Bean Examples

25.  A Message-Driven Bean Example

26.  Using the Embedded Enterprise Bean Container

27.  Using Asynchronous Method Invocation in Session Beans

Asynchronous Method Invocation

Creating an Asynchronous Business Method

Calling Asynchronous Methods from Enterprise Bean Clients

Retrieving the Final Result from an Asynchronous Method Invocation

Cancelling an Asynchronous Method Invocation

Checking the Status of an Asynchronous Method Invocation

Part V Contexts and Dependency Injection for the Java EE Platform

28.  Introduction to Contexts and Dependency Injection for the Java EE Platform

29.  Running the Basic Contexts and Dependency Injection Examples

30.  Contexts and Dependency Injection for the Java EE Platform: Advanced Topics

31.  Running the Advanced Contexts and Dependency Injection Examples

Part VI Persistence

32.  Introduction to the Java Persistence API

33.  Running the Persistence Examples

34.  The Java Persistence Query Language

35.  Using the Criteria API to Create Queries

36.  Creating and Using String-Based Criteria Queries

37.  Controlling Concurrent Access to Entity Data with Locking

38.  Using a Second-Level Cache with Java Persistence API Applications

Part VII Security

39.  Introduction to Security in the Java EE Platform

40.  Getting Started Securing Web Applications

41.  Getting Started Securing Enterprise Applications

42.  Java EE Security: Advanced Topics

Part VIII Java EE Supporting Technologies

43.  Introduction to Java EE Supporting Technologies

44.  Transactions

45.  Resources and Resource Adapters

46.  The Resource Adapter Example

47.  Java Message Service Concepts

48.  Java Message Service Examples

49.  Bean Validation: Advanced Topics

50.  Using Java EE Interceptors

Part IX Case Studies

51.  Duke's Bookstore Case Study Example

52.  Duke's Tutoring Case Study Example

53.  Duke's Forest Case Study Example

Index

 

The async Example Application

The async example demonstrates how to define an asynchronous business method on a session bean and call it from a web client. The MailerBean stateless session bean defines an asynchronous method, sendMessage, which uses the JavaMail API to send an email to a specified email address.


Note - This example needs to be configured for your environment before it runs correctly, and requires access to an SMTPS server.


Architecture of the async Example Application

The async application consists of a single stateless session bean, MailerBean, and a JavaServer Faces web application front end that uses Facelets tags in XHTML files to display a form for users to enter the email address for the recipient of an email. The status of the email is updated when the email is finally sent.

The MailerBean session bean injects a JavaMail resource used to send an email message to an address specified by the user. The message is created, modified, and sent using the JavaMail API. The injected JavaMail resource is configured through the GlassFish Server Administration Console, or through a resource configuration file packaged with the application. The resource configuration can be modified at runtime by the GlassFish Server administrator to use a different mail server or transport protocol.

@Asynchronous
public Future<String> sendMessage(String email) {
    String status;
    try {
        Message message = new MimeMessage(session);
        message.setFrom();
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(email, false));
        message.setSubject("Test message from async example");
        message.setHeader("X-Mailer", "JavaMail");
        DateFormat dateFormatter = DateFormat
                .getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
        Date timeStamp = new Date();
        String messageBody = "This is a test message from the async example "
                + "of the Java EE Tutorial. It was sent on "
                + dateFormatter.format(timeStamp)
                + ".";
        message.setText(messageBody);
        message.setSentDate(timeStamp);
        Transport.send(message);
        status = "Sent";
        logger.log(Level.INFO, "Mail sent to {0}", email);
    } catch (MessagingException ex) {
        logger.severe("Error in sending message.");
        status = "Encountered an error";
        logger.severe(ex.getMessage() + ex.getNextException().getMessage());
        logger.severe(ex.getCause().getMessage());
    }
    return new AsyncResult<String>(status);
}

The web client consists of a Facelets template, template.xhtml, two Facelets clients, index.xhtml and response.xhtml, and a JavaServer Faces managed bean, MailerManagedBean. The index.xhtml file contains a form for the target email address. When the user submits the form, the MailerManagedBean.send method is called. This method uses an injected instance of the MailerBean session bean to call MailerBean.sendMessage. The result is sent to the response.xhtml Facelets view.

Running the async Example

You can use either NetBeans IDE or Ant to build, package, deploy, and run the async example. First, however, you must configure the keystore and truststore.

To Configure the Keystore and Truststore in GlassFish Server

The GlassFish Server domain needs to be configured with the server’s master password to access the keystore and truststore used to initiate secure communications using the SMTPS transport protocol.

  1. Open the GlassFish Server Administration Console in a web browser at http://localhost:4848.
  2. Expand Configurations, then expand server-config, then click JVM Settings.
  3. Click JVM Options, then click Add JVM Option and enter -Djavax.net.ssl.keyStorePassword=master-password, replacing master-password with the keystore master password. The default master password is changeit.
  4. Click Add JVM Option and enter -Djavax.net.ssl.trustStorePassword=master-password, replacing master-password with the truststore master password. The default master password is changeit.
  5. Click Save, then restart GlassFish Server.

To Run the async Example Using NetBeans IDE

Before You Begin

Before running this example, you must configure your GlassFish Server instance to access the keystore and truststore used by GlassFish Server to create a secure connection to the target SMTPS server.

  1. From the File menu, choose Open Project.
  2. In the Open Project dialog, navigate to:
    tut-install/examples/ejb/
  3. Select the async folder and click Open Project.
  4. Under async in the project pane, expand the Server Resources node and double-click glassfish-resources.xml.
  5. Enter the configuration settings for your SMTPS server in glassfish-resources.xml.

    The SMTPS server host name is set in the host attribute; the email address from which you want the message sent is set in the from attribute; and the SMTPS user name is set in the user attribute. Set the mail-smtps-password property value to the password for the SMTPS server user. The following code snippet shows an example resource configuration. Lines in bold need to be modified.

    <resources>
        <mail-resource debug="false" 
                enabled="true" 
                from="user@example.com" 
                host="smtp.example.com" 
                jndi-name="mail/myExampleSession" 
                object-type="user" store-protocol="imap" 
                store-protocol-class="com.sun.mail.imap.IMAPStore" 
                transport-protocol="smtps" 
                transport-protocol-class="com.sun.mail.smtp.SMTPSSLTransport" 
                user="user@example.com">
            <description/>
            <property name="mail-smtps-auth" value="true"/>
            <property name="mail-smtps-password" value="mypassword"/>
        </mail-resource>
    </resources>
  6. Right-click async in the project pane and select Run.

    This will compile, assemble, and deploy the application, and start a web browser at the following URL: http://localhost:8080/async.

  7. In the web browser window, enter the email to which you want the test message sent and click Send email.

    If your configuration settings are correct, a test email will be sent, and the status message will read Sent in the web client. The test message should appear momentarily in the inbox of the recipient.

    If an error occurs, the status will read Encountered an error. Check the server.log file for your domain to find the cause of the error.

To Run the async Example Using Ant

  1. In a terminal window, navigate to tut-install/examples/ejb/async/.
  2. In a text editor, open setup/glassfish-resources.xml and enter the configuration settings for your SMTPS server.

    The SMTPS server host name is set in the host attribute, email address from which you want the message sent is the from attribute, the SMTPS user name is the user attribute. Set the mail-smtps-password property value to the password for the SMTPS server user. The following code snippet shows an example resource configuration. Lines in bold need to be modified.

    <resources>
        <mail-resource debug="false" 
                enabled="true" 
                from="user@example.com" 
                host="smtp.example.com" 
                jndi-name="mail/myExampleSession" 
                object-type="user" store-protocol="imap" 
                store-protocol-class="com.sun.mail.imap.IMAPStore" 
                transport-protocol="smtps" 
                transport-protocol-class="com.sun.mail.smtp.SMTPSSLTransport" 
                user="user@example.com">
            <description/>
            <property name="mail-smtps-auth" value="true"/>
            <property name="mail-smtps-password" value="mypassword"/>
        </mail-resource>
    </resources>
  3. Enter the following command:
    ant all

    This will compile, assemble, and deploy the application, and start a web browser at the following URL: http://localhost:8080/async.


    Note - If your build system isn’t configured to automatically open a web browser, open the above URL in a browser window.


  4. In the web browser window, enter the email to which you want the test message sent and click Send email.

    If your configuration settings are correct, a test email will be sent, and the status message will read Sent in the web client. The test message should appear momentarily in the inbox of the recipient.

    If an error occurs, the status will read Encountered an error. Check the server.log file for your domain to find the cause of the error.