client.java

来自「weblogic应用全实例」· Java 代码 · 共 418 行

JAVA
418
字号
//定义本接口在包examples.ejb20.relationships.one2many中
package examples.ejb20.relationships.one2many;

import java.rmi.RemoteException;
import java.sql.Date;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Properties;

import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;
import javax.ejb.EJBObject;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.transaction.UserTransaction;;

/**
 * 这个类演示CMP和EJB-QL包括如下操作:
 * 用不同的初值和类型创建5个独立的账号和用户;
 * 在不同的beens间建立关系;
 * 打印关系;
 * 找到所有结算大于给定值账号;
 * 找到结算为0的账号;
 * 找到类型是null的账号。
 * 
 * 最后,清除所有新创建的账号。
 */
public class Client {
  //声明服务器url
  private String url;
  //声明主接口
  private AccountHome accountHome;
  private CustomerHome customerHome;
  
  //构造方法
  public Client(String url) 
    throws NamingException {

    this.url       = url;
    //查找主接口
    accountHome = lookupAccountHome();
    customerHome = lookupCustomerHome();
  }

  /**
   * 从命令行运行这个程序,如:
   * 
   * java examples.ejb20.relationships.one2many.Client "t3://localhost:7001" 10020
   * 
   * @参数 url               URL 如: "t3://localhost:7001" 
   */
  public static void main(String[] args) {
    System.out.println("\nBeginning examples.ejb20.relationships.one2many.Client...\n");

    String url       = "t3://localhost:7001";
    
    if (args.length == 1) {
      url = args[0];
    } else if (args.length > 1) {
    	//打印用法提示
      System.out.println("Usage: examples.ejb20.relationships.one2many.Client WebLogicURL");
      return;
    }

    Client client = null;

    try {
    	//本类实例化
      client = new Client(url);
    } catch (NamingException ne) {
      log("Unable to look up the beans home: " + ne.getMessage());
      System.exit(1);
    }

    try {
    	//运行例程
      client.runExample();
    } catch (Exception e) {
    	//异常处理
      log("There was an exception while creating and using the Accounts.");
      log("This indicates that there was a problem communicating with " +
          "the server: "+e);
    }

    System.out.println("\nEnd examples.ejb20.relationships.one2many.Client...\n");
  }


   /**
   * 创建5个新的不同结算值和类型账号和客户,
   * 找到所有结算值大于给定值的账号,
   * 结束时,删除新的账号。
   */
  public void runExample() 
     throws CreateException, RemoteException, FinderException,
            RemoveException
  {
    int numBeans = 5;
		//账号和客户数组
    Account [] ac = new Account [numBeans];
    Customer [] cust = new Customer [numBeans];
    String id = "";
    String z = "";

    // 创建有不同结算值的账号和一些null类型的账号
    log("\nCreate Accounts and customers:");			
    for (int i=0; i<numBeans; i++) {
       // if (Math.IEEEremainder(i, 2) == 0)
       if (i % 2 == 0) {	
       id = "account" + i;
          // 创建一些null类型的账号
          ac [i] = createAccount("ID: "+i, i * 1000, null);
        } else {
          ac [i] = createAccount("ID: "+i, i * 1000, "Savings");
        }					
	
        try {
          z = "customer" + i;
          java.sql.Date lastDate =
                   new Date(System.currentTimeMillis());
          cust [i] = createCustomer(z, i, new Integer(i), lastDate);
        } catch(DuplicateKeyException dke) {
	  log("A customer with name " + id + " already exists!");
	  throw dke;
	} catch(Exception e) {
	  log("Error creating account: " + e.getMessage());
	  e.printStackTrace();
	}
     }
     log("\nCreated Five Customers and Five Accounts");
   
     log("\nEstablish One-to-Many Relationships between Customer and Accounts:");
     int x =0;
     //建立关系
      for (int i=0; i<numBeans; i++) {
        try {
           // 把所有账号加到customer_0
          log("Add account "+ ac[i].getAccountId() + " to " + 
            cust[x].getName());
          cust[x].addAccount(ac[i]);
           // 把客户加到账号ID 0-4
          log("Add customer "+ cust[x].getName() + " to account " +
            ac[i].getAccountId());
            ac[i].addCustomer(cust[x]);
        } catch(Exception e) {
          log("Error setting account: " + e.getMessage());
          e.printStackTrace();
          System.exit(1);
        }
      }
        // 打印客户
     log("\nPrint Customers:");
     // print out the customers
      for (int i=0; i<numBeans; i++) {
        log("Customer: " + cust[i].getName() + " has accounts:");
        Iterator iter = cust[i].getAllAccounts().iterator();
         while (iter.hasNext()) {
           Account acct = (Account)iter.next();
           log("\t" + acct.getPrimaryKey() + " with balance " +
           acct.balance());
        }
      }
         
   // 打印所有账号
     log("\nPrint Accounts:");
        for (int i=0; i<numBeans; i++) {
        log("Account " + ac[i].getAccountId() + " has customers:");       
        log("\t" + ac[i].getCustomer().getPrimaryKey());
      }


    try {
      Context ctx = getInitialContext();
      UserTransaction tx = (UserTransaction)
		ctx.lookup("javax.transaction.UserTransaction");
      tx.begin();
			 
      Collection col = customerHome.findByName("a", "l");
      log("\nFind By Name");
      Iterator iter = col.iterator();
      while (iter.hasNext()) {
	      Customer customer = (Customer)iter.next();
	      log("found- " + customer.getName());
      }

      col = customerHome.findByImportance(0);
      log("\nFind By Importance");
      iter = col.iterator();
      while (iter.hasNext()) {
	      Customer customer = (Customer)iter.next();
	      log("found- " + customer.getName());
      }
			 
      tx.commit();
			 
    } catch(Exception e) {
      log("Error setting account: " + e.getMessage());
      e.printStackTrace();
    }
    
    // 找到所有结算> 2000的账号
    findBigAccounts(2000.0);
    // 找到第一个结算为0的账号
    findAccountWithZeroBalance();
    // 找到所有类型为null的账号
    findNullAccounts();

    // 删除新的账号	
    log("Removing beans...");
    for (int i=0; i<numBeans; i++) {
         ac[i].remove();
         cust[i].remove();
    }
  }
  

   /**
   * 找到第一个结算为0的账号
   */
  private void findAccountWithZeroBalance() 
    throws FinderException, RemoteException
  {
    log("\nQuerying for an account with zero balance...");
    try {
      Account zeroBalance = (Account)PortableRemoteObject.narrow(accountHome.findAccount(0), Account.class);
      
      // Account zeroBalance = home.findAccount(0);
      log("Account " + zeroBalance.getPrimaryKey() + "; balance is zero");
    } catch(ObjectNotFoundException onfe) {
      log("No Account was found with a balance of zero");
    }
  }

   /**
   * 列出所有null类型的账号
   */
  private void findNullAccounts()
    throws RemoteException, FinderException
  {
    log("\nQuerying for accounts with a null account type");
    Collection col = accountHome.findNullAccounts();

    Iterator iter = col.iterator();
    if(! iter.hasNext()) {
      log("No accounts were found with a null account type");
    }

    while (iter.hasNext()) {
      Account nullAccount= (Account) iter.next();
      log("Account " + nullAccount.getPrimaryKey() + "; account type is " + nullAccount.accountType());
    }
  }

   /**
    * 列出所有结算大于给定值的账号
    * This finder illustrates a Finder Method that returns an Enumeration.
    */
  private void findBigAccounts(double balanceGreaterThan) 
    throws RemoteException, FinderException
  {
    log("\nQuerying for accounts with a balance greater than " +
      balanceGreaterThan + "...");

    Iterator iter = accountHome.findBigAccounts(balanceGreaterThan).iterator();

    if(! iter.hasNext()) {
      log("No accounts were found!");
    }

    while (iter.hasNext()) {
      Account bigAccount= (Account) 
	PortableRemoteObject.narrow(iter.next(), Account.class);

      log("Account " + bigAccount.getPrimaryKey() + 
        "; balance is $" + bigAccount.balance());
    }
  }


  /**
   * 如果这个id已存在,则返回它,否则创建新的。
   */
  private Account findOrCreateAccount(String id, double balance, String accountType)
    throws CreateException, FinderException, RemoteException
  {
    Account remote = null;
    try {
      remote = (Account) PortableRemoteObject.narrow(accountHome.findByPrimaryKey(id), Account.class);
      // remote = home.findByPrimaryKey(id);
    } catch (ObjectNotFoundException onfe) {
      // the account id does not yet exist so create it.
      remote = createAccount(id, balance, accountType);
    }
    return remote;
  }


 /**
   * 创建给定id和结算值的新账号
   */
  private Account createAccount(String id, double balance, String accountType) 
    throws CreateException, RemoteException 
  {
    log ("Creating account " + id + " with a balance of " + 
      balance + " account type " + accountType + "...");

    Account ac = (Account) PortableRemoteObject.narrow(
      accountHome.create(id, balance, accountType),
      Account.class);

   log("Account " + id + " successfully created");

   return ac;
  }

  /**
   * 创建给定名字的新客户
   */
  private Customer createCustomer(String name, int age, Integer level, Date last) 
    throws CreateException, RemoteException 
  {
    log ("Creating customer " + name + "...");

    Customer cust = (Customer) PortableRemoteObject.narrow(
      customerHome.create(name, age, level, last), Customer.class);

   log("Customer " + name + " successfully created");

   return cust;
  }

 /**
   * 使用JNDI查找主接口
   */
  private AccountHome lookupAccountHome()
    throws NamingException
  {
    Context ctx = getInitialContext();

    try {
      Object home = (AccountHome) ctx.lookup("one2many.AccountHome");
      return (AccountHome) PortableRemoteObject.narrow(home, AccountHome.class);

    } catch (NamingException ne) {
      log("The client was unable to lookup the EJBHome.  Please make sure " +
      "that you have deployed the ejb with the JNDI name " + 
      "beanManaged.AccountHome on the WebLogic server at "+url);

      throw ne;
    }
  }

  /**
   * 使用JNDI查找主接口
   */
  private CustomerHome lookupCustomerHome()
    throws NamingException
  {
    Context ctx = getInitialContext();

    try {
      Object home = (CustomerHome) ctx.lookup("one2many.CustomerHome");
      return (CustomerHome) PortableRemoteObject.narrow(home, CustomerHome.class);

    } catch (NamingException ne) {
      log("The client was unable to lookup the EJBHome.  Please make sure " +
      "that you have deployed the ejb with the JNDI name " + 
      "CustomerEJB.CustomerHome on the WebLogic server at "+url);

      throw ne;
    }
  }

  /**
   * 获取初始化上下文
   *
   * Java2 可以使用jndi.properties文件,设置
   * INITIAL_CONTEXT_FACTORY和PROVIDER_URL属性
   *  private Context getInitialContext() throws NamingException {
   *    return new InitialContext();
   *  }
   */
  private Context getInitialContext() throws NamingException {

    try {
      // Get an InitialContext
      Properties h = new Properties();
      h.put(Context.INITIAL_CONTEXT_FACTORY,
          "weblogic.jndi.WLInitialContextFactory");
      h.put(Context.PROVIDER_URL, url);
      return new InitialContext(h);
    } catch (NamingException ne) {
      log("We were unable to get a connection to the WebLogic server at "+url);
      log("Please make sure that the server is running.");
      throw ne;
    }
  }
//日志
  private static void log(String s) {
    System.out.println(s);
  }

}







⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?