package com.evermind.ejb;

/*
	public NewsItem create(int id) throws CreateException, RemoteException;
	public NewsItem create(Date date, String subject, String text) throws CreateException, RemoteException;

	public NewsItem findByPrimaryKey(int key) throws RemoteException, FinderException;
	public Collection findAll() throws RemoteException, FinderException;
	public Collection findByPeriod(Date start, Date end) throws RemoteException, FinderException;
*/
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 NewsItemServlet extends HttpServlet
{
	NewsItemHome home;

	public void init() throws ServletException
	{
		try
		{
			Context context = new InitialContext();		
			home = (NewsItemHome)PortableRemoteObject.narrow(context.lookup("java:comp/env/ejb/NewsItem"), NewsItemHome.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 newsItems = home.findAll();

			out.println("<html>");
			out.println("\t<head><title>My NewsItems</title></head>");
			out.println("\t<body>");
			out.println("\t\t<table border=\"2\">");
			out.println("\t\t\t<tr><td><b>Date</b></td><td><b>Locale</b></td><td><b>Subject</b></td></tr>");
		
			Iterator iterator = newsItems.iterator();
		
			while(iterator.hasNext())
			{
				NewsItem newsItem = (NewsItem)PortableRemoteObject.narrow(iterator.next(), NewsItem.class);
				out.println("\t\t\t<tr><td>" + newsItem.getDate() + "</td><td>" + newsItem.getLocale() + "</td><td>" + newsItem.getSubject() + "</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 newsItems: " + e.getMessage());
		}
		finally
		{
			out.close();
		}
	}
}
