/*
 * @author : Elangovan
 * 
 * Development Environment : Oracle9i JDeveloper
 * Name of the file        : StockQuoteBean.java
 * 
 * Creation/Modification History
 * 
 *   Elangovan        06-Aug-2003      Created
 * 
 */
package oracle.otnsamples.ibfbs.admin.ejb;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import java.rmi.RemoteException;
import oracle.otnsamples.ibfbs.toplink.Stockrate;

import oracle.otnsamples.ibfbs.trademanagement.ejb.TradeHelper;

/**
 *  This class implements the StockQuoteService endpoint interface. When the  
 *  stock quote web service is invoked through the end-point interface, this bean
 *  is invoked. Uses TopLink persistence framework to fetch the stock quotes for
 *  the specified symbols. 
 *  
 *  @see StockQuoteService.java
 *  @see oracle.otnsamples.ibfbs.trademanagement.ejb.TradeHelper.java
 *  
 */
public class StockQuoteBean implements SessionBean  {
 
  private TradeHelper tradeHelper = null;

  /**
   * Standard callback method invoked by the container when an instance of this
   * bean is created. Initializes TradeHelper.
   */
  public void ejbCreate() {
      tradeHelper = TradeHelper.getInstance();
  }
   

  /**
   * This method retrieves the latest stock quote for the specified array of symbols.
   *  
   * @param symbols A valid array of stock symbols for which quote is required
   * @return Array of latest stock quotes corresponding to the specified symbols
   * @throws RemoteException if input symbol array is null or blank
   *  
   */
  public Float[] getStockQuote(String symbols[]) 
    throws RemoteException {
    
    // Validate input parameter
    if(symbols == null || symbols.length == 0)
      throw new RemoteException(" Stock Symbols cannot be null or blank ");

    Float[] rates = new Float[symbols.length];
    Stockrate rate = null;
    // Loop through the input symbols, fetch stock quotes and populate the
    // return array
    for(int ctr=0;ctr<symbols.length;ctr++) {
      try {
        rate = tradeHelper.getLatestRate(symbols[ctr]);
        if(rate == null)  { // Invalid symbol
          rates[ctr] = new Float(0f);  
        } else  {
          rates[ctr] = new Float(rate.getLowprice().floatValue());        
        }  
      } catch(Exception ex) {
        System.err.println("StockQuoteBean.getStockQuote: Error getting Stock rate :"+
                            ex.toString());
        rates[ctr] = new Float("0");
      }
    }
    return rates;
  }

  // Standard callback methods
  
  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void ejbRemove() {
    tradeHelper = null;
  }

  public void setSessionContext(SessionContext ctx) {
  }
  
}