📄 stocksymbolhelper.java
字号:
/*
* @author : Elangovan
* @version : 1.0
*
* Development Environment : Oracle9i JDeveloper
* Name of the File : StockSymbolHelper.java
*
* Creation / Modification History
* Elangovan 26-Apr-2002 Created
* Elangovan 19-Aug-2003 Modified
*
*/
package oracle.otnsamples.ibfbs.admin.helper;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import oracle.toplink.tools.sessionmanagement.SessionManager;
import oracle.toplink.sessions.UnitOfWork;
import oracle.toplink.tools.sessionconfiguration.XMLLoader;
import oracle.toplink.threetier.ServerSession;
import oracle.toplink.threetier.ClientSession;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReadAllQuery;
import oracle.toplink.queryframework.ReadObjectQuery;
import oracle.toplink.exceptions.DatabaseException;
import oracle.otnsamples.ibfbs.toplink.Exchange;
import oracle.otnsamples.ibfbs.toplink.Symbol;
import oracle.otnsamples.ibfbs.toplink.Stockrate;
import oracle.otnsamples.ibfbs.admin.exception.AdminHelperException;
import oracle.otnsamples.ibfbs.admin.exception.WebServiceAccessException;
import oracle.otnsamples.ibfbs.usermanagement.exception.ApplicationError;
/**
* This class manages the stock symbols. The Admin can add stock symbols and
* update the traded status of the stocks. Uses Toplink persistence framework
* to manage symbols.
*
* @see oracle.otnsamples.ibfbs.toplink.Symbol.java
*/
public class StockSymbolHelper {
// Toplink server session handle
ServerSession server = null;
/**
* Constructs a new instance of StockSymbolHelper class.
* @exception AdminHelperException if initializing Toplink Server Session fails
*/
public StockSymbolHelper()
throws AdminHelperException {
try {
// Initialize ServerSession from session.xml
server = (ServerSession) SessionManager.getManager().getSession(new XMLLoader(),
"FBSServerSession",
Thread.currentThread().getContextClassLoader());
}catch(DatabaseException dbEx) {
throw new AdminHelperException(" Error initializing Server Session :"+dbEx);
}
}
/**
* Returns the traded status of the symbol.
*
* @param symbol Symbol for which traded status is required
* @return traded status of the symbol.
* @exception ApplicationError if symbol is null or invalid
* @exception AdminHelperException if getting status fails
* @since 1.0
*/
public boolean isTradedHere(String symbol)
throws ApplicationError,AdminHelperException {
boolean traded = false;
// Get the Symbol details
Symbol s = this.getSymbol(symbol);
if (s==null) {
// Symbol not found
throw new ApplicationError(" Invalid Symbol : "+symbol);
} else {
if (s.getTraded().equalsIgnoreCase("Y")) {
traded = true;
}
}
return traded;
}
/**
* This method returns a Collection of all symbols.
*
* @return Collection of all symbols
* @exception AdminHelperException if getting symbols fails
*/
public Collection getAllSymbols()
throws AdminHelperException {
ClientSession client = null;
try {
// Initialize client session
client = server.acquireClientSession();
// Initialize read all query for Symbol ( for reading multiple symbols )
ReadAllQuery query = new ReadAllQuery(Symbol.class);
// ORDER BY SYMBOL ASCE
query.addAscendingOrdering("symbol");
// Force a cache of the query results
query.cacheQueryResults();
// Specify the Collection class that will hold the symbols, default is Vector
query.useCollectionClass(ArrayList.class);
return (ArrayList) client.executeQuery(query);
} catch (Exception ex) { // Generic errors
throw new AdminHelperException(" Generic Exception while getting "
+ " all symbols :\n" + ex.toString());
}
}
/**
* Extracts the symbol name from request and returns the Symbol instance.
*
* @param req The request object that contains 'SYMBOL' parameter.
* @return Symbol instance if found, else null
* @exception AdminHelperException if getting symbol fails
* @exception ApplicationError if symbol is blank
* @since 1.0
*/
public Symbol getSymbol(HttpServletRequest req)
throws AdminHelperException,ApplicationError {
String s = req.getParameter("SYMBOL");
if(s == null || "".equals(s)) {
throw new ApplicationError(" Symbol cannot be blank");
}
return this.getSymbol(s);
}
/**
* Returns the Symbol instance with the specified name.
* @param s Symbol name
* @return Symbol instance if match found, else null
* @exception AdminHelperException if getting symbol fails
*/
public Symbol getSymbol(String s)
throws AdminHelperException {
Symbol symbol = null;
ClientSession client = null;
try {
// Initialize client session
client = server.acquireClientSession();
// Initialize read query to read Symbol ( to read a single Symbol )
ReadObjectQuery readSymbol = new ReadObjectQuery(Symbol.class);
// Construct the where condition
// WHERE symbol = ?
ExpressionBuilder whereClause = new ExpressionBuilder();
readSymbol.setSelectionCriteria(whereClause.get("symbol").equalsIgnoreCase(s));
symbol = (Symbol)client.executeQuery(readSymbol);
} catch (DatabaseException dbEx) {
throw new AdminHelperException(" Error while getting "
+ " Symbol :\n" + dbEx.toString());
}
return symbol;
}
/**
* Checks with Web Service if the symbol name is valid.
*
* @param symbol Symbol name
* @return true - if symbol name is valid, else false
*/
public boolean isValidSymbol(String symbol) {
boolean validSymbol = true;
try {
// Initialize Webservicehelper
WebServicesHelper wsHelper = new WebServicesHelper();
// Get the stock rate
Stockrate stockrate = wsHelper.fetchStockRate(symbol);
// Check if the symbol is valid, Low price will be 0f for invalid symbol
if(stockrate.getLowprice().floatValue() <= 0f)
validSymbol = false;
} catch(WebServiceAccessException weEx) {
// Invalid Symbol
validSymbol = false;
}
return validSymbol;
}
/**
* This method adds the symbol details to the symbols repository.
*
* @param req request object
* @exception AdminHelperException if insert of symbol details fails
* @exception ApplicationError if request contains invalid parameters
*/
public void addSymbol(HttpServletRequest req)
throws AdminHelperException,ApplicationError {
if(req.getAttribute("EXCHANGELIST") == null)
req.setAttribute("EXCHANGELIST", this.getExchangesList());
if(req.getParameter("SYMBOL") != null) {
// Retrieve Symbol data from the request object
String symbol = req.getParameter("SYMBOL").trim().toUpperCase();
String companyName = req.getParameter("COMPANYNAME");
String companyProfile = req.getParameter("COMPANYPROFILE");
String traded = req.getParameter("TRADED").trim();
String exchangeId = req.getParameter("EXCHANGEID");
// If symbol name is valid
if(isValidSymbol(symbol)) {
UnitOfWork work = null;
try {
// Construct a new Symbol instance
Symbol newSymbol = new Symbol();
newSymbol.setSymbol(symbol);
newSymbol.setCompanyname(companyName);
newSymbol.setCompanyprofile(companyProfile);
newSymbol.setTraded(traded);
newSymbol.setExchangeid(new Integer(exchangeId));
// Get a transaction
work = server.acquireClientSession().acquireUnitOfWork();
// Register the object with transaction
work.registerNewObject(newSymbol);
// Commit the transaction
work.commit();
} catch (DatabaseException se) {
// Unique constraint error
if(se.toString().indexOf("ORA-00001") != -1) {
throw new ApplicationError(" Could not add '"+symbol+"', symbol exists already ");
} else {
throw new AdminHelperException("SQLException while inserting " + " symbol : \n"
+ se.toString());
}
} catch (Exception ex) { // Generic errors
throw new AdminHelperException(" Generic Exception while inserting "
+ " symbol:\n" + ex.toString());
}
} else {
throw new ApplicationError(" Could not add '"+symbol+"', invalid symbol ");
}
req.setAttribute("InfoMessage"," Symbol '"+symbol+"' added successfully ");
}
}
/**
* This method, updates the traded status of a symbol.
*
* @param req request object
* @return status message
* @exception AdminHelperException if updating status fails
* @exception ApplicationError if request contains invalid parameters
*
*/
public void changeTradedFlag(HttpServletRequest req)
throws AdminHelperException, ApplicationError {
if(req.getParameter("SYMBOL") == null)
throw new ApplicationError(" Symbol cannot be null");
// Retrieve the symbol to be updated and flag from request object
String traded = req.getParameter("TRADED").trim();
String symbol = req.getParameter("SYMBOL").trim().toUpperCase();
try {
Symbol s = this.getSymbol(symbol);
if(s == null) {
throw new ApplicationError(" Could not update traded status, symbol '" +
symbol + "' does not exist ");
} else {
// Get a transaction
UnitOfWork work = server.acquireClientSession().acquireUnitOfWork();
// Register the instance to be updated and
// create a clone of the instance
Symbol sClone = (Symbol) work.registerObject(s);
// Update the data in clone instance
sClone.setTraded(traded);
// Commit
work.commit();
}
} catch (Exception ex) {
throw new AdminHelperException(" Error while "
+ " updating traded status :\n"
+ ex.toString());
}
req.setAttribute("InfoMessage"," Traded status for '" + symbol + "' updated");
}
/**
* This method retrieves the list of exchanges where this financial brokerage
* system trades.
*
* @return list of exchanges
* @exception AdminHelperException if getting exchange detail fails
* @since 1.0
*/
public ArrayList getExchangesList()
throws AdminHelperException {
ArrayList exchanges = null;
ClientSession client = null;
try {
// Initialize client session
client = server.acquireClientSession();
// Initialize a read query with the object to be read
ReadAllQuery query = new ReadAllQuery(Exchange.class);
// Set the Collection class that should hold the return objects
query.useCollectionClass(ArrayList.class);
// Force a cache of this query results
query.cacheQueryResults();
exchanges = (ArrayList)client.executeQuery(query);
} catch (Exception ex) {
throw new AdminHelperException(" Error : Could not retrieve "
+ " Exchanges Details:\n" + ex.toString());
}
return exchanges;
}
/**
* This method uses page-by-page iterator to return the list of symbols.
*
* @param req Request containing the page details that is needed
* @return list of symbols as Collection
* @exception AdminHelperException when retrieval of symbols fails
*/
public Collection getSymbolPage(HttpServletRequest req)
throws AdminHelperException {
// Initialize default values
int pageNo = 1;
int symbolsPerPage = 5;
int startIndex = 0;
ArrayList symbols = (ArrayList)this.getAllSymbols();
int syblLength = symbols.size();
// Get page number
if (req.getParameter("PAGENO") != null) {
pageNo = Integer.parseInt(req.getParameter("PAGENO"));
}
// Get the number of symbols to be displayed per page
if (req.getParameter("SYMBOLSPERPAGE") != null) {
symbolsPerPage = Integer.parseInt(req.getParameter("SYMBOLSPERPAGE"));
}
startIndex = (pageNo - 1) * symbolsPerPage;
// Set the total number of pages so that client can write page numbers
req.getSession().setAttribute("TOTALPAGES",
new Integer((int) Math.ceil((float) syblLength
/ (float) symbolsPerPage)));
// Get the number of symbols for this page number
symbolsPerPage = (syblLength < (symbolsPerPage + startIndex))
? syblLength - startIndex
: symbolsPerPage;
return symbols.subList(startIndex,startIndex+symbolsPerPage);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -