client.java

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

JAVA
399
字号
//定义本类在包examples.ejb20.relationships.many2many中
package examples.ejb20.relationships.many2many;
//本类用到的其他类
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import java.util.Iterator;
//本类用到的EJB类
import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;
//本类用到的名称服务类
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

/**
 * 这个类演示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.many2many.Client "t3://localhost:7001" 10020
   * 
   * @参数 url               URL 如: "t3://localhost:7001" 
   */
  public static void main(String[] args) {
    System.out.println("\nBeginning examples.ejb20.relationships.many2many.Client...\n");

    String url       = "t3://localhost:7001";
 
    if (args.length == 1) {
      url = args[0];
    } else if (args.length > 1) {
    	//打印用法提示
      System.out.println("用法: examples.ejb20.relationships.many2many.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.many2many.Client...\n");
  }


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

    // 创建有不同结算值的账号和一些null类型的账号
    log("\nCreate Accounts and customers:");
    for (int i=0; i<numBeans; i++) {
      // if (Math.IEEEremainder(i, 2) == 0)
      if (i % 2 == 0) {
        // 创建一些null类型的账号
        accounts [i] = findOrCreateAccount("ID: "+i, i * 1000, null);
      } else {
        accounts [i] = findOrCreateAccount("ID: "+i, i * 1000, "Savings");
      }

      try {
      	//创建客户
	customers[i] = createCustomer("customer_"+i);
      } catch(DuplicateKeyException dke) {
      	//异常处理
        log("A customer with name customer_" + i + " already exists!");
      } catch(Exception e) {
      	//异常处理
        log("Error creating account: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
      }
    }

    log("\nEstablish relationships:");
    //建立关系
    for (int i=0; i<numBeans; i++) {
      for (int x=0; x<numBeans; x++) {
        try {
          // 把所有账号加到customer_0
          log("Add account "+ accounts[i].getAccountId() + " to " + 
            customers[x].getName());
          customers[x].addAccount(accounts[i]);
          // 把所有客户加到账号ID 0
          log("Add customer "+ customers[i].getName() + " to " +
            accounts[x].getAccountId());
          accounts[x].addCustomer(customers[i]);
        } catch(Exception e) {
          log("Error setting account: " + e.getMessage());
          e.printStackTrace();
          System.exit(1);
        }
      }
    }

    log("\nPrint Customers:");
    // 打印所有客户
    for (int i=0; i<numBeans; i++) {
      log("Customer: " + customers[i].getName() + " has accounts:");
       Iterator iter = customers[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 " + accounts[i].getAccountId() + " has customers:");
       Iterator iter = accounts[i].getAllCustomers().iterator();
       while (iter.hasNext()) {
         Customer cust = (Customer)iter.next();
         log("\t" + cust.getPrimaryKey());
       }
    }

    // 找到所有结算> 2000的账号
    findBigAccounts(2000.0);
    // 找到第一个结算为0的账号
    findAccountWithZeroBalance();
    // 找到所有类型为null的账号
    findNullAccounts();

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

  /**
   * 找到第一个结算为0的账号
   */
  private void findAccountWithZeroBalance() 
    throws FinderException, RemoteException
  {
    log("\nQuerying for an account with zero balance...");
    try {
    //调用finder方法,找到远程对象	
      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");
    //调用finder方法
    Collection col = accountHome.findNullAccounts();

    Iterator it = col.iterator();
    if(! it.hasNext()) {
      log("No accounts were found with a null account type");
    }
    //所有找到的账号
    while (it.hasNext()) {
      Account nullAccount= (Account)it.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 + "...");
    //调用finder方法
    Collection col = accountHome.findBigAccounts(balanceGreaterThan);
    Iterator it = col.iterator();

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

    while (it.hasNext()) {
      Account bigAccount= (Account)it.next();

      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) {
    // 账号不存在,创建它
      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) 
    throws CreateException, RemoteException 
  {
    log ("Creating customer " + name + "...");
   //调用主接口方法,创建远程对象
    Customer cust = (Customer) PortableRemoteObject.narrow(
      customerHome.create(name), Customer.class);

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

   return cust;
  }

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

    try {
    	//创建主接口对象
      Object home = (AccountHome) ctx.lookup("many2many.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 " + 
      "many2many.AccountHome on the WebLogic server at "+url);

      throw ne;
    }
  }

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

    try {
    	//创建主接口对象
      Object home = (CustomerHome) ctx.lookup("many2many.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 " + 
      "many2many.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 {
      // 属性对象
      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 + -
显示快捷键?