Thursday, March 12, 2009

Bank Account Manager

package manager;


import model.BankAccount;
import dataaccess.BankAccountDAO;

public class BankAccountMgr {
BankAccountDAO badao=(BankAccountDAO)new BankAccountDAO();
public BankAccount[] retrieveAcctType(String id)throws Exception
{
BankAccountDAO bDAO=new BankAccountDAO();
try{
bDAO.openConnection();
BankAccount[] result=bDAO.retrieveAccType(id);
return result;
}
catch(Exception e)
{
throw e;
}
finally
{
bDAO.closeConnection();
}
}
public boolean updatebalance(String custId,Integer fromaccId,Integer toaccId,Float tranamount,String accounttype)
throws Exception{
BankAccountDAO bDAO=new BankAccountDAO();
boolean b;
try{
bDAO.openConnection();
b=bDAO.updatebalance(custId,fromaccId,toaccId,tranamount,accounttype);
}catch(Exception e)
{
throw e;
}finally
{
bDAO.closeConnection();
}
return b ;
}

public int validateaccount (int accountno) throws Exception{
BankAccountDAO bDAO=new BankAccountDAO();
int result;
try{
bDAO.openConnection();
result = bDAO.validateaccount(accountno);
}
catch(Exception e)
{
throw e;
}finally
{
bDAO.closeConnection();
}
return result ;
}

}

Bank Account DAO

package dataaccess;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.sql.Connection;
import java.util.Calendar;

import model.BankAccount;
import java.sql.ResultSet;

public class BankAccountDAO {
private String driver = "com.mysql.jdbc.Driver";
private String url="jdbc:mysql://localhost:3306/ibanking";
private String user="root";
private String password="password";
private Connection conn;
public void openConnection() throws
ClassNotFoundException,SQLException
{
Class.forName(driver);
conn=(Connection) DriverManager.getConnection(url,user,password);
}
public boolean updatebalance(String custId, Integer fromaccId,Integer toaccId,Float tranamount, String accounttype)
throws Exception{
boolean b;
Calendar cal=Calendar.getInstance();
int dates=cal.get(Calendar.DATE);
int months=cal.get(Calendar.MONTH)+1;
int years=cal.get(Calendar.YEAR);
String str= years+"/" + months +"/"+ dates;
Statement st=conn.createStatement();
//String sql4="Select RoleID from user where UserID='"+id+"'";
//ResultSet rs=st.executeQuery(sql4);
//custId=rs.getString("RoleID");
String sql5="Select CurrentBalance From bankaccount where CustomerId='"+custId+"'and AccountNo='"+fromaccId+"'";
ResultSet rs1=st.executeQuery(sql5);
float CurrentBalance = 0;
while (rs1.next())
{
CurrentBalance=rs1.getFloat(1);
}
if (CurrentBalance>0.0 && tranamount<=CurrentBalance)
{
String sql1="update bankaccount set CurrentBalance=CurrentBalance-"+tranamount+ "where CustomerId='"+custId+"'and AccountNo='"+fromaccId+"'";
String sql3="update bankaccount set CurrentBalance=CurrentBalance+"+tranamount+ "where AccountNo='"+toaccId+"'";
//String transferToAccId=null;
//String sql2="INSERT INTO transaction(TransactionID,TransactionCode,myAccountNo,myAccountType,TransferAccountNo,TransferAccountType,TransferAmount,TransferDate)"+"VALUES('"+fromAccId+"'"+","+"'"+transferToAccId+"'"+","+"'"+tranamount+"'"+","+"'"+acctypeId+"')";
String sql2="INSERT INTO transaction(TransactionCode,myAccountNo,myAccountType,TransferAccountNo,TransferAccountType,TransferAmount,TransferDate)VALUES('ITD','"+fromaccId+"','"+accounttype+"','"+toaccId+"','"+accounttype+"','"+tranamount+"',str_to_date('"+str+"','%Y/%m/%d'))";
st.executeUpdate(sql1);
st.executeUpdate(sql2);
st.executeUpdate(sql3);
}
else
{
System.out.println("Transaction is not available");
conn.close();
}
b=true;
st.close();
conn.close();
return b;
}

@SuppressWarnings("unchecked")
public BankAccount[] retrieveAccType(String id) throws Exception{
Statement stmt=conn.createStatement();
String sql="Select AccountNo From bankaccount where CustomerID='"+id+"'";
Vector v=new Vector();
try{
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
BankAccount bact=new BankAccount();
String s=rs.getString("accountno");
bact.setAccountno(Integer.parseInt(s));
//String s1=rs.getString("accounttypeid");
//bact.setAccounttypeid(Integer.parseInt(s1));
v.add(bact);
}
stmt.close();
rs.close();
}catch (Exception e){
//throw new Exception();
System.out.print(e);
}finally
{
try{
System.out.println("Closing connection");
conn.close();
}catch(Exception e){}
}
BankAccount[] result=new BankAccount[v.size()];
result=(BankAccount[])v.toArray(result);
return(result);
}
public void closeConnection()throws ClassNotFoundException, SQLException,InstantiationException,IllegalAccessException {
if (conn!=null)
conn.close();
}
private BankAccount[] FindAccounts(String sql) throws Exception {
Vector v=new Vector();
try{
this.openConnection();
System.out.println("Created connection");
Statement statement=(Statement) conn.createStatement();
System.out.println("Execute query:"+sql);
java.sql.ResultSet rs= (java.sql.ResultSet) statement.executeQuery(sql);
System.out.println("Executed query");
if(rs!=null){
while(rs.next()){
BankAccount obj=new BankAccount();
obj.setAccountno(Integer.parseInt(rs.getString("accountno")));
obj.setPin(rs.getString("pin"));
obj.setAccounttypeid(Integer.parseInt(rs.getString("accounttypeid")));
obj.setCardno(Integer.parseInt(rs.getString("cardno")));
obj.setCurrentbalance(Double.parseDouble(rs.getString("currentbalance")));
obj.setCustomerid(rs.getString("customerid"));
obj.setOpeingdate(rs.getDate("opeingdate"));
v.add(obj);
}
}
else
throw new SQLException();
}
catch(Exception e){
throw e;
}
BankAccount[] result=new BankAccount[v.size()];
result=(BankAccount[])v.toArray(result);
return result;
}

public int validateaccount (int accountno) throws Exception{
Statement stmt=conn.createStatement();
BankAccount ba = new BankAccount();
int result = 0;
String sql="Select AccountNo From bankaccount where accountno = " + accountno + " ";

try{
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
result = 1;
}
stmt.close();

}catch (Exception e){
//throw new Exception();
System.out.print(e);
}finally
{
try{
System.out.println("Closing connection");
conn.close();

}catch(Exception e){}
}
return result;

}
public static void main(String[] args){
BankAccountDAO dao=new BankAccountDAO();
try {
dao.openConnection();
// User u = dao.getUser("123");
// System.out.println(u.getRole()); // show customer
int x = dao.validateaccount(222222222);
System.out.println("--------x is ="+ x);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}


Bank Accouunt Servlet Sample

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import manager.BankAccountMgr;
import manager.CustomerMgr;
import model.BankAccount;
import model.Customer;

public class BankAccountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public BankAccountServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Servlet starting............");
//try {
retrieveAcctType(request,response);
doPost(request, response);
//} catch (Exception e) {
//e.printStackTrace();
//}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
System.out.println("Servlet starting............do post");
updatebalance(request,response);
}catch (Exception e)
{
e.printStackTrace();
}

/*String action =request.getParameter("action");
System.out.println(action);
if(action.equalsIgnoreCase("transfertoother"))
{
try{
initialTransfertoOther(request,response);
}
catch (Exception e)
{
e.printStackTrace();
}
}*/
//if (request.getParameter("T").equals("Transfer"))
// {
//}
}
public void retrieveAcctType(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException
{
//HttpSession session=request.getSession(true);
//String id=request.getAttribute("userid").toString();
//String id=request.getParameter("roleid");
String id="C1";
try{

BankAccountMgr accountmgr=new BankAccountMgr();
BankAccount[] result=(BankAccount[]) accountmgr.retrieveAcctType(id);
request.setAttribute("acctid",result);

RequestDispatcher dispatcher = request.getRequestDispatcher("TransfertoOther.jsp");
dispatcher.forward(request, response);


}
catch(Exception e){
e.printStackTrace();
request.setAttribute("exception", e);
RequestDispatcher disp=request.getRequestDispatcher("ErrorMsgForm.jsp");
disp.forward(request,response);
}

}

public void updatebalance(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException
{
String custId="C1";
// String id=request.getParameter("id");
String facctid= request.getParameter("fromAccount");
System.out.println(facctid);
String tacctid=request.getParameter("transferToAccountId");
String tamount=request.getParameter("transferAmount");
String accounttype=request.getParameter("atype");
Float tranamount;
Integer fromaccId,toaccId;
int resultvalidate = 0;
BankAccountMgr accountmgr=new BankAccountMgr();
try{

resultvalidate = accountmgr.validateaccount(Integer.parseInt(request.getParameter("transferToAccountId")));}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if (resultvalidate == 1)
{
try{
fromaccId=Integer.parseInt(facctid);
toaccId=Integer.parseInt(tacctid);
tranamount=Float.parseFloat(tamount);
try{
//BankAccountMgr accountmgr=new BankAccountMgr();
boolean result=accountmgr.updatebalance(custId, fromaccId,toaccId,tranamount,accounttype);
if(result ==true)
{
RequestDispatcher disp=request.getRequestDispatcher("TranMsgForm.jsp");
disp.forward(request,response);
}
}
catch(Exception e){
e.printStackTrace();
request.setAttribute("exception", e);
RequestDispatcher disp= request.getRequestDispatcher("ErrorMsgForm.jsp");
disp.forward(request,response);
}
}catch(NumberFormatException nfe)
{
PrintWriter out=response.getWriter();
out.println("error");
}
}
else
{
PrintWriter out=response.getWriter();
out.println("Transfer to account not found");
}
}

/*private void initialTransfertoOther(HttpServletRequest request,HttpServletResponse response)throws Exception{
try
{
//HttpSession session=request.getSession(true);
//String id=request.getAttribute("userid").toString();
String id="C1";
BankAccountMgr accountmgr=new BankAccountMgr();
BankAccount[] result=(BankAccount[]) accountmgr.retrieveAcctType(id);
request.setAttribute("acctid",result);
//BankAccount[] acc=null;
RequestDispatcher dispatcher = request.getRequestDispatcher("TransfertoOther.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("GET Request.No Form Post");

}
catch(Exception e){
e.printStackTrace();
request.setAttribute("exception", e);
RequestDispatcher disp=request.getRequestDispatcher("ErrorMsgForm.jsp");
disp.forward(request,response);
}
}*/
}

Tic Tac Toe Codes example

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace TicTac
{
public class FTicTac : System.Windows.Forms.Form
{
private int[] m_nGameGrid;
private int m_nNextChar;
private Rectangle[] m_rcSquares;
private const int EX = 1;
private const int OH = 2;
private bool m_bDoubleClick = false;

private System.ComponentModel.Container

components = null;

public FTicTac()
{
InitializeComponent();

m_nNextChar = EX;
m_nGameGrid = new int[9];
m_rcSquares = new Rectangle[9];
Size size = new Size( 96, 96 );
for( int j = 0 ; j <>
{
m_rcSquares[j].Size = size;
}
m_rcSquares[0].Offset( 16, 16 );
m_rcSquares[1].Offset( 128, 16 );
m_rcSquares[2].Offset( 240, 16 );
m_rcSquares[3].Offset( 16, 128 );
m_rcSquares[4].Offset( 128, 128 );
m_rcSquares[5].Offset( 240, 128 );
m_rcSquares[6].Offset( 16, 240 );
m_rcSquares[7].Offset( 128, 240 );
m_rcSquares[8].Offset( 240, 240 );
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
private void InitializeComponent()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Name = "FTicTac";
this.Text = "Tic Tac Toe";
}
#endregion

[STAThread] static void Main()
{
Application.Run(new FTicTac());
}

protected override void OnMouseDown( MouseEventArgs e )
{
switch( e.Button )
{
case MouseButtons.Left:
OnLButtonDown( new Point( e.X, e.Y ) );
break;
case MouseButtons.Right:
OnRButtonDown( new Point( e.X, e.Y ) );
break;
}
base.OnMouseDown( e );
}

private void OnLButtonDown( Point p )
{
if( m_bDoubleClick )
{
m_bDoubleClick = false;
return;
}
if( m_nNextChar != EX )
{
return;
}
int nPos = GetRectID( p );
if( nPos == -1 )
{
return;
}
if( m_nGameGrid[nPos] != 0 )
{
return;
}
m_nNextChar = OH;
m_nGameGrid[nPos] = EX;
Graphics g = this.CreateGraphics();
DrawX( g, nPos );
g.Dispose();
CheckForGameOver();
}

private void OnRButtonDown( Point p )
{
if( m_bDoubleClick )
{
m_bDoubleClick = false;
return;
}
if( m_nNextChar != OH )
{
return;
}
int nPos = GetRectID( p );
if( nPos == -1 )
{
return;
}
if( m_nGameGrid[nPos] != 0 )
{
return;
}
m_nNextChar = EX;
m_nGameGrid[nPos] = OH;
Graphics g = this.CreateGraphics();
DrawO( g, nPos );
g.Dispose();
CheckForGameOver();
}

protected override void OnDoubleClick( EventArgs e )
{
m_bDoubleClick = true;
ResetGame();
base.OnDoubleClick( e );
}

protected override void OnPaint( PaintEventArgs pe )
{
Graphics g = pe.Graphics;
DrawBoard( g );
}

private int GetRectID( Point p )
{
for( int i = 0 ; i <>
{
if( m_rcSquares[i].Contains( p ) )
{
return( i );
}
}
return( -1 );
}

private void DrawBoard( Graphics g )
{
Pen myPen = new Pen( Color.Black, 16 );
g.DrawLine( myPen, 120, 16, 120, 336 );
g.DrawLine( myPen, 232, 16, 232, 336 );
g.DrawLine( myPen, 16, 120, 336, 120 );
g.DrawLine( myPen, 16, 232, 336, 232 );
for( int i = 0 ; i <>
{
if( m_nGameGrid[i] == EX )
{
DrawX( g, i );
}
else if( m_nGameGrid[i] == OH )
{
DrawO( g, i );
}
}
myPen.Dispose();
}

private void DrawX( Graphics g, int nPos )
{
Pen myPen = new Pen( Color.Red, 16 );
g.DrawLine( myPen, m_rcSquares[nPos].Left+16, m_rcSquares[nPos].Top+16,
m_rcSquares[nPos].Right-16, m_rcSquares[nPos].Bottom-16 );
g.DrawLine( myPen, m_rcSquares[nPos].Left+16, m_rcSquares[nPos].Bottom-16,
m_rcSquares[nPos].Right-16, m_rcSquares[nPos].Top+16 );
myPen.Dispose();
}

private void DrawO( Graphics g, int nPos )
{
Pen myPen = new Pen( Color.Blue, 16 );
Rectangle rect = new Rectangle();
rect = m_rcSquares[nPos];
rect.Inflate( -16, -16 );
g.DrawEllipse( myPen, rect );
myPen.Dispose();
}

private void ResetGame()
{
m_nNextChar = EX;
for( int j = 0 ; j <>
{
m_nGameGrid[j] = 0;
}
this.Invalidate();
}

private void CheckForGameOver()
{
int nWinner = IsWinner();
switch( nWinner )
{
case 0:
if( IsDraw() )
{
MessageBox.Show( "It's a draw!", "Tic Tac Toe" );
ResetGame();
}
break;
case EX:
MessageBox.Show( "X Wins!", "Tic Tac Toe" );
ResetGame();
break;
case OH:
MessageBox.Show( "O Wins!", "Tic Tac Toe" );
ResetGame();
break;
}
}

private int IsWinner()
{
int[,] nPattern =
{
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 },
{ 0, 3, 6 },
{ 1, 4, 7 },
{ 2, 5, 8 },
{ 0, 4, 8 },
{ 2, 4, 6 }
};

for( int i = 0 ; i <>
{
if( ( m_nGameGrid[nPattern[i,0]] == EX )
&& ( m_nGameGrid[nPattern[i,1]] == EX )
&& ( m_nGameGrid[nPattern[i,2]] == EX ) )
{
return( EX );
}
if( ( m_nGameGrid[nPattern[i,0]] == OH )
&& ( m_nGameGrid[nPattern[i,1]] == OH )
&& ( m_nGameGrid[nPattern[i,2]] == OH ) )
{
return( OH );
}
}
return( 0 );
}

private bool IsDraw()
{
for( int i = 0 ; i <>
{
if( m_nGameGrid[i] == 0 )
{
return( false );
}
}
return( true );
}
}
}