package oracle.otnsamples.oracle9ijdbc.transactiontoggling;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.XAConnection;
import javax.naming.NamingException;
import javax.transaction.xa.Xid;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.XAException;
import java.io.IOException;
import oracle.jdbc.xa.client.OracleXADataSource;
import oracle.jdbc.xa.OracleXid;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Hashtable;
import java.util.Date;
import java.util.Enumeration;
import java.util.ArrayList;
public class TransTogglingSampleBean {
private XAConnection xconnLocal = null;
private XAConnection xconnGlobal = null;
OracleXADataSource oxdsLocal = null;
OracleXADataSource oxdsGlobal = null;
private HttpSession session = null;
public static Properties loadParams( String file ) throws IOException {
Properties prop = new Properties();
ResourceBundle bundle = ResourceBundle.getBundle( file );
Enumeration enum = bundle.getKeys();
String key = null;
while( enum.hasMoreElements() ) {
key = (String)enum.nextElement();
prop.put( key, bundle.getObject( key ) );
}
return prop;
}
public void initDataSource() throws NamingException, Exception{
Properties localConnProp = this.loadParams("ConnectionLocal");
Properties globalConnProp = this.loadParams("ConnectionGlobal");
java.sql.DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn = java.sql.DriverManager.getConnection(
"jdbc:oracle:thin:@" +
(String)localConnProp.get("HostName") + ":" +
(String)localConnProp.get("Port") + ":" +
(String)localConnProp.get("SID"),
(String)localConnProp.get("UserName"),
(String)localConnProp.get("Password"));
conn.close();
oxdsLocal = new OracleXADataSource();
oxdsGlobal = new OracleXADataSource();
this.configureDataSource(oxdsLocal, localConnProp);
this.configureDataSource(oxdsGlobal, globalConnProp);
oxdsLocal.setNativeXA(true);
oxdsGlobal.setNativeXA(true);
}
public void dbConnection() throws SQLException, Exception{
if(oxdsLocal == null || oxdsGlobal == null)
initDataSource();
if(oxdsLocal != null) {
xconnLocal = oxdsLocal.getXAConnection();
}
if(oxdsGlobal != null) {
xconnGlobal = oxdsGlobal.getXAConnection();
}
}
private boolean doGlobalUpdate(Connection connLocal, HttpServletRequest request)
throws SQLException, XAException, Exception {
Connection connGlobal = null;
XAResource xresLocal = null;
XAResource xresGlobal = null;
Xid xidLocal = null;
Xid xidGlobal = null;
try {
boolean doCommit = true;
xresLocal = xconnLocal.getXAResource();
xresGlobal = xconnGlobal.getXAResource();
connGlobal = xconnGlobal.getConnection();
xidLocal = createXid(1);
xidGlobal = createXid(2);
xresLocal.start(xidLocal,XAResource.TMNOFLAGS);
xresGlobal.start (xidGlobal ,XAResource.TMNOFLAGS);
this.insertShippingInformation(connGlobal,
request.getParameter("OtherCity"), request);
this.updateShippingStatus(connLocal);
xresLocal.end(xidLocal,XAResource.TMSUCCESS);
xresGlobal.end (xidGlobal ,XAResource.TMSUCCESS);
int prpLocal = xresLocal.prepare(xidLocal);
int prpGlobal = xresGlobal.prepare(xidGlobal);
if(!((prpLocal == XAResource.XA_OK) || (prpLocal == XAResource.XA_RDONLY)))
doCommit = false;
if(!((prpGlobal == XAResource.XA_OK) || (prpGlobal == XAResource.XA_RDONLY)))
doCommit = false;
if(prpLocal == XAResource.XA_OK) {
if(doCommit)
xresLocal.commit (xidLocal, false);
else
xresGlobal.rollback (xidLocal);
}
if(prpGlobal == XAResource.XA_OK) {
if (doCommit)
xresGlobal.commit (xidGlobal, false);
else
xresGlobal.rollback (xidGlobal);
}
connGlobal.close();
return(doCommit);
} catch (Exception excep) {
xresLocal.end(xidLocal,XAResource.TMFAIL);
xresGlobal.end (xidGlobal ,XAResource.TMFAIL);
xresGlobal.rollback (xidGlobal);
xresLocal.rollback(xidLocal);
connLocal.close();
connGlobal.close();
throw excep;
}
}
private Xid createXid(int branchId) throws XAException {
byte[] globalId = new byte[1];
globalId[0]= (byte)'O';
byte[] branchIdArr = new byte[1];
branchIdArr[0]= (byte)branchId;
byte[] globalTranId = new byte[64];
byte[] branchQualifier = new byte[64];
System.arraycopy (globalId, 0, globalTranId, 0, 1);
System.arraycopy (branchIdArr, 0, branchQualifier, 0, 1);
Xid xid = new OracleXid(0x1234, globalTranId, branchQualifier);
return xid;
}
private void insertOrderInformation(Connection conn, String city)
throws Exception {
int orderId = this.getOrderId(conn);
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement("INSERT INTO Order_Master "
+ "(Order_Id, Order_Date, Customer_Id, Branch_Id, Order_Total) "
+ " VALUES (?, ?, ?, ?,?)");
pstmt.setInt(1, orderId);
pstmt.setDate(2, new java.sql.Date(new Date().getTime()));
pstmt.setString(3, (String)session.getAttribute("UserId"));
pstmt.setString(4, this.getBranchId(city, conn));
pstmt.setFloat(5, this.getOrderTotal());
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement("INSERT INTO Order_Items (Order_Id, Product_Id,"
+" Quantity_Ordered) VALUES (?, ?, ?)");
pstmt.setInt(1, orderId);
ShoppingCartProduct scProduct = null;
Hashtable shoppingCartHash = (Hashtable)session.getAttribute("ShoppingCart");
Enumeration enumCart = shoppingCartHash.keys();
while (enumCart.hasMoreElements()){
scProduct = (ShoppingCartProduct)shoppingCartHash.get(enumCart.nextElement());
pstmt.setString(2, scProduct.productID);
pstmt.setInt(3,scProduct.getQuantityOrdered());
pstmt.executeUpdate();
}
pstmt.close();
}
private void updateShippingStatus(Connection conn) throws Exception {
PreparedStatement pstmt = conn.prepareStatement(" UPDATE Order_Master SET "
+ "Order_Status = 'Shipped' where Order_Id = ?");
pstmt.setInt(1,((Integer)session.getAttribute("OrderId")).intValue());
pstmt.executeUpdate();
pstmt.close();
}
private void insertShippingInformation(Connection conn, String city,
HttpServletRequest request) throws Exception {
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement("INSERT INTO Shipping_Details "
+ "(Order_Id, Name, Email_Id, Phone_Number, Address, City, "
+ "Country, Zip_Code) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
pstmt.setInt(1, ((Integer)session.getAttribute("OrderId")).intValue());
pstmt.setString(2, request.getParameter("Name"));
pstmt.setString(3, request.getParameter("EmailId"));
pstmt.setString(4, request.getParameter("PhoneNumber"));
pstmt.setString(5, request.getParameter("Address"));
pstmt.setString(6, city);
pstmt.setString(7, request.getParameter("Country"));
pstmt.setInt(8, Integer.parseInt(request.getParameter("ZipCode")));
pstmt.executeUpdate();
pstmt.close();
}
public Hashtable getUserDetails(String userId, String password)
throws SQLException, Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
Hashtable customerDetails = null;
conn = xconnLocal.getConnection();
pstmt = conn.prepareStatement(" SELECT Customer_Name, Role "
+ " FROM Customer_Master "
+ " WHERE LOWER(TRIM(Customer_Id)) = "
+ "LOWER(TRIM(?)) AND LOWER(Password) = LOWER(?)");
pstmt.setString(1, userId);
pstmt.setString(2, password);
rset = pstmt.executeQuery();
if(rset.next()) {
customerDetails = new Hashtable();
customerDetails.put("UserName", rset.getString(1));
customerDetails.put("Role", rset.getString(2));
}
rset.close();
pstmt.close();
conn.close();
return(customerDetails);
}
public Hashtable getProductDetails() throws Exception {
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
Hashtable productDetails = new Hashtable();
conn = xconnLocal.getConnection();
String query = "SELECT Product_Id, INITCAP(Product_Name), Product_Desc, "
+ "Price, Category_Desc, Quantity_On_Hand "
+ "FROM Product_Master ORDER BY LOWER(Product_Name)";
stmt = conn.createStatement();
rset = stmt.executeQuery(query);
Product productObj = null;
while(rset.next()) {
productObj = new Product(rset.getString(1), rset.getString(2),
rset.getString(3),
rset.getFloat(4), rset.getString(5),
rset.getInt(6));
productDetails.put(rset.getString(1), productObj);
}
rset.close();
stmt.close();
conn.close();
return(productDetails);
}
public void placeOrder(HttpServletRequest request) throws SQLException, Exception{
Connection conn = null;
session = request.getSession(false);
String city = request.getParameter("City");
String shippedFrom = "";
if(city.equals("Others")){
shippedFrom = "Washington";
} else {
shippedFrom = city;
}
conn = xconnLocal.getConnection();
this.insertOrderInformation(conn, shippedFrom);
conn.commit();
if(shippedFrom.equals("San Francisco")){
try {
conn.setAutoCommit(false);
this.insertShippingInformation(conn, city, request);
this.updateShippingStatus(conn);
conn.commit();
} catch(Exception excep){
conn.rollback();
}
}else if(shippedFrom.equals("Washington")){
this.doGlobalUpdate(conn, request);
}
conn.close();
}
public void retrieveAllOrders(HttpServletRequest request) throws Exception {
session = request.getSession(false);
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
Hashtable orderHash = new Hashtable();
conn = xconnLocal.getConnection();
String query = "SELECT Order_Id, Customer_Id, "
+ "TO_CHAR(Order_Date,'dd-MON-yyyy'), Order_Total, "
+ "INITCAP(Branch_Location), Order_Status "
+ "FROM Order_Master om, Shipping_Branches sb "
+ "WHERE om.Branch_Id = sb.Branch_Id ORDER BY Order_Id DESC";
stmt = conn.createStatement();
rset = stmt.executeQuery(query);
OrderMasterInfo orderMasterInfo = null;
int orderId = 0;
while(rset.next()) {
orderId = rset.getInt(1);
orderMasterInfo = new OrderMasterInfo(orderId, rset.getString(2),
rset.getString(3), rset.getFloat(4),
rset.getString(5), rset.getString(6));
orderHash.put(new Integer(orderId), orderMasterInfo);
}
session.setAttribute("AllOrders", orderHash);
rset.close();
stmt.close();
conn.close();
}
public void retrieveOrderDetails(int orderId) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
session.removeAttribute("OrderItems");
session.removeAttribute("ShippingDetails");
conn = xconnLocal.getConnection();
pstmt = conn.prepareStatement(" SELECT oi.Product_Id, INITCAP(Product_Name),"
+ " Price, Quantity_Ordered "
+ "FROM Order_Items oi, Product_Master pm "
+ "WHERE Order_Id = ? AND "
+ "oi.Product_Id = pm.Product_Id");
pstmt.setInt(1, orderId);
rset = pstmt.executeQuery();
ArrayList orderItems = new ArrayList();
while(rset.next()) {
orderItems.add(rset.getString(1));
orderItems.add(rset.getString(2));
orderItems.add(new Float(rset.getFloat(3)));
orderItems.add(new Integer(rset.getInt(4)));
}
session.setAttribute("OrderItems", orderItems);
rset.close();
pstmt.close();
Hashtable ordersHash = (Hashtable)session.getAttribute("AllOrders");
OrderMasterInfo orderObj = (OrderMasterInfo)ordersHash.get(new Integer(orderId));
String branchLocation = orderObj.branchLocation;
String orderStatus = orderObj.orderStatus;
if(orderStatus.equalsIgnoreCase("Shipped")) {
if(branchLocation.equals("Washington")){
conn.close();
conn = xconnGlobal.getConnection();
}
retrieveShippingDetails(conn, orderId);
}
conn.close();
}
public void retrieveShippingDetails(Connection conn, int orderId)
throws Exception {
PreparedStatement pstmt = null;
ResultSet rset = null;
pstmt = conn.prepareStatement(" SELECT INITCAP(Name), Email_Id, Phone_Number,"
+ " Address, INITCAP(City), INITCAP(Country), Zip_Code "
+ "FROM Shipping_Details WHERE Order_Id = ?");
pstmt.setInt(1, orderId);
rset = pstmt.executeQuery();
ShippingDetails shippingDetails = null;
if(rset.next()) {
shippingDetails = new ShippingDetails(rset.getString(1), rset.getString(2),
rset.getString(3),
rset.getString(4), rset.getString(5),
rset.getString(6), rset.getInt(7));
}
session.setAttribute("ShippingDetails", shippingDetails);
rset.close();
pstmt.close();
}
private String getBranchId(String city, Connection conn) throws Exception{
PreparedStatement pstmt = conn.prepareStatement(" SELECT Branch_Id,"
+ " Shipping_Charge FROM Shipping_Branches "
+ " WHERE Branch_Location = ?");
pstmt.setString(1,city);
ResultSet rset = pstmt.executeQuery();
String branchId = "";
if(rset.next()) {
branchId = rset.getString(1);
session.setAttribute("ShippingCharges",new Float(rset.getFloat(2)));
}
rset.close();
pstmt.close();
return branchId;
}
private float getOrderTotal() throws Exception {
float orderTotal= 0.0f;
ShoppingCartProduct scProduct = null;
Hashtable shoppingCartHash = (Hashtable)session.getAttribute("ShoppingCart");
Enumeration enumCart = shoppingCartHash.keys();
while (enumCart.hasMoreElements()){
Object key = enumCart.nextElement();
scProduct = (ShoppingCartProduct)shoppingCartHash.get(key);
orderTotal += scProduct.getTotalPrice();
}
return orderTotal;
}
private int getOrderId(Connection conn) throws Exception{
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("SELECT ORDER_ID_SEQ.NEXTVAL FROM DUAL");
int orderId = 0;
if(rset.next()) {
orderId = rset.getInt(1);
session.setAttribute("OrderId", new Integer(orderId));
}
stmt.close();
return orderId;
}
private void configureDataSource(OracleXADataSource oxds, Properties prop) {
oxds.setDriverType("thin");
oxds.setServerName((String)prop.get("HostName"));
oxds.setPortNumber(new Integer((String)prop.get("Port")).intValue());
oxds.setDatabaseName((String)prop.get("SID"));
oxds.setUser((String)prop.get("UserName"));
oxds.setPassword((String)prop.get("Password"));
}
public void cleanUp()
throws SQLException,Exception {
if(session != null){
|