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 ProductServlet extends HttpServlet
{
	ProductHome home;

	public void init() throws ServletException
	{
		try
		{
			Context context = new InitialContext();		
			home = (ProductHome)PortableRemoteObject.narrow(context.lookup("MyProduct"), ProductHome.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 products = home.findAll();

			out.println("<html>");
			out.println("\t<head><title>My products</title></head>");
			out.println("\t<body>");
			out.println("\t\t<table border=\"2\">");
			out.println("\t\t\t<tr><td><b>Name</b></td><td><b>Price</b></td></tr>");
		
			Iterator iterator = products.iterator();
		
			while(iterator.hasNext())
			{
				Product product = (Product)PortableRemoteObject.narrow(iterator.next(), Product.class);
				out.println("\t\t\t<tr><td>" + product.getName() + "</td><td>" + product.getPrice() + "</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 products: " + e.getMessage());
		}
		finally
		{
			out.close();
		}
	}
}
