package examples.ejb.extensions.finderEnumeration;

import java.rmi.RemoteException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
// import javax.rmi.PortableRemoteObject;
// FIXME mshinn@weblogic.com 2000-Mar-13 -- We need to update these javadocs
/**
 * This class demonstrates calling an entity EJBean,
 * followed by two exercises:
 * <p>
 * Part A: Deposit and attempt to withdraw more than the current
 * account balance. An application-specific exception should be thrown.
 * <p>
 * Part B: Create some new accounts, with different initial balances.
 * Find all the accounts with a balance greater than a specific value.
 * When finished, the new accounts are removed.
 * <p>
 * This class also illustrates how to lookup an EJB home in the JNDI tree. 
 * 
 * @author Copyright (c) 1998 by WebLogic, Inc. All Rights Reserved.
 * @author Copyright (c) 1998-1999 by BEA WebXpress. All Rights Reserved.
 */
 public class Client {

   private String url;
   private String user;
   private String password;
   private AccountHome home;

   public Client(String url, String user, String password) {

     this.url       = url;
     this.user      = user;
     this.password  = password;

     try {
       home = lookupHome();
     } catch(Exception e) {
       System.out.println("Unable to look up the beans home: "
         + e.getMessage());
       System.exit(1);
     }
   }
  /**
   * Runs this example from the command line. Example:
   * <p>
   * <tt>java examples.ejb.basic.beanManaged.Client "t3://localhost:7001" scott tiger</tt>
   * <p>
   * The parameters are optional, but if any are supplied,
   * they are interpreted in this order:
   * <p>
   * @param url               URL such as "t3://localhost:7001" of Server
   * @param user              User name, default null
   * @param password          User password, default null
   */
   public static void main(String[] args) {
     System.out.println("\nBeginning finderEnumeration.Client...\n");

     String url       = "t3://localhost:7001";
     String user      = null;
     String password  = null;

     // Parse the argument list 
     if ((args != null) && (args.length != 0)) {
       for (int i = 0; i < args.length; i++) {
         switch(i) {
         case 0:
           url = args[i];
           break;
         case 1:
           user = args[i];
           break;
         case 2:
           password = args[i];
           break;
         default:
         }
       }
     }
     
     Client client = new Client(url, user, password);
     client.runExamplePartA();
     client.runExamplePartB();

     System.out.println("\nEnd beanManaged.Client...\n");
   }

   /**
    * Executes Part A of this example.
    *
    * Part A: Find some accounts using a normal finder method and then call a
    * business method on each.
    */
   public void runExamplePartA() {
     System.out.println("Starting Part A of the example...\n");

     System.out.println("Finding accounts with a balance of zero...");
     Enumeration enum = null;
     try {
       enum = home.findAccountsWithBalance(0);
     } catch(Exception e) {
       System.out.println("Error finding accounts with zero balance: " +
         e.getMessage());
       System.exit(1);
     }

     System.out.println("Find complete\n");
     System.out.println("Calling business method on each bean found...");

     int count = 0;
     try {
       while(enum.hasMoreElements()) {
         Account ac = (Account) enum.nextElement();
         System.out.println("Found account with balance: " + ac.balance());
         count++;
       }
     } catch(RemoteException re) {
       System.out.println("Error fetching balance: " + re.getMessage());
       System.exit(1);
     }

     System.out.println("A total of " + count + " accounts found");
     System.out.println("End Part A of the example...\n");
   }

   /**
    * Executes Part B of this example.
    *
    * Part B: Find some accounts using a finder that uses FinderEnumeration to 
    * prime the EJB cache with its results and call a business method on each
    * bean.
    */
   public void runExamplePartB() {
     System.out.println("Starting Part B of the example...\n");

     System.out.println("Finding accounts with a balance of one...");
     Enumeration enum = null;
     try {
       enum = home.findAndLoadAccountsWithBalance(1);
     } catch(Exception e) {
       System.out.println("Error finding accounts with balance of one: " +
         e.getMessage());
       System.exit(1);
     }

     System.out.println("Find complete\n");
     System.out.println("Calling business method on each bean found...");

     int count = 0;
     try {
       while(enum.hasMoreElements()) {
         Account ac = (Account) enum.nextElement();
         System.out.println("Found account with balance: " + ac.balance());
         count++;
       }
     } catch(RemoteException re) {
       System.out.println("Error fetching balance: " + re.getMessage());
       System.exit(1);
     }

     System.out.println("A total of " + count + " accounts found");
     System.out.println("End Part B of the example...\n");
   }

   private AccountHome lookupHome()
     throws NamingException, ClassNotFoundException
   {
     // Lookup the beans home using JNDI
      Context ctx = getInitialContext();
      AccountHome home = (AccountHome) ctx.lookup("finderEnumeration.AccountHome");
      return home;
   }

  private Context getInitialContext() throws NamingException {
    // Get an InitialContext
    Hashtable h = new Hashtable();
    h.put(Context.INITIAL_CONTEXT_FACTORY,
        "weblogic.jndi.WLInitialContextFactory");
    h.put(Context.PROVIDER_URL, url);
    if (user != null) {
      System.out.println ("user: " + user);
      h.put(Context.SECURITY_PRINCIPAL, user);
      if (password == null) 
      password = "";
      h.put(Context.SECURITY_CREDENTIALS, password);
    } 
    return new InitialContext(h);
  }

}








