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