package examples.count;

import javax.ejb.*;
import javax.naming.*;
import java.util.Properties;

/**
 * This class is a simple example of client code.
 *
 * We create 3 EJB Objects in this example, but we only allow
 * the container to have 2 in memory.  This illustrates how
 * beans are passivated to storage.
 */
public class CountClient {

	public static void main(String[] args) {

		try {
			/*
			 * Get System properties for JNDI initialization
			 */
			Properties props = System.getProperties();

			/*
			 * Get a reference to the Home Object - the
			 * factory for EJB Objects
			 */
			Context ctx = new InitialContext(props);
			CountHome home = (CountHome)
			  javax.rmi.PortableRemoteObject.narrow(
			    ctx.lookup("CountHome"), CountHome.class);

			/*
			 * An array to hold 3 Count EJB Objects
			 */
			Count count[] = new Count[3];

			int countVal = 0;

			/*
			 * Create and count() on each member of array
			 */
			System.out.println("Instantiating beans...");
			for (int i=0; i < 3; i++) {
				/*
				 * Create an EJB Object and initialize
				 * it to the current count value.
				 */
				count[i] = home.create(countVal);

				/*
				 * Add 1 and print
				 */
				countVal = count[i].count();

				System.out.println(countVal);

				/*
				 * Sleep for 1/2 second
				 */
				Thread.sleep(500);
			}

			/*
			 * Let's call count() on each EJB Object to
			 * make sure the beans were passivated and
			 * activated properly.
			 */
			System.out.println("Calling count() on beans...");
			for (int i=0; i < 3; i++) {

				/*
				 * Add 1 and print
				 */
				countVal = count[i].count();

				System.out.println(countVal);

				/*
				 * Sleep for 1/2 second
				 */
				Thread.sleep(500);
			}

			/*
			 * Done with EJB Objects, so remove them 
			 */
			for (int i=0; i < 3; i++) {
				count[i].remove();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
