Developing JavaMail Applications

Today you'll develop the Emailer EJB, which is responsible in our university registration system for sending e-mails to students when they submit courses at enrollment time, and for notifying them again when they are approved for registration.

Our example today uses the Model-View-Controller (MVC) architecture pattern to design a JavaMail application. The servlet component in the Web tier represents the controller, which acts as a client to the EJB tier. The Emailer EJB in the EJB tier represents the model, which handles business logic (primarily sending an e-mail message). The view is represented by an HTML form (which could be a JSP) that interacts with the servlet. Figure 20.2 illustrates the use of the MVC pattern in designing our JavaMail application.

Figure 20.2. Using the MVC pattern in the JavaMail application.


The example also partitions the application into a Web tier module (packaged into a WAR file) as well as an EJB module (packaged into a JAR file). You'll learn how to create and deploy an EAR file, which combines both the JAR file and the WAR file into an enterprise application.

Figure 20.3 summarizes the sequence diagram of the sample application in sending an e-mail message. The student interacts with the EmailerServlet using the emailer.html HTML form. The EmailerServlet, on behalf of the client, relays the request to the Emailer EJB, which sends the e-mail to the recipient through the e-mail server.

Figure 20.3. The sequence diagram for sending an e-mail message.


Here's a summary of the steps required to develop your JavaMail application of today's example:

1.
Develop the EJB tier components. You need to develop only one component: the Emailer session bean.

2.
Package the EJB tier into an EJB module (JAR file).

3.
Develop the Web tier components. You need to develop the EmailerServlet.

4.
Package the Web tier components into a Web module (WAR file).

5.
Package the modules into an application (EAR file).

6.
Develop an HTML form (this could be a JSP) as a GUI to make requests to the Web tier.

7.
Create and configure the JavaMail Session on both the WebLogic Server and JBoss server environments.

8.
Deploy and run the application on each server.

The following sections give you more details about performing each of the steps mentioned in this list. As usual, the full application code listing, and scripts for compiling and deploying into the WebLogic Server and JBoss server environments can be downloaded from our Web site.

Developing the EJB Tier Components

The EJB tier contains only the Emailer EJB, and we selected a stateless session bean to model its activities. The main business method is the sendMail() method, which sends e-mail messages to students. To optimize the Emailer EJB, you can cache the mail Session object so that you don't have to look it up every time you send a message.

As you learned on previous days, we need to develop the remote interface, home interface, and the bean class. The following listings provide the code for these components.

Listing 20.1 is for the remote interface Emailer, which lists all the business methods used in our example.

Listing 20.1. The Remote Interface Emailer.java
package day20;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
// Provides a method to send mail messages
public interface Mailer extends EJBObject {
    public void sendMail(String to, String body)
        throws RemoteException, URSMailerException;
}

Listing 20.2 shows the home interface EmailerHome, which lists all the life cycle methods used to manage the bean.

Listing 20.2. The Home Interface EmailerHome.java
package day20;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
// The Home interface for MailerEJB
public interface MailerHome extends EJBHome {
    public Mailer create() throws RemoteException, CreateException;
}

Listing 20.3 is the bean class EmailerEJB, which implements all the business methods listed in the remote interface and the callback methods to manage the bean's life cycle by the container.

Listing 20.3. The Bean Class EmailerEJB.java
package day20;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.Session;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

// Session Bean implementation of MailerEJB.
// Used to send a mail message confirmation such as an email
// to a student after a registration into courses is completed.

public class MailerEJB implements SessionBean {
    private Session mailSession = null;
    public void sendMail(String to, String body)throws URSMailerException {
      try {
          MimeMessage msg = new MimeMessage(mailSession);
          msg.setFrom();
          InternetAddress dest = new InternetAddress(to);
          msg.setSubject("Testing STYEJB JavaMail");
          msg.setRecipient(Message.RecipientType.TO, dest);
          msg.setSentDate(new Date());
          msg.setHeader("X-Mailer", "JavaMailer");
          msg.setContent(body, "text/plain");
          Transport.send(msg);
      } catch (Exception e) {
          e.printStackTrace();
          throw new URSMailerException("Failure while sending email");
      }
    }

    public void ejbCreate() {
      try {
          InitialContext ctx = new InitialContext();
          mailSession = (Session) ctx.lookup("java:comp/env/mail/Mail");
      } catch (javax.naming.NamingException e) {
          e.printStackTrace();
      }
    }
    public void ejbPostCreate() {}
    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void ejbRemove() {}
    public void setSessionContext(javax.ejb.SessionContext ec) {}
}

Notice that we've created the Session object in the ejbCreate() method, and cached it into the session instance variable. This will enhance the application's performance, and can handle a larger number of students.

Packaging the Emailer EJB into an EJB Module

For large applications, all the components of the EJB tiers are packaged into one JAR file, along with its deployment descriptors. For our example today, you need to package only one component.

To build the example for the appropriate application server, you need to be in the Day20 directory, and then run the build script provided for this server. This will create a build subdirectory that contains all the compiled code. The script will then package the EJBs with the deployment descriptor (see Listing 20.4) into an EJB module (JAR file).

Listing 20.4. The Deployment Descriptor ejb-jar.xml
<?xml version="1.0"?>

<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>MailerEJB</ejb-name>
      <home>day20.MailerHome</home>
      <remote>day20.Mailer</remote>
      <ejb-class>day20.MailerEJB</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
       <resource-env-ref>
								<resource-env-ref-name>mail/Mail</resource-env-ref-name>
								<resource-env-ref-type>javax.mail.Session</resource-env-ref-type>
								</resource-env-ref>
    </session>
  </enterprise-beans>
</ejb-jar>

You must provide a server-specific deployment descriptor for each application server; they are included in your download (jboss.xml for the JBoss server and weblogic-ejb-jar.xml for the WebLogic Server). For the sake of making your application portable, you must specify the <resource-env-ref> element in your ejb-jar.xml deployment descriptor, as you learned on Day 4.

Developing the Web Tier Components

This example includes a servlet component in the Web tier to act as a client to the Emailer EJB in the EJB tier. Students first interact with the servlet (through the HTML form discussed in the next section), and requests are relayed back to the EJB tier to execute the required business logic. Listing 20.5 is the EmailerServlet.

Listing 20.5. The Servlet EmailerServlet.java
package web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import day20.*;

// This Servlet will call the MailerEJB with the email address.
public class MailerServlet extends HttpServlet
{
   private MailerHome mailerHome = null;
   // Looks up the MailerHome interface and saves it for use in doGet().
   public void init() throws ServletException{
      try{
         InitialContext jndiCtx = new InitialContext();
         Object ref  = jndiCtx.lookup("day20/Mailer");
         mailerHome = (MailerHome)
              PortableRemoteObject.narrow(ref, MailerHome.class);
      }
      catch(Exception e){
         throw new ServletException("Failed to lookup Mailer", e);
      }
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException{
      String title = "Servlet client to Mailer EJB";
      String toAddress = request.getParameter("toAddress");
      String mailMsg   = request.getParameter("message");
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<HTML><HEAD><TITLE>");
      out.println(title);
      out.println("</TITLE></HEAD><BODY>");
      out.println("<H1>" + title + "</H1>");
      out.println("<H2>Calling EJB...</H2>");
      try{
         Mailer bean = mailerHome.create();
             bean.sendMail(toAddress, mailMsg);
             out.println("Mail Message is sent....");
      }
      catch(Exception e){
         out.println(e.toString());
      }
      finally{
         out.println("</BODY></HTML>");
         out.close();
      }
   }
}

Packaging the EmailerServlet into a WAR File Module

All components in the Web tier (such as JSP, servlets, and TagLibs), along with a web.xml deployment descriptor, should be packaged into a Web module (WAR file). You must also provide a server-specific Web deployment descriptor. The jboss-web.xml file is included for the JBoss server, and weblogic.xml is provided for WebLogic Server.

The script provided for each server will create a web subdirectory that contains all the compiled code. It will then package the EmailerServlet component and the deployment descriptor web.xml into a Web module (WAR file).

Listing 20.6 provides the web.xml deployment descriptor.

Listing 20.6. The Web Deployment Descriptor web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
        <servlet-name>MailerServlet</servlet-name>
        <servlet-class>MailerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MailerServlet</servlet-name>
        <url-pattern>/MailerServlet</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
      <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

Building the EAR File

The modules created in the previous sections—one for the Web tier and one for the EJB tier—can be combined into an application file (EAR file). For the sake of convenience, both scripts are also combined into one script to package the application into an EAR file. Listing 20.7 shows the application.xml deployment descriptor that will combine both WAR and JAR files into an enterprise application.

Listing 20.7. The EAR Deployment Descriptor application.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC
   '-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN'
     'http://java.sun.com/dtd/application_1_3.dtd'>

<application>
    <display-name>STYEJB JavaMail Application</display-name>
    <module>
    <web>
        <web-uri>mailer.war</web-uri>
        <context-root>day20</context-root>
    </web>
    </module>
    <module>
        <ejb>mailer.jar</ejb>
    </module>
</application>

Listing 20.8 provides the build script for the WebLogic Server application server. The script for JBoss is included in the downloaded files.

Listing 20.8. The Build Script for WebLogic Server buildWebLogic.bat
@echo Compiling EJB tier files...
rem "Cleaning previous build (if any)"
rmdir /s/q build build1

rem "Creating a staging area for the build"
mkdir build buildMETA-INF

rem "Copying deployment files to META-INF directory"
copy %STYEJB_HOME%day20ejb-jar.xml buildMETA-INF
copy %STYEJB_HOME%day20weblogic-ejb-jar.xml buildMETA-INF

rem "Compiling  EJB classes and interfaces"
javac -g -d build URSMailerException.java 
        Mailer.java MailerHome.java MailerEJB.java

rem "Creating the EJB's deployment Jar file"
cd build
jar cv0f tmp_mailer.jar META-INF day20
cd ..

rem "Compiling the container classes"
java weblogic.ejbc -keepgenerated -g 
          -deprecation build	mp_mailer.jar buildmailer.jar

@echo Compiling Web tier files...
rem "Cleaning previous build (if any)"
rmdir /s/q web
mkdir web webWEB-INF webWEB-INFclasses

copy GUIMailerServlet.java web.
copy GUI*.html web.
javac -g -d webWEB-INFclasses -classpath %CLASSPATH%;build 
       URSMailerException.java Mailer.java MailerHome.java MailerEJB.java
javac -g -d webWEB-INFclasses 
       -classpath %CLASSPATH%;webWEB-INFclasses;build web*.java

rem Copying Web Deployment Descriptor...
copy web.xml webWEB-INF
copy weblogic.xml webWEB-INF

jar cf mailer.war -C  web .
mkdir build1 build1META-INF
move mailer.war build1

@echo Creating Enterprise Archive (EAR) file ...
copy application.xml build1META-INF
copy buildmailer.jar build1
jar cf mailer.ear -C build1 .

@echo Moving Enterprise archive file in to build directory...
move mailer.ear build1
rem "Deploying the war file"
copy build1mailer.ear  %APPLICATIONS%

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.50.156