HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

The story so far: In Part 1 (JDJ Vol. 6, issue 4), I covered servlets and gave a practical demonstration of how a basic access control mechanism for intranet applications could be built using Servlet Session Tracking and HTTP Authentication. In Part 2 (Vol. 6, issue 5), I introduced a couple of applets into the architecture and showed how a communication channel could be established between the applets and servlets that comprised the application.

The next version of my application will include the ability for an engineer to transfer tasks to another engineer when he goes on vacation or when he's sick. This added functionality requires a servlet to present the transfer form and subsequently to process the form submission. An Enterprise JavaBean (session) will perform the actual transfer function.

Figure 1
Figure  1:

Task Transfer Servlet
Figure 1 shows what the Task Transfer Form looks like. You can type the name of a recipient engineer and submit the form to initiate the transfer. If the transfer succeeds, the user is presented with a confirmation page (not shown).

I will be using a single servlet to support two functions: presenting the transfer form, and handling the form submission. One servlet, two uses, distinguished by invoking the servlet through its doGet() or doPost() method.

The initial form presentation is performed by the doGet() method of the new servlet, which I've called TransferServlet. Listing 1 provides the code for this method, and for clarity I've delegated the construction of the HTML form to a separate displayForm() function to facilitate the representation of the form in the case of user error. The first time around, the form is displayed with a null error message via the call displayForm(out.user,null).

When the user submits the form, the submission is handled by the same servlet's doPost() method given in Listing 2. This method first gets hold of the engineer to which the transfer should be targeted. If no engineer was specified, it redisplays the form with an error message - displayForm(out,user, "You must specify an engineer") - otherwise the transfer goes ahead courtesy of an Enterprise JavaBean.

Simple EJB Solution
I've created the simplest possible Enterprise JavaBean to perform the transfer of tasks from one engineer to another. The TaskManager EJB is referenced by name via JNDI, and its home interface is obtained. The home interface is used to create an instance of the bean, and this instance is instructed to transfer the tasks. I said that this is the simplest possible EJB, and it is: the remote interface has only one method - transferTasks(...).

The EJB implementation in Listing 3 is a minimal session bean with no transactional attributes, and a single method with a single JDBC statement to manipulate the usertasks database table. I've kept it simple not only for illustration, but also because it's often the best approach. The sole SQL statement succeeds and is committed - or it fails and is rolled back. Either way, transactional integrity is assured.

When presented like this, EJBs look easy, so to spice things up I'll suggest another way of achieving exactly the same functionality.

The Alternative EJB Solution
This time, I'll use an entity bean to represent each individual engineer and I'll rework the TaskManager session bean to coordinate the two entity beans that represent the two engineers. The remote interface for an engineer (entity) bean has the method definitions shown in Listing 4. For any given engineer you can count his tasks, get his tasks, delete them, and assign new ones.

In case you're wondering, the sometimesFail parameter on the assignTasks() method was my way of testing this. If set to true, this parameter causes the method to throw an exception once in a while, which triggers the entire transfer operation to be rolled back.

The TaskManager session bean now has a revised version of the transferTasks method, given in Listing 5. It looks up the two entity beans representing the from- and to- Engineer(s), gets the tasks of the fromEngineer, deletes them, and then adds them one-by-one to the toEngineer.

Adopting this approach introduces many points at which the transactional integrity might be compromised. The deleteTasks call - or any one of the assignTask calls - might fail, leaving the database in an inconsistent state. Rest assured that you could make it work by setting the transactional properties of the participating session and entity beans, in which case the EJB container will call the ejbLoad and ejbStore methods (assuming bean-managed persistence) on the entity beans at appropriate times to assure the transactional integrity.

This leaves us with (at least) two ways to implement the transferring of tasks between engineers using Enterprise JavaBeans; one way being considerably easier to implement - and more reliable - and the other showing the power and complexity of EJBs. In general, my suggestion would be: beware the consultant who dives straight into the second approach without considering the simpler solution, although, of course, there are times when only a complex solution will do.

Table 1

Fitting the Pieces into the Puzzle
Having presented the three major architectures offered by the J2EE (the servlet, applet, and EJB) in a way that hopefully shows that these three approaches may be complementary rather than competitive, you might now have some good ideas about the direction in which to take your project. But you might still be a little unsure about the answer to the essential question: Which horse for which course?

I can only give an opinion, but the order in which I have covered these technologies is no accident. For any Internet/intranet application, I would, by default, assume the servlet-only approach initially as providing the thinnest possible clients and the lowest common denominator for compatibility with client Web browsers.

For very limited client-side validation and control, I might stick with the HTML/servlet approach, add some JavaScript, and stop there. In all other situations that necessitated highly interactive or graphical clients, I would use applets with the straightforward applet-servlet communication mechanism based on serialized objects.

In situations that demand true, stateful, remotely referenced server-side objects I would consider Enterprise JavaBeans. I would try to keep my EJBs as simple as possible, and that's where the irony is. The real benefits of the EJB model come through using the standard services for transactions, security, and so on. So if you're not going to use these services - in the name of keeping it simple - you might be better off sticking with simple RMI. In a nutshell, don't treat EJBs as a half-hearted solution; either find an easier method or commit to the EJB approach with all your heart.

I've not yet mentioned CORBA as a candidate for client/server communication or even as an alternative to EJBs. In the time that it took RMI to mature and EJB to take off, CORBA - in the form of the Visigenic (Visibroker) or Iona (Orbix) Java ORB implementations - provided a solution that was more comprehensive than RMI and ahead of EJB. Now that niche has been filled by pure Java technologies and I see CORBA as being limited to the one remaining niche for which it is uniquely suited - legacy integration.

The Three Approaches
I've taken a tour of the three major architecture styles for application development that are available to Enterprise Java developers - namely servlets, applets, and EJB - and I've presented my ideas on how applications may be built comprising all three approaches, with some interesting diversions into areas such as access control. I've fitted the big pieces into the puzzle by offering my advice on which pieces should be inserted first and which later, if at all.

I'll leave you with one final thought. There are a few smaller pieces such as XML and JSP that could be placed into the gaps between the big ones to complete the final puzzle, as shown in Figure 2.

Figure 2
Figure  2:

Author Bio
Tony Loton works through his company - LOTONtec Limited (www.lotontech.com) - as an independent consultant, course instructor, and technical author. He's spent the past 10 years in IT, the last five devoted almost exclusively to Java, UML, and related technologies. He holds a degree in computer science and management. [email protected]

	


Listing 1:  TransferServlet "doGet" Method

public void doGet(HttpServletRequest req
, HttpServletResponse res) throws IOException
{
 // -- get the current http session --
 HttpSession session=req.getSession(true);


 String user=(String)
  session.getAttribute("user");


 if (user==null)
  { /* -- write error message -- */ }
 else
 {
  // -- display the transfer form
  res.setContentType("text/html");
  PrintWriter out = res.getWriter();


  displayForm(out,user,null);
 }
}



Listing 2: TransferServlet "doPost" Method

public void doPost(HttpServletRequest req
 , HttpServletResponse res) throws IOException
{
 // -- get the current http session --
 HttpSession session=req.getSession(true);
 String user=(String) session.getAttribute("user");


 if (user==null)
  { /* -- write error message -- */ }
 else
 {
  // -- handle the transfer form submission --


  res.setContentType("text/html");
  PrintWriter out = res.getWriter();


  String toEngineer=
   req.getParameter("toEngineer");


  if (toEngineer==null)
  {
   displayForm(out,user
    ,"You must specify an engineer");
  }
  else
  {
   out.println("");


   out.println("TransferServlet
    ");


   try
   {
    Context initial = new InitialContext();


    TaskManagerHome taskManagerHome =
     (TaskManagerHome) PortableRemoteObject
     .narrow(initial.lookup("TaskManager")
     ,TaskManagerHome.class);


    TaskManager taskManager=
     taskManagerHome.create();


    taskManager.transferTasks(user,toEngineer);


    out.println("Transfer to "+toEngineer
     +" succeeded. ");
   }
   catch (TransferException ex1)
   {
    out.println("Transfer to "+toEngineer
     +" failed with an application error. ");
   }
   catch (Exception ex2)
   {
    out.println("Transfer to "+toEngineer
     +" failed with a system error. ");
   }


   out.println("");
   out.println("");
  }
 }
}



Listing 3: TaskManager Implementation

public class TaskManagerEJB
 implements SessionBean
{
 public void ejbCreate() throws CreateException
  {}


 public void transferTasks(String fromEngineer
  , String toEngineer) throws TransferException
 {
  try
  {
   InitialContext ic = new InitialContext();


   DataSource ds = (DataSource)
    ic.lookup("java:comp/env/jdbc/LOTONtech");


   Connection con = ds.getConnection();
   Statement st=con.createStatement();


   st.executeQuery(
   "UPDATE usertasks SET username='"+toEngineer
   +"' WHERE username='"+fromEngineer+"'");


  }
  catch (Exception e) { /* handle the error */ }
 }


 public TaskManagerEJB() {}
 public void ejbRemove() {}
 public void ejbActivate() {}
 public void ejbPassivate() {}
 public void setSessionContext(SessionContext sc) {}
}


 Listing 4: Engineer Entity Bean
 
public interface Engineer extends javax.ejb.EJBObject
{
 public int getTaskCount() throws java.rmi.RemoteException;
 public String[] getTasks() throws java.rmi.RemoteException;
 public void deleteTasks() throws java.rmi.RemoteException;
 public void assignTask(String task, boolean sometimesFail)
  throws java.rmi.RemoteException;
 public String getKey() throws java.rmi.RemoteException;
}


 Listing 5: transferTasks Method with Entity Beans

public void transferTasks
 (String fromEngineerID, String toEngineerID)
 throws java.rmi.RemoteException
{
 try
 {
  EngineerHome engineerHome= (IEngineerHome)
  ctx.lookup( "EngineerHome" );


  Engineer fromEngineer=engineerHome
   .findByPrimaryKey(fromEngineerID);


  Engineer toEngineer=engineerHome
   .findByPrimaryKey(toEngineerID);


  String[] tasks=fromEngineer
   .getTasks();


  fromEngineer.deleteTasks();


  for (int i=0; i<tasks.length; i++)
  {
   // Sometimes fail this, to roll back the transaction
   toEngineer.assignTask(tasks[i], true);
  }
 }
 catch (Exception e)
 {
  System.out.println("TaskManager Exception: "+e);
 }
}


All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.