📄 trademanagementsessionfacadebean.java
字号:
sc.setRollbackOnly();
nextTradeId = new Integer(0);
}
} catch(RemoteException ex) {
throw new RemoteException("Exception in corporate transfer " +
"while sending order details : \n" +
ex.toString());
}
return nextTradeId;
}
/**
* This method is called from TradeManagementHelper when the user sells stock
* using the application. The trade amount is calculated after getting the
* current stock price. Trade Details are added. Portfolio details are updated.
* The User's Available balance is updated depending on whether the stock was
* bought by the user or obtained through corporate transfer. In case of
* corporate transfer only the difference between the current stock value and
* the stock value when it was transferred (ie,. the profit) is updated.
* In case the profit is negative, the balance remains unchanged.
* Order Details are sent by calling the method sendOrderDetails.
*
* @param accountNo User Account Number
* @param qtyValues String Array of Stock Quantity Values
* @param lineNos String Array of Line Numbers
* @param symbols String Array of Stock Symbols
* @param tradeId String Array of Trade Id
* @param isTradedFlag String Array containing 'Y' if the symbol is traded
* or 'N' if not
* @param userEmail Email id of the Logged in User
* @param systemDate Formatted String containing value of System Date
* @return The return message is a string which contains details
* about the failure or success of the sell transactions.
* @exception RemoteException If error occurs while adding details
* @exception SQLException If error occurs while getting data
* @since 1.0
*/
public String sellStock(Integer accountNo, String[] qtyValues,
String[] lineNos, String[] symbols,
String[] tradeId, String[] isTradedFlag,
String userEmail, Hashtable connHash,
String systemDate)
throws RemoteException, SQLException {
Integer quantity = new Integer(0);
int retVal = 0;
String retMessage = "";
StringBuffer sb = new StringBuffer();
Date sysDate = new Date(); // Current Date
for (int i = 0;i < lineNos.length;i++) {
retMessage = "FAILURE";
if (!qtyValues[i].equals("")) {
Integer nextTradeId = new Integer(0);
float price = tradeHelper.getLatestRate(symbols[i]).getLowprice().floatValue();
try {
quantity = new Integer(qtyValues[i]);
} catch (NumberFormatException nfe) {
retMessage = "INVALIDQUANTITY";
sb.append("Failed to sell stocks of '");
sb.append(symbols[i]);
sb.append("' : Invalid Quantity! \n");
}
String retValue = "FAILURE";
TradeDetailsInfo tdInfo = null;
// The following steps are involved in the sell transaction
// 1) TradeDetails, Portfolio record is created with the stock information
// 2) The User's Account Balance is updated with the trade amount
// 3) The Order Details are sent for further processing
// 4) If the send is successful, the sell transaction is complete,
// and 'SUCCESS' message is appended to the return string,
// Else the corresponding error message is appended.
// 5) The above steps are repeated for all the records.
// The sell 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.
if (!(retMessage.equals("INVALIDQUANTITY"))) {
// Proceed further only if the quantity is valid
// Create TradeDetailsInfo object
tdInfo = new TradeDetailsInfo(null, "S", quantity,
sysDate, price,
symbols[i], "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 sellStock: " +
re.toString());
}
// Create PortfolioInfo object
PortfolioInfo pfInfo = new PortfolioInfo(Integer.valueOf(lineNos[i]),
quantity, price, symbols[i],
null, sysDate, "P", nextTradeId);
// If the trade id has a valid value
if (nextTradeId.intValue() > 0) {
try {
// Update portfolio info for the Account Number
retValue = updatePortfolio(accountNo, pfInfo);
} catch(RemoteException re) {
sc.setRollbackOnly();
throw new RemoteException("Remote Exception while updating " +
"Portfolio details sellStock: " +
re.toString());
}
if (retValue.equals("INSUFFICIENTQUANTITY") ||
retValue.equals("RECORDNOTFOUND")) {
sc.setRollbackOnly();
sb.append("Failed to sell stocks of '");
sb.append(symbols[i]);
sb.append("' : Stocks possibly sold in another transaction! \n");
}
}
}
if (retValue.equals("SUCCESS")) {
boolean updateFlag = false;
float amount = 0;
tdInfo = null;
try {
// Get the TradeDetailsInfo corresponding to the stock which is being sold
tdInfo = getTradeDetailsInfo(new Integer(tradeId[i]));
} catch(RemoteException re) {
sc.setRollbackOnly();
throw new RemoteException("Remote Exception while getting TradeDetails Info : "
+ re.toString());
}
// Calculate amount depending on whether the stocks were purchased or
// transferred through corporate transfer
// In case of purchase, amount = (quantity * current price)
// In case of corporate transfer,
// amount = (quantity * (current price - buy price)
if (tdInfo.getAction().equals("B")) {
amount = quantity.floatValue() * price;
} else if(tdInfo.getAction().equals("T")) {
// Stocks transferred through corporate transfer
amount = quantity.floatValue() * (price - tdInfo.getPrice());
// Only profit has to be considered
if (amount < 0) {
amount = 0;
}
}
try {
// Check the available balance and add the trade amount
// Return flag indicates whether the balance was updated or not
updateFlag = checkAndUpdateBalance(accountNo, amount, "ADD");
} catch(RemoteException re) {
sc.setRollbackOnly();
throw new RemoteException("Remote Exception while updating balance : "
+ re.toString());
}
boolean isTraded = false;
if (isTradedFlag[i].equals("Y")) {
isTraded = true;
}
// The Order Details are sent to the Exchange.
// The Trade is successful only if the send is successful
retVal = sendOrderDetails(accountNo, symbols[i], "S", quantity,
isTraded, userEmail, connHash, systemDate);
if (retVal < 0) {
// If send is not successful, the transaction has to be rolled back
sc.setRollbackOnly();
} else {
retMessage = "SUCCESS";
}
if(retMessage.equals("SUCCESS")) {
sb.append("Transaction completed. ");
sb.append(qtyValues[i]);
sb.append(" stocks of '");
sb.append(symbols[i]);
sb.append("' sold at the price : $");
sb.append(price);
sb.append(" per share \n");
} else {
sb.append("Failed to sell stocks of '");
sb.append(symbols[i]);
sb.append("' \n");
}
}
}
}
return sb.toString();
}
/**
* This method is called when any user transaction ie,. 'Buy', 'Sell' or
* 'Transfer' happens. The trade details are sent to the stock exchange. The
* Stock exchange is a JMS queue which provides asynchronous processing for
* conducting trade. The exchange process the trade request and sends a
* notification to the user.
*
* @param accountNo User Account Number
* @param symbol Stock Symbol
* @param tradeType Trade Type
* Valid Values : 'B' for 'Buy', 'S' for 'Sell', 'T' for 'Transfer'
* @param quantity Quantity
* @return Returns an int indicating success or failure :
* 0 for success and -1 for failure
* @exception RemoteException If error occurs while sending the Order Details
* @since 1.0
*/
private int sendOrderDetails(Integer accountNo, String symbol,
String tradeType, Integer quantity,
boolean isTraded, String userEmail,
Hashtable connHash, String tradeDt)
throws RemoteException {
int retVal = 0;
if (isTraded) {
QueueSession session = null;
QueueConnection qconn = null;
try {
// Send a message to the exchange with trade details
if(exchageQConnfactory == null || exchangeQueue == null) {
InitialContext ic = new InitialContext();
exchageQConnfactory = (QueueConnectionFactory)ic.lookup(
(String)connHash.get("EXCHQCONNFACTORY"));
exchangeQueue = (Queue)ic.lookup((String)connHash.get("EXCHQUEUE"));
}
// Create Queue Connection
qconn = exchageQConnfactory.createQueueConnection();
qconn.start();
session = qconn.createQueueSession(false, 1);
// Create a message and set the trade details
Message message = session.createMessage();
message.setStringProperty("toAddress", userEmail);
message.setStringProperty("symbol", symbol);
message.setStringProperty("tradeDate", tradeDt);
message.setStringProperty("tradeType", tradeType);
message.setStringProperty("qty", quantity.toString());
message.setJMSExpiration(18000L);
// Send the message
session.createSender(exchangeQueue).send(message);
} catch (Exception ex) {
throw new RemoteException(" sendOrderDetails failed :"+
ex.toString());
} finally {
try {
if(session != null)
session.close();
if(qconn != null)
qconn.close();
} catch(JMSException je) {
retVal = -1;
throw new RemoteException("JMSException : while closing session" + je.toString());
}
}
} else {
retVal = -2;
}
return retVal;
}
/**
* Other Standard Call Back Methods
* @since 1.0
*/
public void ejbRemove() {}
public void ejbActivate() {
initialize(); // To avoid de-serialization errors
}
public void ejbPassivate() {}
public void setSessionContext(SessionContext cntx) {
sc = cntx;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -