01: import java.io.InputStream;
02: import java.io.IOException;
03: import java.io.OutputStream;
04: import java.io.PrintWriter;
05: import java.net.Socket;
06: import java.util.Scanner;
07: 
08: /**
09:    Executes Simple Bank Access Protocol commands
10:    from a socket.
11: */
12: public class BankService implements Runnable
13: {
14:    /**
15:       Constructs a service object that processes commands
16:       from a socket for a bank.
17:       @param aSocket the socket
18:       @param aBank the bank
19:    */
20:    public BankService(Socket aSocket, Bank aBank)
21:    {
22:       s = aSocket;
23:       bank = aBank;
24:    }
25: 
26:    public void run()
27:    {
28:       try
29:       {
30:          try
31:          {
32:             in = new Scanner(s.getInputStream());
33:             out = new PrintWriter(s.getOutputStream());
34:             doService();            
35:          }
36:          finally
37:          {
38:             s.close();
39:          }
40:       }
41:       catch (IOException exception)
42:       {
43:          exception.printStackTrace();
44:       }
45:    }
46: 
47:    /**
48:       Executes all commands until the QUIT command or the
49:       end of input.
50:    */
51:    public void doService() throws IOException
52:    {      
53:       while (true)
54:       {  
55:          if (!in.hasNext()) return;
56:          String command = in.next();
57:          if (command.equals("QUIT")) return;         
58:          else executeCommand(command);
59:       }
60:    }
61: 
62:    /**
63:       Executes a single command.
64:       @param command the command to execute
65:    */
66:    public void executeCommand(String command)
67:    {
68:       int account = in.nextInt();
69:       if (command.equals("DEPOSIT"))
70:       {
71:          double amount = in.nextDouble();
72:          bank.deposit(account, amount);
73:       }
74:       else if (command.equals("WITHDRAW"))
75:       {
76:          double amount = in.nextDouble();
77:          bank.withdraw(account, amount);
78:       }      
79:       else if (!command.equals("BALANCE"))
80:       {
81:          out.println("Invalid command");
82:          out.flush();
83:          return;
84:       }
85:       out.println(account + " " + bank.getBalance(account));
86:       out.flush();
87:    }
88: 
89:    private Socket s;
90:    private Scanner in;
91:    private PrintWriter out;
92:    private Bank bank;
93: }