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

📄 trademanagementsessionfacadebean.java

📁 Oracle的J2EE Sample
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
   * This method is used to check the available balance in the user account
   * whenever a 'Buy' or 'Sell' transaction is carried out by the user.
   *
   * @param accountNumber Account Number
   * @param amount        Amount to be added or subtracted
   * @return Boolean value indicating whether the account balance can be
   *         updated or not
   * @exception RemoteException If error occurs while checking account balance
   * @since 1.0
   */
  private boolean checkBalance(Integer accountNumber, float amount)
      throws RemoteException {

    boolean flag = false;

    try {

      // Find the User Account Entity for the input account number
      UserAccountLocal userAccountLocal =
        userAccountHomeLocal.findByPrimaryKey(accountNumber);

      // Get the account balance for the user
      float availableBalance = userAccountLocal.getAccountBalance();

      // Check if there is enough balance
      if (amount <= availableBalance) {
        flag = true;
      }

    } catch(FinderException ex) {
      throw (new RemoteException("Finder Exception in Update Balance : " +
                                 ex.toString()));
    }

    return flag;
  }

  /**
   * This method is used to update the available balance in the user account
   * whenever a 'Buy' or 'Sell' transaction is carried out by the user. If the
   * input operation is 'ADD', the input amount is added to the User's account.
   * Else if it is 'SUB', the balance is checked for availability before
   * subtracting the amount.
   *
   * @param accountNumber Account Number
   * @param amount        Amount to be added or subtracted
   * @param operation     Valid Values : 'ADD', 'SUB'
   * @return Boolean value indicating whether the account balance was
   *         updated or not
   * @exception RemoteException If error occurs while updating account balance
   * @since 1.0
   */
  private boolean checkAndUpdateBalance(Integer accountNumber,
                                        float amount,
                                        String operation)
      throws RemoteException {

    boolean flag = false;

    try {
      // Find the User Account Entity for the input account number
      UserAccountLocal userAccountLocal =
        userAccountHomeLocal.findByPrimaryKey(accountNumber);

      // Get the account balance for the user
      float availableBalance = userAccountLocal.getAccountBalance();

      if(operation.equals("SUB")) {
        // In case of subtraction, check if there is enough balance
        if(amount <= availableBalance) {
          // subtract amount
          userAccountLocal.setAccountBalance(availableBalance - amount);
          flag = true;
        }
      } else {
        if(operation.equals("ADD")) {
          // add amount
          userAccountLocal.setAccountBalance(availableBalance + amount);
          flag = true;
        }
      }
    } catch(FinderException ex) {
      throw (new RemoteException("Finder Exception in Update Balance : " +
                                 ex.toString()));
    }
    return flag;
  }

  /**
   * This method is called from TradeManagementHelper when the user buys
   * stock using the application. If the User has enough balance to carry out
   * the transaction, the trade amount is deducted from his account and
   * Portfolio Details, Trade Details are added. The Order Details are sent by
   * calling the method sendOrderDetails. If the available balance for the user
   * is not sufficient for the transaction, corresponding message is returned.
   * If everything goes through fine, 'SUCCESS' message is returned.
   * Else On 'FAILURE', corresponding message is returned.
   *
   * @param accountNo  Account Number
   * @param quantity   Quantity of stocks bought
   * @param symbol     Stock Symbol
   * @param isTraded   Boolean indicating if the symbol is traded or not
   * @param userEmail  Email id of the Logged in User
   * @param systemDate Formatted String containing value of System Date
   * @return The return message indicates whether the buy transaction
   *         was a success or failure.
   * @exception RemoteException If error occurs while adding details
   * @exception SQLException    If error occurs while getting data
   * @since 1.0
   */
  public String buyStock(Integer accountNo, Integer quantity,
                         String symbol, boolean isTraded,
                         String userEmail, Hashtable connHash, String systemDate)
      throws RemoteException, SQLException {

    String retMessage = "FAILURE";

    float price = tradeHelper.getLatestRate(symbol).getLowprice().floatValue();

    // Additional check though the check exists in Helper class itself
    if (price == 0) {
      retMessage = "Invalid Symbol, Unable to get the Stock Rate for the Symbol";
      return retMessage;
    }

    float amount       = quantity.floatValue() * price; // Calculate the trade amount

    Date  sysDate      = new Date();  // Current Date
    boolean updateFlag = false;

    // The following steps are involved in the buy transaction
    // 1) If the User's Account Balance is sufficient for the trade,
    //    the trade amount is deducted from the available balance
    //    and further trade processing is carried out as in Step 2)
    //    Else the corresponding error message is returned
    // 2) TradeDetails, Portfolio record is created with the stock information
    // 3) The Order Details are sent for further processing
    // 4) If the send is successful, the buy transaction is complete
    //    and 'SUCCESS' message is returned, Else the corresponding
    //    error message is returned.

    // The buy transaction is not complete until all the steps are carried
    // out successfully. Hence if any exception occurs during the transaction,
    // the previous steps have to be rolled back. This is achieved using the
    // setRollbackOnly() method on the SessionContext. This ensures that in
    // case of exception or failure, no changes are committed to the database.

    try {
      // Check the available balance, the return flag indicates
      // whether the balance can be updated or not
      updateFlag = checkBalance(accountNo, amount);
    } catch(RemoteException re) {
      throw new RemoteException("Remote Exception while checking balance : " +
                                re.toString());
    }

    int retVal;

    if(updateFlag) { // If the available balance permitted the transaction

      Integer nextTradeId = new Integer(0);

      // Create TradeDetailsInfo object
      TradeDetailsInfo tdInfo = new TradeDetailsInfo(null, "B", quantity,
                                                     sysDate, price, symbol,
                                                     "M", "O", null);
      try {

        // Add new trade details info for the account number and return the trade id
        nextTradeId = addTradeDetails(accountNo, tdInfo);

      } catch(RemoteException re) {
        sc.setRollbackOnly();
        throw new RemoteException("Remote Exception while adding tradedetails: "
                                  + re.toString());
      } catch(Exception ex) {
        sc.setRollbackOnly();
        throw new RemoteException("Exception while adding tradedetails: " +
                                  ex.toString());
      }

      Integer nextId = new Integer(0);

      // If the trade id has a valid value
      if(nextTradeId.intValue() > 0) {

        // Create PortfolioInfo object
        PortfolioInfo pfInfo = new PortfolioInfo(null, quantity, price,
                                                 symbol, null, sysDate,
                                                 "P", nextTradeId);
        try {

          // Add new portfolio info for the account number and return the next id
          nextId = addPortfolio(accountNo, pfInfo);

        } catch(RemoteException re) {
          sc.setRollbackOnly();
          throw new RemoteException("Remote Exception while adding Portfolio : "
                                    + re.toString());
        }

        try {

          // The Order Details are sent to the Exchange.
          // The Trade is successful only if the send is successful
          retVal = sendOrderDetails(accountNo, symbol, "B",
                                    quantity, isTraded, userEmail,
                                    connHash, systemDate);
          if (retVal < 0) {
            sc.setRollbackOnly();
            retMessage = "Failed to contact another FBS " +
                         "while trying to buy the stock";
          }

        } catch(RemoteException re) {
          retVal = -1;
          sc.setRollbackOnly();
          throw new RemoteException("Remote Exception while adding Portfolio : "
                                    + re.toString());
        }

        if (retVal >= 0) {

          boolean checkFlag = checkAndUpdateBalance(accountNo, amount, "SUB");

          // Check if available balance permits the transaction to complete
          // Return flag indicates whether the balance was updated or not
          if (checkFlag) {

            retMessage = "SUCCESS";

          } else {

            retMessage = "Cannot Proceed with the transaction, " +
                         "Not enough Account Balance";
            sc.setRollbackOnly();

          }
        }
      }

      if (retMessage.equals("FAILURE")) {

        retMessage = "Failed to carry out the transactions";

      }

    } else {

      retMessage = "Cannot Proceed with the transaction, " +
                   "Not enough Account Balance";
    }

    return retMessage;
  }

  /**
   * This method is called by TradeManagementHelper and is used by the
   * AdminHelper to transfer stocks from a corporate to an individual.
   * Portfolio details and Trade Details are added.
   * The Order Details are sent by calling the method sendOrderDetails.
   *
   * @param toAccountNumber Account Number to which Stocks are
   *                           to be transferred
   * @param symbol       Stock Symbol
   * @param qty          Quantity
   * @param price        Price
   * @param isTraded     Boolean indicating if the symbol
   *                     is traded or not
   * @param userEmail    Email id of the Logged in User
   * @param systemDate   Formatted String containing value of System Date
   * @return An integer indicating success or failure,
   *         0 indicates success and -1 indicates failure
   * @exception RemoteException If error occurs while adding details
   * @since 1.0
   */
  public Integer corporateTransfer(Integer toAccountNumber, String symbol,
                                   Integer qty, Float price, boolean isTraded,
                                   String userEmail, Hashtable connHash,
                                   String systemDate)
      throws RemoteException {

    Integer nextTradeId = new Integer(0);
    int     retVal      = 0;

    try {

      Date  sysDate      = new Date();  // Current Date

      // Calculate the trade amount
      float amount = qty.intValue() * price.floatValue();

      // The corporate transfer process involves the following steps :
      // 1) New TradeDetails and Portfolio are created
      // 2) The Order Details are sent for further processing
      // 3) If the send is successful, the transaction is complete and
      //    '0' is returned indicating success, Else -1 is returned.

      // The corporate transfer transaction is not complete until all the steps
      // are carried out successfully. Hence if any exception occurs during the
      // transaction, the previous steps have to be rolled back. This is achieved
      // using the setRollbackOnly() method on the SessionContext. So in case of
      // exception or failure, the transactions are rolled back.

      // Create TradeDetailsInfo object
      TradeDetailsInfo tdInfo = new TradeDetailsInfo(null, "T", qty, sysDate,
                                                     price.floatValue(), symbol,
                                                     "M", "O", null);

      // Add new trade details info for the account number
      // and return the next trade id
      nextTradeId = addTradeDetails(toAccountNumber, tdInfo);

      // Create PortfolioInfo object
      PortfolioInfo pfInfo = new PortfolioInfo(null, qty, price.floatValue(),
                                               symbol, null, sysDate, "P",
                                               nextTradeId);
      Integer nextId;

      // Add new portfolio info for the account number and return the next id
      nextId = addPortfolio(toAccountNumber, pfInfo);

      // The Order Details are sent to the Exchange.
      // The Trade is successful only if the send is successful
      retVal = sendOrderDetails(toAccountNumber, symbol, "T", qty, isTraded,
                                userEmail, connHash, systemDate);

      if (retVal < 0) {

⌨️ 快捷键说明

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