// EmployeeServlet.java

package cmpapp;

import java.util.*;
import java.io.IOException;
import java.rmi.RemoteException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;

public class EmployeeServlet extends HttpServlet
{
  EmployeeHome home;
  
  public void init() throws ServletException
  {
    try {
      Context context = new InitialContext();		
      Object homeObject =
                 context.lookup("java:comp/env/EmployeeBean");
      home =
	(EmployeeHome) PortableRemoteObject.narrow(homeObject,
                                                   EmployeeHome.class);
    } catch(NamingException e) {
      throw new ServletException("Error looking up home", e);
    }		
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();
    
    try
    {
      Collection recs = home.findAll();

      out.println("<html>");
      out.println("\t<head><title>Employee Bean</title></head>");
      out.println("\t<body>");
      out.println("\t\t<table border=\"2\">");
      out.println("\t\t\t<tr><td>" + "<b>EmpNo</b>"
                  + "</td><td>"    + "<b>EmpName</b>"
                  + "</td><td>"    + "<b>Salary</b>"
                  + "</td></tr>");
      
      Iterator iterator = recs.iterator();
      
      while(iterator.hasNext()) {
	Employee rec =
	  (Employee) PortableRemoteObject.narrow(iterator.next(),
                                                 Employee.class);
	out.println("\t\t\t<tr><td>" + rec.getEmpNo()
		    + "</td><td>"    + rec.getEmpName()
		    + "</td><td>"    + rec.getSalary()
		    + "</td></tr>");
      }
      
      out.println("\t\t</table>");
      out.println("\t</body>");
      out.println("</html>");	
    } catch(RemoteException e) {
      out.println("Error communicating with EJB-server: " + e.getMessage());
    } catch(FinderException e) {
      out.println("Error finding records: " + e.getMessage());
    } finally {
      out.close();
    }
  }
}
