package ejava.examples.checkouts.demo;

import ejava.examples.checkouts.demo.Thread1RemoteHome;
import ejava.examples.checkouts.demo.Thread1Remote;

import javax.ejb.EJBHome;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import java.util.Hashtable;

public class Client {
   static final String url_ = "t3://localhost:7001";
   static final String thread1Ctx_ = "library.demo.Thread1RemoteHome";

   public void execute() throws Exception {
      Thread1RemoteHome home = (Thread1RemoteHome) getHome(thread1Ctx_);
      Thread1Remote thread1 = home.create();
      System.out.println(thread1.execute());
   }

   public void status() throws Exception {
      Thread1RemoteHome home = (Thread1RemoteHome) getHome(thread1Ctx_);
      Thread1Remote thread1 = home.create();
      System.out.println(thread1.status());
   }

   public void cleanup() throws Exception {
      Thread1RemoteHome home = (Thread1RemoteHome) getHome(thread1Ctx_);
      Thread1Remote thread1 = home.create();
      thread1.cleanup();
   }

   public EJBHome getHome(String name) throws Exception {
      EJBHome home = (EJBHome)PortableRemoteObject.narrow(
         getInitialContext().lookup(name), EJBHome.class);
      return home;
   }

   public Context getInitialContext() throws NamingException {
      Hashtable props = new Hashtable(2);
      props.put(Context.INITIAL_CONTEXT_FACTORY,
                "weblogic.jndi.WLInitialContextFactory");
      props.put(Context.PROVIDER_URL, url_);
      return new InitialContext(props);
   }

   public static void main(String args[]) throws Exception {
      if (args.length == 1 && args[0].equals("-c")) {
         new Client().cleanup();
      }
      else if (args.length == 1 && args[0].equals("-e")) {
         new Client().execute();
      }
      else {
         new Client().status();
      }
   }
}
