📄 adminhelper.java
字号:
/*
* @author : Elangovan
* @version : 1.0
*
* Development Environment : Oracle9i JDeveloper
* Name of the File : AdminHelper.java
*
* Creation / Modification History
* Elangovan 26-Apr-2002 Created
* Elangovan 28-Aug-2003 Modified
*
*/
package oracle.otnsamples.ibfbs.admin.helper;
// XML processing
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
// Servlet request
import javax.servlet.http.HttpServletRequest;
// JNDI imports
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Timer;
import oracle.otnsamples.ibfbs.usermanagement.helper.NewsHelper;
import oracle.otnsamples.ibfbs.trademanagement.helper.StockRateHelper;
import oracle.otnsamples.ibfbs.utils.XMLUtils;
import oracle.otnsamples.ibfbs.usermanagement.helper.UserManagementHelper;
import oracle.otnsamples.ibfbs.trademanagement.helper.TradeManagementHelper;
import oracle.otnsamples.ibfbs.admin.ejb.MailService;
import oracle.otnsamples.ibfbs.admin.ejb.MailServiceHome;
import oracle.otnsamples.ibfbs.admin.exception.AdminHelperException;
import oracle.otnsamples.ibfbs.usermanagement.exception.ApplicationError;
/**
* This class configures the upload tasks scheduled by the site
* administrator. When an upload task is scheduled, old tasks are
* cancelled and a new task s created with the new scheduled interval
* and configured. It also executes the orders sent by a corporate user by
* transferring stocks to the specified accounts.
*
* @see java.util.Timer
* @see oracle.otnsamples.ibfbs.usermanagement.helper.NewsHelper.java
* @see oracle.otnsamples.ibfbs.usermanagement.helper.StockRateHelper.java
* @see UploadStockRateTask.java
* @see UploadNewsTask.java
*/
public class AdminHelper {
// Timer to upload news data
private Timer uploadNewsTimer = null;
// Timer to upload stock rates
private Timer uploadStockRateTimer = null;
// To get StockRates for Headlines symbols
private StockRateHelper srHelper = null;
// To get News for Headlines symbols
private NewsHelper newsHelper = null;
// Symbols for News Headlines (can be set at runtime also)
private String[] headlinesSymbol = new String[] {
"ORCL", "IBM", "MSFT", "AOL", "BEAS", "CSCO", "HPQ", "SUNW", "PSFT"
};
/**
* Constructor, builds a new instance of AdminHelper.
*
* @exception AdminHelperException if initializing helper classes fails
*/
public AdminHelper()
throws AdminHelperException {
// Initialize helper classes
try {
srHelper = new StockRateHelper();
newsHelper = new NewsHelper();
} catch (Exception ex) { // Generic errors
throw new AdminHelperException(" Generic Exception while initializing "
+ " Helper classes :\n" + ex.toString());
}
}
/**
* This method does a lookup on JNDI tree using the specified JNDI name.
*
* @param jndiName JNDI name of the Object for lookup
* @return Object corresponding to the jndiName.
* @exception AdminHelperException if lookup of the specified jndiName fails
* @since 1.0
*/
private Object lookUp(String jndiName)
throws AdminHelperException {
// Object that was bound to the jndi tree
Object boundObject = null;
try {
// create Initial Context and look up directory service of OC4J for object
Context context = new InitialContext();
boundObject = context.lookup(jndiName);
} catch (NamingException ne) {
throw new AdminHelperException("NamingException while looking" + " up :"
+ jndiName + " \n" + ne.toString());
} catch (Exception ex) {
throw new AdminHelperException(" Generic Exception while looking "
+ " up :" + jndiName + " \n"
+ ex.toString());
}
return boundObject;
}
/**
* This method configures News upload timer. The interval to schedule
* the timer is taken from the request object. This uses java.util.Timer to
* schedule the task.
*
* @param req HttpServletRequest containing timer interval
* @return Integer status of configuration 0 - Success, -1 failure
* @exception ApplicationError if request contains invalid parameters
*/
public Integer configNewsUpload(HttpServletRequest req)
throws ApplicationError {
int status = 0;
int hour = Integer.parseInt(req.getParameter("NHOUR"));
int mins = Integer.parseInt(req.getParameter("NMINUTES"));
// Minimum interval should be 15 minutes
if ((hour <= 0) && (mins < 15)) {
throw new ApplicationError(" Minimum interval should be 15 minutes ");
} else {
// Calculate interval in milli seconds
long delay = (hour * 60 + mins) * 60 * 1000;
// If timer is running, stop it
if (uploadNewsTimer != null) {
// Cancel all the current tasks
uploadNewsTimer.cancel();
uploadNewsTimer = null;
}
// Initialize timer with given params and as a daemon process
uploadNewsTimer = new Timer(true);
// Schedule the task to run now and again after 'delay' milliseconds
uploadNewsTimer.schedule(new UploadNewsTask(), 0, delay);
}
req.setAttribute("InfoMessage", "News upload configured successfully");
return new Integer(status);
}
/**
* This method retrieves the latest stockrates and news for symbols set in
* the 'headlinesSymbol' member variable.
*
* @param req request object
* @return collection of StockRates and News
* @exception AdminHelperException if getting stockrates or news fails
*/
public Collection getStockRatesandNews(HttpServletRequest req)
throws AdminHelperException {
ArrayList result = new ArrayList(2);
try {
result.add(srHelper.getLatestRate(this.headlinesSymbol));
result.add(newsHelper.getLatestNews(this.headlinesSymbol));
} catch (Exception ex) {
throw new AdminHelperException(" Exception while getting "
+ " MarketData :\n" + ex.toString());
}
return result;
}
/**
* This method configures Stockrate upload timer. The interval to schedule
* the timer is taken from the request object. This uses java.util.Timer to
* schedule the task.
*
* @param req HttpServletRequest containing timer interval
* @return Integer status of configuration 0 - Success, -1 failure
* @exception ApplicationError if request contains invalid parameters
* @since 1.0
*/
public Integer configStockRateUpload(HttpServletRequest req)
throws ApplicationError {
int status = 0;
int hour = Integer.parseInt(req.getParameter("SHOUR"));
int mins = Integer.parseInt(req.getParameter("SMINUTES"));
// Minimum interval should be 15 minutes
if ((hour <= 0) && (mins < 15)) {
throw new ApplicationError("Minimum interval should be 15 minutes");
}
else {
// Calculate interval in milli seconds
long delay = (hour * 60 + mins) * 60 * 1000;
// If timer is running, stop it
if (uploadStockRateTimer != null) {
// Cancel all the current tasks
uploadStockRateTimer.cancel();
uploadStockRateTimer = null;
}
// Initialize timer with given params and as a daemon process
uploadStockRateTimer = new Timer(true);
// Schedule the task to run now and again after 'delay' milliseconds
uploadStockRateTimer.schedule(new UploadStockRateTask(), 0, delay);
}
req.setAttribute("InfoMessage", "Stock Rates upload configured successfully");
return new Integer(status);
}
/**
* This method, gets the Trade Orders as an XML String, parses it and
* executes the Orders.
*
* @param req Request object that contains the XMLOrder
* @return log messages during the execution of trade orders.
* @exception ApplicationError if request contains invalid parameters
* @since 1.0
*/
public String dispatchCorporateShares(HttpServletRequest req)
throws ApplicationError {
Document xmlOrderDoc = null;
Element xmlOrder = null;
// Log all messages while executing orders
StringBuffer log = new StringBuffer();
// Get the order from request instance
String strOrder = req.getParameter("XMLORDER");
// Validate the given xml order with the corporateorder schema.
if (strOrder != null) {
String requestURL = req.getRequestURL().toString();
String corpSchemaFilePath = requestURL.substring(0,requestURL.lastIndexOf("/"))+
"/schema/corporateorder.xsd";
xmlOrderDoc = XMLUtils.stringToXML(strOrder, corpSchemaFilePath);
}
// If the order is valid
if (xmlOrderDoc != null) {
// Get the root element
xmlOrder = xmlOrderDoc.getDocumentElement();
// Initialize helper classes to execute orders
TradeManagementHelper tradeHelper = new TradeManagementHelper();
UserManagementHelper userHelper = new UserManagementHelper();
// Stock Symbol to be traded
String symbol = xmlOrder.getAttribute("symbol");
// Get the Trade Orders
NodeList tradeOrder = xmlOrder.getElementsByTagName("TradeOrder");
int orderlen = tradeOrder.getLength();
Node order = null;
Integer result = null;
MailService mailService = null;
try {
// Initialize the MailSender
MailServiceHome mailServiceHome =
(MailServiceHome) lookUp("MailService");
mailService = mailServiceHome.create();
} catch (Exception ex) {
log.append("Warning : Couldn't initialize Mail Service ")
.append(" Manual dispatch of ")
.append(" acounts recommended ")
.append("\n");
}
// Iterate through the orders and execute the order
for (int ctr = 0; ctr < orderlen; ctr++) {
order = tradeOrder.item(ctr);
String strAccountNumber = XMLUtils.getNodeValueByName(order,
"ToAccountNumber");
// If account number is not given, create a new account and
// transfer the shares to the new account
if (strAccountNumber == null) {
// Get the Email ID and create a user
String email = XMLUtils.getNodeValueByName(order, "Email");
result = userHelper.signUpCorporateUser(email);
// If account creation was success
if (result.intValue() != 0) {
strAccountNumber = result.toString();
log.append("User Account created for :")
.append(email)
.append(" - Account Number : ")
.append(strAccountNumber)
.append("\n");
try {
// Email the account details for the user
mailService.sendMail(email,
"admin@fbs.com",
" FBS Account Details",
getMailBody(strAccountNumber));
} catch (Exception ex) {
log.append("Warning : Couldn't send account details for : ")
.append(strAccountNumber)
.append("\n");
}
} else {
log.append("Warning : Couldn't create user account for :")
.append(email)
.append("\n");
}
}
// Transfer stocks to the account
if (strAccountNumber != null) {
try {
result =
tradeHelper.corporateTransfer(
Integer.valueOf(strAccountNumber),
symbol,
Integer.valueOf(XMLUtils.getNodeValueByName(order,
"Quantity")),
Float.valueOf(XMLUtils.getNodeValueByName(order,
"Price")));
} catch (Exception ex) {
result = new Integer(0);
System.out.println("Warning : Couldn't transfer stocks :"
+ ex.toString());
}
if (result.intValue() != 0) {
log.append("Stock transfered to user :")
.append(strAccountNumber)
.append("\n");
} else {
log.append("Warning : Couldn't transfer stocks for user :")
.append(strAccountNumber)
.append("\n");
}
}
}
} else {
// Invalid order
throw new ApplicationError(" Invalid XML order ");
}
return log.toString();
}
/**
* Creates the mail body for new account notification message.
*
* @param accountNumber account number to be used to generate message
* @return generated mail body
*/
private String getMailBody(String accountNumber) {
StringBuffer mailBody = new StringBuffer(
"<br><br> Hi, <br> Your FBS Account Details <br><br> AccountNumber : ");
mailBody.append(accountNumber);
mailBody.append(" <br> Password : welcome");
mailBody.append(" <br><br> Please log in and update your personal ");
mailBody.append("information and preferences .<br>");
mailBody.append(" <br>Happy Trading !<br> FBS Team ");
return mailBody.toString();
}
/**
* This method sets the Headlines Symbol for News.
*
* @param headlinesSymbol Array of Symbols
* @since 1.0
*/
public void setHeadlinesSymbol(String[] headlinesSymbol) {
this.headlinesSymbol = headlinesSymbol;
}
/**
* This method returns the Headlines Symbol for News.
*
* @return headlinesSymbol Array of Symbols
* @since 1.0
*/
public String[] getHeadlinesSymbol() {
return headlinesSymbol;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -