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