<%

/*
 * list.jsp
 *
 * Lists all the entries in the address book. This JSP is the only JSP that
 * will actually connect to the entity bean. On success, it will save a
 * reference to the entity bean in the session. So there will be one reference
 * to the bean per session.
 *
 * Version: $Revision: 1.1 $ $Date: 2001/11/10 00:22:17 $
 * Authors: Ernst de Haan (ernst@jollem.com)
 */
%>
<%@ page import="addressbook.ejb.*,java.io.*,java.net.*,java.util.*,javax.naming.*,javax.rmi.*" %>
<%

// Make sure this page will not be cached by the browser
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-Control", "no-store");

// We will send error messages to System.err, for verbosity. In a real
// application you will probably not want this.
PrintStream errorStream = System.err;

// If we find any fatal error, we will store it in the "error" variable. If
// an exception is caught that corresponds with this error message, then we
// will store it in the "exception" variable.
String error        = null;
Exception exception = null;

// First check if the reference to the EJB is already stored in the session.
AddressBook addressBook = (AddressBook) session.getAttribute("AddressBook");

// If not, then attempt to get the initial JNDI context.
if (addressBook == null) {

   // When attempting to connect to JNDI, we store the reference to the
// initial JNDI context in this variable. We will use it to lookup the
// entity bean.
Context context = null;

   try {
      context = new InitialContext();
   } catch (Exception e) {
      exception = e;
      error = "Caught \"" + exception.getClass().getName() + "\" while " +
              "attempting to create the initial JNDI context.";
      errorStream.println(error);
      exception.printStackTrace(errorStream);
   }

   // We have specified "ejb/Addressbook" in the web.xml file as the name by
// which we would like to contact the AddressBook home interface. We will
// have to prepend "java:comp/env/", the root `directory' for enterprise
// beans.
final String location = "java:comp/env/ejb/AddressBook";
   if (error == null) {
      try {
         // Attempt to lookup an object at the specified location in the JNDI
// context.
Object boundObject = context.lookup(location);

         // Try to convert it to an instance of AddressBook, the home
// interface for our bean.
addressBook = (AddressBook) PortableRemoteObject.narrow(boundObject,
                                                           AddressBook.class);

         // If we got this far, we've done it, let's save the reference to the
// AddressBook home interface in the session for future use by both
// this page and the other JSP pages.
session.setAttribute("AddressBook", addressBook);

      } catch (Exception e) {
         exception = e;
         error = "Caught \"" + exception.getClass().getName() + "\" while " +
                 "attempting to lookup the AddressBook bean at \"" +
                 location + "\".";
         errorStream.println(error);
         exception.printStackTrace(errorStream);
      }
   }
}

// This is the variable we will store the set of all address entries in. We
// convert this set from an instance of java.util.Collection to an Object
// array for easy iteration.
Object[] entries = null;
int entryCount = 0;

// The method that converts a Collection to an Object array needs a reference
// to the target return type. This is why we need an instance of an
// AddressEntry array.
final AddressEntry[] emptyAddressEntryArray = new AddressEntry[] {};

if (error == null) {
   try {
      // Find all the address entries
Collection entryCollection = addressBook.findAll();

      entries = entryCollection.toArray(emptyAddressEntryArray);
      if (entries == null) {
         entryCount = 0;
      } else {
         entryCount = entries.length;
      }
   } catch (Exception e) {
      exception = e;
      error = "Caught \"" + exception.getClass().getName() + "\" while " +
              "attempting to find all AddressBook entries.";
      errorStream.println(error);
      exception.printStackTrace(errorStream);
   }
}

// Decide what the title will be.
String title;
if (error != null) {
   title = "Error";
} else {
   title = "Addressbook | List of entries";
}
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>
<TITLE><%= title %></TITLE>
</HEAD>
<BODY bgcolor="#FFFFFF">
<H1><%= title %></H1>

<%
// Display the error message, if any.
if (error != null) {
%>

<P><BLOCKQUOTE><%= error %></BLOCKQUOTE>

<%
// Display the exception message, if any.
if (exception != null) {
%>

<P><BLOCKQUOTE><CODE><%= exception %></CODE></BLOCKQUOTE>

<%
} /* if */

} else {

      // If there are no entries to be displayed, display a descriptive text.
if (entryCount == 0) {
%>

<P><BLOCKQUOTE>No entries found.</BLOCKQUOTE>

<%
// Otherwise display a table with all names, addresses and cities, and
// display two extra choices: "Edit" and "Delete".
} else {
%>

<P><TABLE border="1" width="100%">
<TR>
<TD><STRONG>Name</STRONG></TD>
<TD><STRONG>Address</STRONG></TD>
<TD><STRONG>City</STRONG></TD>
<TD><STRONG>Actions</STRONG></TD>
</TR>

<%
for (int i=0; i<entryCount; i++) {
            AddressEntry entry = (AddressEntry) entries[i];
            String name        = entry.getName();
            String address     = entry.getAddress();
            String city        = entry.getCity();

            String encodedName = URLEncoder.encode(name);

            String editURL   = "edit.jsp?name=" + encodedName;
            String deleteURL = "delete.jsp?name=" + encodedName;
%>

<TR>
<TD><%= name %></TD>
<TD><%= address %></TD>
<TD><%= city %></TD>
<TD><A href="<%= editURL %>">Edit</A>&nbsp;<A href="<%= deleteURL %>">Delete</A></TD>
</TR>

<%
} /* for */
%>

</TABLE>

<%
} /* else */
} /* else */

// Finally display a link to the page that allows the user to add an entry
// to the address book.
%>

<P><TABLE border="1">
<TR><TD><A href="add.jsp">Add entry</A></TD></TR>
</TABLE>
</BODY>
</HTML>