package com.evermind.ejb;

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

/**
 * A simple client for adding news.
 */
public class NewsClient
{
	public static void main(String[] args)
	{
		try
		{
			/**
			 * Create access to the naming context.
			 */
			Context context = new InitialContext();

			/**
			 * Lookup the NewsItemHome object. The reference is retrieved from the
			 * application-local context (java:comp/env). The variable is
			 * specified in the assembly descriptor (META-INF/application-client.xml).
			 */
			Object homeObject = context.lookup("java:comp/env/ejb/NewsSession");

			// Narrow the reference to a NewsItemHome.
			NewsSessionHome home = (NewsSessionHome)PortableRemoteObject.narrow(homeObject, NewsSessionHome.class);

			NewsSession session = home.create();

			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

			System.out.print("Enter the subject of the news-item you want to add: ");
			String subject = in.readLine();

			System.out.print("Enter the text for item '" + subject + "': ");
			System.out.flush();
			String text = in.readLine();

			// Add a news-item
			session.addNews(0, new Date(), subject, text);

			System.out.println("Item added");
			System.exit(0);
		}
		catch(NumberFormatException e)
		{
			System.err.println("Invalid number specified");
		}
		catch(RemoteException e)
		{
			System.err.println("System/communication error: " + e.getMessage());
		}
		catch(IOException e)
		{
			System.err.println("IO Error: " + e.getMessage());
		}
		catch(NamingException e)
		{
			System.err.println("Communication error: " + e.getMessage());
		}
		catch(CreateException e)
		{
			System.err.println("Error creating item: " + e.getMessage());
		}
		catch(FinderException e)
		{
			System.err.println("Error creating item: " + e.getMessage());
		}
	}
}
