⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tellerbean.java

📁 weblogic应用全实例
💻 JAVA
字号:
//定义本类在包examples.cluster.ejb.teller 中
package examples.cluster.ejb.teller;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.*;
import javax.ejb.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;
import java.sql.*;

import weblogic.common.*;
import weblogic.management.Admin;

import examples.cluster.ejb.account.*;

/**
 * TellerBean是一个无状态会话Bean
 */
public class TellerBean implements SessionBean {
  static final boolean VERBOSE  = true;
  static final int     SLEEP    = 3000; //time to sleep to give an 
                                        //opportunity to test failover

  // -----------------------------------------------------------------
  // 私有variables
  //会话上下文  
  private SessionContext ctx;
  //上下文
  private Context rootCtx;
  //服务器名
  private transient String         serverName;
  //主接口
  private transient AccountHome    bank;
  //表大小
  private transient int            maxLogTableSize;
  private transient String         logPoolName;

  // -----------------------------------------------------------------
  // SessionBean 实现

  /**
   * EJB规范定义的方法,这里没用到
   */
  public void ejbActivate() {
    if (VERBOSE)
      System.out.println("teller.ejbActivate called");
  }

  /**
   * EJB规范定义的方法,这里没用到
   */
  public void ejbRemove() {
    if (VERBOSE)
      System.out.println("teller.ejbRemove called");
  }

  /**
   * EJB规范定义的方法,这里没用到
   */
  public void ejbPassivate() {
    if (VERBOSE)
      System.out.println("teller.ejbPassivate called");
  }

  /**
   * 设置会话上下文
   *
   * @参数 ctx               SessionContext
   */
  public void setSessionContext(SessionContext ctx) {
    if (VERBOSE)
      System.out.println("teller.setSessionContext called");
    this.ctx        = ctx;
    serverName      = getServerName();
  }

  // 公共接口

  /**
   * ejbCreate方法
   */
  public void ejbCreate() throws CreateException {
    if (VERBOSE)
      System.out.println("teller.ejbCreate called");
    try {
	Properties p = new Properties();
	p.put(Context.INITIAL_CONTEXT_FACTORY,
	      "weblogic.jndi.WLInitialContextFactory");
	InitialContext ic = new InitialContext(p);
	rootCtx = (Context) ic.lookup("java:comp/env");
	maxLogTableSize = ((Integer) rootCtx.lookup("maxLogTableSize")).intValue();
	logPoolName = (String) rootCtx.lookup("logPoolName");
    } catch (NamingException ne) {
	throw new CreateException("Could not look up context");
    }
  }

  /**
   * 结算
   *
   */
  public TellerResult balance(String accountId)
      throws TellerException,
             RemoteException
  {
    if (VERBOSE)
      System.out.println("teller.balance called");
    return (this.new Balance(accountId)).transaction();
  }

  /**
   * 存入
   */
  public TellerResult deposit(String accountId, double amount, String transactionId)
      throws TellerException,
             RemoteException
  {
    if (VERBOSE)
      System.out.println("teller.deposit called");
    return (this.new Deposit(accountId, amount, transactionId)).transaction();
  }

  /**
   * 提取
   *
   * @参数 accountId         string 账号ID
   * @参数 amount            double 提取数量
   * @参数 transactionId     string 业务ID
   * @返回                  TellerResult 结果
   */
  public TellerResult withdraw(String accountId, double amount, String transactionId)
      throws TellerException,
             RemoteException
  {
    if (VERBOSE)
      System.out.println("teller.withdraw called");
    return (this.new Withdrawal(accountId, amount, transactionId)).transaction();
  }

  /**
   *转账
   *
   * @参数 accountFrom       string 源账号ID
   * @参数 accountTo         string 目的账号ID
   * @参数 amount            double 转账数目
   * @参数 transactionId     string 业务ID
   */
  public TellerResult transfer(String accountFrom, String accountTo, 
    double amount, String transactionId)
      throws TellerException,
             RemoteException
  {
    if (VERBOSE)
      System.out.println("teller.transfer called");
    return (this.new Transfer(accountFrom, accountTo, amount, transactionId)).transaction();
  }

  /**
   * 检查业务id
   */
  public boolean checkTransactionId(String transactionId)
      throws RemoteException {
    if (VERBOSE) {
      System.out.println("teller.checkTransaction called: failover test point");
      try {
        Thread.sleep(SLEEP);
      } catch (InterruptedException ie) {
      // do nothing
      }
    }
    //以下是数据库操作
    Connection conn  = null;
    Statement  stmt  = null;
    ResultSet  rs    = null;
    boolean    check = false;
    try {
      conn = getDatabaseConnection();
      stmt = conn.createStatement();
      rs = stmt.executeQuery("select transId from ejbTransLog where transId = " + transactionId);
      while (rs.next())
        check = true;
    }
    catch (SQLException sqe) {
      throw new RemoteException (sqe.getMessage());
    }
    finally {
      try {
        if (rs  != null) rs.close();
        if (stmt!= null) stmt.close(); 
        if (conn!= null) conn.close(); 
      }
      catch (Exception ignore) {}
    }
    return check;
  }

// 私有方法

  /**
   * 插入业务日志表一个记录
   */
  private void setTransactionId(String transactionId) throws RemoteException {
    if (VERBOSE)
      System.out.println("account.setTransactionId called");
    //数据库操作
    Connection         conn = null;
    Statement          stmt = null;
    ResultSet          rs   = null;
    PreparedStatement  ps   = null;
    int                numberOfTrans = 0; 
    try {
    	//数据库连接
      conn = getDatabaseConnection();
      System.out.println("account.conn.createStatement() called");
      stmt = conn.createStatement();
      rs   = stmt.executeQuery("select count(*) from ejbTransLog");
      while (rs.next())
        numberOfTrans = rs.getInt(1);

      java.sql.Timestamp now = new java.sql.Timestamp(new java.util.Date().getTime());

      if (numberOfTrans < maxLogTableSize) {
        if (VERBOSE)
          System.out.println("account.setTransactionId: inserting record into log");
        ps = conn.prepareStatement("insert into ejbTransLog values (?,?)");
      } else {
        if (VERBOSE)
          System.out.println("account.setTransactionId: updating record in log");
        ps = conn.prepareStatement(
             "update ejbTransLog set transId = ?, transCommitDate = ? where " +
             "transCommitDate = (select min(transCommitDate) from ejbTransLog) and " +
             "transId = (select min(transId) from ejbTransLog " +
             " where transCommitDate = " +
             "  (select min(transCommitDate) from ejbTransLog) )");
      }
      ps.setString(1, transactionId);
      ps.setTimestamp(2, now);
      ps.execute();
    }
    catch (SQLException sqe) {
      throw new RemoteException (sqe.getMessage());
    }
    finally {
      try {
        if (rs  != null) rs.close();
        if (ps  != null) ps.close(); 
        if (stmt!= null) stmt.close(); 
        if (conn!= null) conn.close(); 
      }
      catch (Exception ignore) {}
    }
  }

  /**
   * 从数据连接池中返回一个连接

   */
  private Connection getDatabaseConnection() throws SQLException {
    return DriverManager.getConnection("jdbc:weblogic:jts:" + logPoolName);
  }

  /**
   * 返回服务器名
   *
   * @返回                  String 服务器名
   */
  private String getServerName() {
    if (VERBOSE)
      System.out.println("teller.getServerName called");
    String toReturn = null;
    try {
      toReturn = weblogic.management.Admin.getServerName();
      if (toReturn == null) {
        return "";
      } else {
        return toReturn;
      }
    }
    catch (Exception e) {
      return "";
    }
  }

  /**
   * 内部类用来调用会话beans.
   *
   */
  class Transaction{
    //业务id
    String transactionId;
    //账号1
    String account1Id;
    //账号2
    String account2Id;
    //数目
    double amount;
    //账号1
    AccountPK       account1PK;//     = new AccountPK();
    Account         account1;
    AccountResult   account1Result;// = new AccountResult();
    //账号2
    AccountPK       account2PK;
    Account         account2;
    AccountResult   account2Result;// = new AccountResult();
    //事务
    UserTransaction tx;

  /**
   * 业务方法
   */
  TellerResult transaction() throws TellerException, RemoteException {
    if (VERBOSE)
      System.out.println("teller.transaction: transactionId = " + transactionId);
    try {
      Properties p = new Properties();
      //上下文
      InitialContext ic = new InitialContext(p);
      if (bank == null) {
        if (VERBOSE)
          System.out.println("teller.transaction: looking up bank home");
        //查找主接口
        bank = (AccountHome)ic.lookup("examples.cluster.ejb.AccountHome");
      }
      if (transactionId != null) {
 	
        tx = (UserTransaction)ic.lookup("javax.transaction.UserTransaction");
        //事务开始
        tx.begin();
      }
      //触发事务
      invokeTransaction();
      if (transactionId != null) {
        setTransactionId(transactionId);
        if (VERBOSE)
          System.out.println("teller.transaction: tx.commit() about to be called: " +
                             "failover test point");
        Thread.sleep(SLEEP);
        if (VERBOSE)
          System.out.println("teller.transaction: calling tx.commit()");
        tx.commit();
        if (VERBOSE)
          System.out.println("teller.transaction: tx.commit() completed: " +
                             "failover test point");
        Thread.sleep(SLEEP);
      }
    }
    catch (Exception e ) {
    	//异常处理
      if (transactionId != null) {
        try {
          System.out.println("Rolling back transaction " + transactionId + 
            " because of exception:\n" + e.getMessage());
          tx.rollback();
        } 
        catch (Exception ee) {
          // 异常处理
          throw new TellerException(ee.getMessage());
        }
      }
      //抛出异常
      throw new RemoteException(e.getMessage());
    }
    //返回结果
    return new TellerResult(TellerBean.this.serverName, account1Result, account2Result);
  }

    /**
     * 业务的基本操作:找到一个账号bean
     * 基于主键
     */
    void invokeTransaction() throws AccountException, FinderException, RemoteException {
      if (account1Id != null) {
        account1PK = new AccountPK(account1Id);
        account1 = bank.findByPrimaryKey(account1PK);
      }
    }
  }

  /**
   * 执行结算值查询
   * 
   */
  class Balance extends Transaction {

    /**
     * 构造方法
     * 
     */
    Balance(String accountId) {
     this.account1Id = accountId;
    }

    /**
     * 调用TellerBean执行结算值查询
     *
     */
    void invokeTransaction() throws AccountException, FinderException, RemoteException {
      super.invokeTransaction();
      account1Result = account1.balance();
    }
  }

  /**
   * 执行存入
   * 
   */
  class Deposit extends Transaction {

    /**
     * 构造方法.
     * 
     */
    Deposit(String accountId, double amount, String transactionId) {
      this.account1Id    = accountId;
      this.amount        = amount;
      this.transactionId = transactionId;
    }

    /**
     * 调用TellerBean执行存入
     *
     */
    void invokeTransaction() throws AccountException, FinderException, RemoteException {
      super.invokeTransaction();
      account1Result = account1.deposit(amount);
    }
  }

  /**
   * 执行提取
   * 
   */
  class Withdrawal extends Transaction {

    /**
     * 构造方法.
     * 
     */
    Withdrawal(String accountId, double amount, String transactionId) {
      this.account1Id    = accountId;
      this.amount        = amount;
      this.transactionId = transactionId;
    }

    /**
     * 调用TellerBean执行提取
     *
     */
    void invokeTransaction() throws AccountException, FinderException, RemoteException {
      super.invokeTransaction();
      account1Result = account1.withdraw(amount);
    }
  }

  /**
   * 执行转账
   * 
   */
  class Transfer extends Transaction {

    /**
     * 构造方法.
     * 
     */
    Transfer(String accountFrom, String accountTo, double amount, String transactionId) {
      this.account1Id    = accountFrom;
      this.account2Id    = accountTo;
      this.amount        = amount;
      this.transactionId = transactionId;
    }

    /**
     * 调用TellerBean执行转账
     *
     */
    void invokeTransaction() throws AccountException, FinderException, RemoteException {
      super.invokeTransaction();
      if (account2Id != null) {
        account2PK     = new AccountPK(account2Id);
        account2       = bank.findByPrimaryKey(account2PK);
        account1Result = account1.withdraw(amount);
        account2Result = account2.deposit(amount);
      }
    }
  }
}

⌨️ 快捷键说明

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