package oracle.otnsamples.oracle9ijdbc.savepoint;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import oracle.jdbc.pool.OracleDataSource;
import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.ArrayList;
public class SavepointSample
{
private Connection conn=null;
private SavepointFrame savepointFrame;
private boolean isTransactionStarted = false;
private Hashtable savepointsCreated = new Hashtable();
private boolean isTransferStarted = false;
Savepoint firstSavepoint = null;
public SavepointSample() {
savepointFrame = new SavepointFrame(this);
}
public static void main(String arg[]){
SavepointSample savepointSample = new SavepointSample();
savepointSample.dbConnection();
if(savepointSample.conn != null){
savepointSample.displayAllAccounts();
savepointSample.savepointFrame.putStatus(
"Select an account to be updated and click on either Update or Transfer"
+ " to start the transaction.");
}
}
public void dispatchEvent (String eventName) {
if (eventName.equals("SHOW UPDATE")){
this.showAccountDetails();
} else if (eventName.equals("UPDATE ACCOUNT")){
this.updateAccountDetails();
} else if (eventName.equals("TRANSFER ACCOUNT")){
if(isTransferStarted){
this.addAmtToSecondAccount();
} else { isTransferStarted = false;
this.tranferAmount();
}
} else if (eventName.equals("TRANSFER CANCELLED")){
this.transferCancelled();
} else if (eventName.equals("ROLLBACK")){
this.transactionRollback();
} else if (eventName.equals("SET SAVEPOINT")){
this.createSavepoint();
} else if (eventName.equals("COMPLETE ROLLBACK")){
this.completeRollback();
} else if (eventName.equals("COMMIT")){
this.commitTransaction();
} else if (eventName.equals("EXIT")){
this.exitApplication();
}
}
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 dbConnection() {
try {
savepointFrame.putStatus("Trying to connect to the Database");
Properties prop = this.loadParams("Connection");
OracleDataSource ods = new OracleDataSource();
this.configureDataSource(ods, prop);
conn = ods.getConnection();
conn.setAutoCommit(false);
} catch(SQLException ex) { System.out.println(
"Error in Connecting to the Database "+'\n'+ex.toString());
} catch(IOException ex) { System.out.println(
"Error in reading the properties file "+'\n'+ex.toString());
}
}
private void displayAllAccounts() {
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Account_Number, "
+ "INITCAP(Customer_Name), Balance FROM Account_Master "
+ "ORDER BY Account_Number");
while(rs.next()){
savepointFrame.addToAccountTable(rs.getString(1), rs.getString(2),
rs.getString(3));
}
savepointFrame.enableFrame();
} catch(Exception excep){ savepointFrame.putStatus("Error while retrieving Account details : "
+ excep.toString());
} finally {
try {
if(stmt != null) stmt.close();
} catch(Exception excep) {
savepointFrame.putStatus("Error while closing Statement. : "
+ excep.toString());
}
}
}
private void showAccountDetails() {
ArrayList accountDetailsArr = savepointFrame.getSelectedAccountDetails();
float previousBalance = this.getAccountBalance(
Integer.parseInt(accountDetailsArr.get(0).toString()));
try {
savepointFrame.frmUpdate.displayAccountDetails( accountDetailsArr.get(0).toString(),
accountDetailsArr.get(1).toString(),
previousBalance
);
} catch(Exception excep){ savepointFrame.putStatus("Error while displaying Account Details : "
+ excep.toString());
}
}
private void updateAccountDetails(){
PreparedStatement pstmt=null;
try {
String transaction = savepointFrame.getTransactionType();
pstmt = conn.prepareStatement(" UPDATE Account_Master"
+ " SET Balance = ?"
+ " WHERE Account_Number = ? ");
float balance = savepointFrame.getBalance();
if(transaction.equals(savepointFrame.frmUpdate.transactionTypes[0])){
balance += savepointFrame.getAmount();
}else if(transaction.equals(savepointFrame.frmUpdate.transactionTypes[1])){
balance -= savepointFrame.getAmount();
}
pstmt.setFloat(1, balance);
pstmt.setInt(2, savepointFrame.getAccountNumber());
int i = pstmt.executeUpdate();
this.refreshAccountsTable();
this.enableTransactionBtns();
savepointFrame.putStatus("Account with id "+savepointFrame.getAccountNumber()
+ " is updated.");
} catch(Exception excep){ savepointFrame.putStatus("Error while updating account details: "
+ excep.toString());
} finally {
try {
if(pstmt != null) pstmt.close();
} catch(Exception excep) {
savepointFrame.putStatus("Error while closing Prepared Statement. : "
+ excep.toString());
}
}
}
private void tranferAmount(){
PreparedStatement pstmt=null;
try {
int fromAccountNo = savepointFrame.frmTransfer.getFromAccountNo();
float amount = savepointFrame.frmTransfer.getAmountTransfered();
firstSavepoint = conn.setSavepoint("beforeTransfer");
try{
pstmt = conn.prepareStatement(" UPDATE Account_Master"
+ " SET Balance = Balance - ?"
+ " WHERE Account_Number = ? ");
pstmt.setFloat(1, amount);
pstmt.setInt(2, fromAccountNo);
int i = pstmt.executeUpdate();
}catch(Exception exception){
conn.rollback(firstSavepoint);
return;
}
this.addAmtToSecondAccount();
} catch(Exception excep){ savepointFrame.putStatus("Error while transferring amt from first account : "
+ excep.toString());
} finally {
try {
if(pstmt != null) pstmt.close();
} catch(Exception excep) {
savepointFrame.putStatus("Error while closing Prepared Statement. : "
+ excep.toString());
}
}
}
private void addAmtToSecondAccount(){
PreparedStatement pstmt = null;
try {
int toAccountNo = savepointFrame.frmTransfer.getToAccountNo();
float amount = savepointFrame.frmTransfer.getAmountTransfered();
Savepoint secondSavepoint = conn.setSavepoint("afterTransfer");
try{
pstmt = conn.prepareStatement( " UPDATE Account_Master"
+ " SET Balance = Balance + ?"
+ " WHERE Account_Number = ? ");
pstmt.setFloat(1, amount);
pstmt.setInt(2, toAccountNo);
int i = pstmt.executeUpdate();
if(i == 0){
throw new SQLException();
}
}catch(SQLException sqlException){
conn.rollback(secondSavepoint);
isTransferStarted = true;
savepointFrame.callTransferFrame(amount);
return;
}
this.refreshAccountsTable();
firstSavepoint = null;
secondSavepoint = null;
this.enableTransactionBtns();
savepointFrame.putStatus("Transfer between accounts "
+ savepointFrame.frmTransfer.getFromAccountNo()
+ ", " + toAccountNo + " is done.");
} catch(Exception excep){ savepointFrame.putStatus("Error while updating account details: "
+ excep.toString());
} finally {
try {
if(pstmt != null) pstmt.close();
} catch(Exception excep) {
savepointFrame.putStatus("Error while closing Prepared Statement. : "
+ excep.toString());
}
}
}
private void transferCancelled(){
try{
if(isTransferStarted){
isTransferStarted = false;
conn.rollback(firstSavepoint);
firstSavepoint = null;
}
savepointFrame.putStatus("Transfer between accounts is cancelled.");
}catch(Exception excep){ savepointFrame.putStatus("Error while canceling transfer: "
+ excep.toString());
}
}
private void createSavepoint(){
try{
Savepoint savepoint = conn.setSavepoint();
savepointsCreated.put(new Integer(savepoint.getSavepointId()),savepoint);
savepointFrame.addToLogTable(savepoint.getSavepointId());
if(!savepointFrame.rollbackButton.isEnabled()){
savepointFrame.enableTransactionButtons();
}
savepointFrame.putStatus(" Savepoint with id "+savepoint.getSavepointId()
+ " is created");
}catch(Exception excep){
savepointFrame.putStatus("Error while creating a Savepoint: "
+ excep.toString());
}
}
private void transactionRollback(){
try{
ArrayList selectedLogDetails = savepointFrame.getSelectedLogDetails();
int selectedSavepointId = Integer.parseInt(selectedLogDetails.get(0).toString());
Savepoint savepoint = (Savepoint)savepointsCreated.get(new Integer(
selectedSavepointId));
conn.rollback(savepoint);
this.refreshAccountsTable();
int selectedRow = savepointFrame.logTable.getSelectedRow();
savepointFrame.deleteRowsFromLogTable(selectedRow);
savepointFrame.putStatus("The transaction is rolled back up to the point selected");
savepointFrame.lblLog.setText("Transaction Rolledback");
}catch(Exception excep){
savepointFrame.putStatus("Error while trying to rollback the transaction: "
+ excep.toString());
}
}
private void completeRollback(){
try {
conn.rollback();
this.refreshAccountsTable();
this.removeTransactionDetails("Transaction Rolled back");
savepointFrame.putStatus("The transaction is rolled back completely");
}catch (Exception excep){ savepointFrame.putStatus(" Error when rolling back the complete transaction: "
+ excep.toString());
}
}
private void commitTransaction(){
try{
conn.commit();
this.removeTransactionDetails("Transaction Committed");
savepointFrame.putStatus("The transaction is committed.");
}catch(Exception excep){
savepointFrame.putStatus("Error while committing the transaction: "
+ excep.toString());
}
}
private float getAccountBalance(int accountNumber){
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("SELECT Balance FROM "
+ "Account_Master WHERE Account_Number = ?");
pstmt.setInt(1,accountNumber);
ResultSet rs = pstmt.executeQuery();
rs.next();
return (rs.getFloat(1));
} catch(Exception excep){ savepointFrame.putStatus("Error while retrieving Balance details : "
+ excep.toString());
return -1;
} finally {
try {
if(pstmt != null) pstmt.close();
} catch(Exception excep) {
savepointFrame.putStatus("Error while closing Prepared Statement. : "
+ excep.toString());
}
}
}
private void removeTransactionDetails(String logLbl){
savepointsCreated.clear();
savepointFrame.clearLogTable();
isTransactionStarted = false;
savepointFrame.lblLog.setText(logLbl);
savepointFrame.disableTransactionbuttons();
}
private void refreshAccountsTable(){
savepointFrame.clearAccountsTable();
this.displayAllAccounts();
}
private void enableTransactionBtns(){
if(!isTransactionStarted){
savepointFrame.lblLog.setText("Transaction Started");
isTransactionStarted = true;
savepointFrame.completeRollbackButton.setEnabled(true);
savepointFrame.completeRollbackButton.setToolTipText(
savepointFrame.completeRollbackBtnToolTip);
}
savepointFrame.savepointButton.setEnabled(true);
savepointFrame.savepointButton.setToolTipText(
savepointFrame.savepointBtnToolTip);
savepointFrame.commitButton.setEnabled(true);
savepointFrame.commitButton.setToolTipText(savepointFrame.commitBtnToolTip);
}
private void configureDataSource(OracleDataSource ods, Properties prop) {
ods.setDriverType("thin");
ods.setDatabaseName((String)prop.get("Database"));
ods.setServerName((String)prop.get("HostName"));
ods.setPortNumber(Integer.parseInt((String)prop.get("Port")));
ods.setUser((String)prop.get("UserName"));
ods.setPassword((String)prop.get("Password"));
}
void exitApplication(){
if (conn != null) {
try {
conn.rollback();
conn.close();
conn = null;
}catch (Exception excep){ savepointFrame.putStatus(" Error while Closing the connection: "
+ excep.toString());
}
}
System.exit(0);
}
}
|