/
Atm.java
720 lines (637 loc) · 27.4 KB
/
Atm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
import java.io.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.*;
import java.lang.ClassNotFoundException;
import java.lang.Double;
import java.lang.IllegalAccessException;
import java.lang.InstantiationException;
import java.lang.Integer;
import java.lang.String;
import java.lang.StringBuffer;
import java.lang.StringBuilder;
import java.lang.SuppressWarnings;
import java.lang.reflect.Array;
import java.util.*;
import java.util.ArrayList;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import javax.swing.*;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import java.awt.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
public class Atm extends JFrame implements Serializable {
private ArrayList<Customer> cust;
private ArrayList<AdminLog> adminLogs = new ArrayList<AdminLog>(100);
private int starting_account_number = 1001;
private int starting_customer_number = 101;
private String admin_pin;
private int interest_rate;
private int transaction_counter = 0;
private String id;
private RunningFrame jf = null;
private AdminRunningFrame ajf = null;
private String pin;
private boolean found = false;
private String depositAmount;
private Customer customer = null;
private long timestamp;
private static ArrayList<Integer> allIDs;
private static Date date = new Date();
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
private File DBfile = new File("p2.dat");
private File logFile = new File("p2.log");
static final long serialVersionUID = -3005023205032780691L;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
ConsoleReader console = new ConsoleReader(System.in);
public Atm() // constructor
// sets the customer array to that found in the file if the file exists
{
try {
// Set cross-platform Java L&F (also called "Metal")
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
}
catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
if (logFile.exists()) {
try {
adminLogs = returnLog("p2.log");
if (!adminLogs.isEmpty()) {
// there may be customer data but perhaps no transactions yet.
ArrayList<Integer> allTransactions = new ArrayList<>(100);
for (AdminLog a : adminLogs) {
int transaction = a.getTransactionID();;
allTransactions.add(transaction);
}
transaction_counter = Collections.max(allTransactions) + 1;
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
if (DBfile.exists()) {
try {
cust = returnSavedData("p2.dat");
// sets the starting ID to the max of all the IDs stored in the file.
allIDs = new ArrayList<Integer>(100);
ArrayList<Integer> allAccounts = new ArrayList<>();
for (Customer customer : cust) {
String idString = customer.returnID();
int id = Integer.parseInt(idString);
allIDs.add(id);
int accountNumber = customer.returnMaxAccount();
allAccounts.add(accountNumber);
}
// checks to see if the customer has even made any accounts, if not, max accounts will be set at 1001
if (starting_account_number != 1) {
starting_account_number = Collections.max(allAccounts) + 1;
}
starting_customer_number = Collections.max(allIDs) + 1;
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
} else {
cust = new ArrayList<>(100);
// creates the file if it does not exist
try {
saveFile(cust, DBfile);
} catch (IOException e) {
e.printStackTrace();
}
}
interest_rate = 5;
}
public void model_admin() {
if (ajf != null) {
ajf.dispose();
}
if (jf != null) {
jf.dispose();
}
ajf = new AdminRunningFrame(this);
ajf.startPage();
if (DBfile.exists()) {
try {
cust = returnSavedData("p2.dat");
if (cust.isEmpty()) {
ajf.errorMessage("There are no customers in this database.");
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
if (logFile.exists()) {
try {
adminLogs = returnLog("p2.log");
if (adminLogs.isEmpty()) {
ajf.errorMessage("No entries have been found!");
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
}
public void printByCustomerName() {
// Prints the database info by customer's name in ascending order
Collections.sort(cust, Customer.CompareName);
ajf.dispose();
ajf = new AdminRunningFrame(this);
StringBuilder stringResults = new StringBuilder();
String header = header();
stringResults.append(header);
if (!cust.isEmpty()) {
for (Customer customer : cust) {
String id = customer.returnID();
String name = customer.getName().toUpperCase();
String pin = customer.returnPin();
ArrayList<Account> accounts = customer.getAccounts();
if (!accounts.isEmpty()) {
for (Account account : accounts) {
if (account.checkActive()) {
String accountNumber = account.returnNumber();
double balance = account.returnBalance();
String balanceAsString = formatter.format(balance);
String customerInfo = printAdminInfo(name, id, accountNumber, pin, balanceAsString);
stringResults.append(customerInfo);
}
}
} else {
// Still prints customers who have created customer accounts but not set up any checking/savings
String noAccounts = String.format("%-20s %-9s %-10s\n", name, id, pin);
stringResults.append(noAccounts);
}
}
}
String resultsAsString = stringResults.toString();
ajf.printInfo(resultsAsString);
}
public void printHighestBalance() {
// prints the accounts from highest amount to lowest, with those who have empty accounts last
ajf.dispose();
ajf = new AdminRunningFrame(this);
StringBuilder stringResults = new StringBuilder();
String header = header();
stringResults.append(header);
if (!cust.isEmpty()) {
ArrayList<Account> allAccounts = new ArrayList<Account>();
ArrayList<Customer> CustomersNoAccounts = new ArrayList<Customer>();
for (Customer c : cust) {
ArrayList<Account> accounts = c.getAccounts();
if (!accounts.isEmpty()) {
// Concatenates all the accounts together for easy sorting
allAccounts.addAll(accounts);
}
// Adds customers without accounts to a separate list to be printed at the end of all the others
else {
CustomersNoAccounts.add(c);
}
}
if (!allAccounts.isEmpty()) {
Collections.sort(allAccounts, Account.CompareBalances);
for (Account a : allAccounts) {
if (a.checkActive()) {
String id = a.getID();
String name = a.getName().toUpperCase();
String pin = a.getPin();
String accountNumber = a.returnNumber();
double balance = a.returnBalance();
String balanceAsString = formatter.format(balance);
String customerInfo = printAdminInfo(name, id, accountNumber, pin, balanceAsString);
stringResults.append(customerInfo);
}
}
}
if (!CustomersNoAccounts.isEmpty()) {
Collections.sort(CustomersNoAccounts, Customer.CompareName);
for (Customer c : CustomersNoAccounts) {
String id = c.returnID();
String name = c.getName().toUpperCase();
String pin = c.returnPin();
String noAccounts = String.format("%-20s %-9s %-10s\n", name, id, pin);
stringResults.append(noAccounts);
}
}
String resultsAsString = stringResults.toString();
ajf.printInfo(resultsAsString);
}
}
public void model_printAllAccounts() {
ArrayList<String> cusIDs = new ArrayList<String>(100);
cusIDs.add("Accounts:");
Collections.sort(cust, Customer.CompareIDs);
for (Customer c: cust) {
String id = c.returnID();
cusIDs.add(id);
}
if (ajf != null) {
ajf.dispose();
}
ajf = new AdminRunningFrame(this);
ajf.showOneCustomerScreen(cusIDs);
}
public void printAllAccounts(String customerID) {
// Sorts the customer based on ID, then prints the accounts information
// change the withdrawal funcitons and deposit functions too
ajf.dispose();
ajf = new AdminRunningFrame(this);
Collections.sort(cust, Customer.CompareIDs);
String searchString = ajf.getCustomerID();
StringBuilder stringResults = new StringBuilder();
String header = header();
stringResults.append(header);
for (Customer customer : cust) {
String id = customer.returnID();
String name = customer.getName().toUpperCase();
String pin = customer.returnPin();
if (searchString.equals(id)) {
ArrayList<Account> accounts = customer.getAccounts();
if (!accounts.isEmpty()) {
for (Account account : accounts) {
if (account.checkActive()) {
String accountNumber = account.returnNumber();
double balance = account.returnBalance();
String balanceAsString = formatter.format(balance);
String customerInfo = printAdminInfo(name, id, accountNumber, pin, balanceAsString);
stringResults.append(customerInfo);
}
}
}
}
}
String resultsAsString = stringResults.toString();
ajf.printInfo(resultsAsString);
}
public void printTimeStamp() {
ajf.dispose();
ajf = new AdminRunningFrame(this);
StringBuilder stringResults = new StringBuilder();
// creates a new header
String Tim = "[Time Stamp]";
String transID = "[Transaction ID]";
String CusID = "[ID #]";
String CusAcct = "[Account #]";
String transAmount = "[Amount]";
String header = String.format("%-30s %-20s %-10s %10s %10s\n", Tim, transID, CusID, CusAcct, transAmount);
stringResults.append(header);
if (cust.isEmpty()) {
ajf.errorMessage("There are no customers in this database."); }
if (adminLogs.isEmpty()) {
ajf.errorMessage("No entries have been found!");
} else {
Collections.sort(adminLogs, AdminLog.CompareTimeStamp);
for (AdminLog a: adminLogs) {
long timestamp = a.getTimestamp();
String date = dateFormat.format(timestamp);
int transactionID = a.getTransactionID();
String customerID = a.getCustomerID();
String accountID = a.getAccountNum();
double amount = a.getAmount();
String newLine = String.format("%-30s %-20d %-10s %10s %10s\n", date, transactionID, customerID, accountID, amount);
stringResults.append(newLine);
}
String resultsAsString = stringResults.toString();
ajf.printInfo(resultsAsString);
}
}
public String header() {
// Prints the header
String CusName = "[Customer Name]";
String CusID = "[ID #]";
String CusAcct = "[Account #]";
String CusPin = "[Pin #]";
String CusBal = "[Current Balance]";
String result = String.format("%-20s %-20s %-10s %10s %18s\n", CusName, CusID, CusPin, CusAcct, CusBal);
return result;
}
public String printAdminInfo(String name, String id, String accountNumber, String pin, String balanceAsString) {
// Prints the data from each account
String result = String.format("%-20s %-20s %-10s %10s %18s\n", name, id, pin, accountNumber, balanceAsString);
return result;
}
@SuppressWarnings("unchecked")
public static ArrayList<Customer> returnSavedData(String filename) throws IOException, ClassNotFoundException {
ArrayList<Customer> obj = new ArrayList<Customer>();
FileInputStream fileinput = new FileInputStream(filename);
ObjectInputStream inObj = new ObjectInputStream(fileinput);
obj = (ArrayList) inObj.readObject();
inObj.close();
fileinput.close();
return obj;
}
@SuppressWarnings("unchecked")
public static ArrayList<AdminLog> returnLog(String filename) throws IOException, ClassNotFoundException {
ArrayList<AdminLog> obj = new ArrayList<AdminLog>();
FileInputStream fileinput = new FileInputStream(filename);
ObjectInputStream inObj = new ObjectInputStream(fileinput);
obj = (ArrayList) inObj.readObject();
inObj.close();
fileinput.close();
return obj;
}
public void saveFile(ArrayList<? extends Serializable> objectArray, File fileName)throws IOException {
if (!fileName.exists()) {
fileName.createNewFile();
}
FileOutputStream fileoutput = new FileOutputStream(fileName);
ObjectOutputStream output = new ObjectOutputStream(fileoutput);
output.writeObject(objectArray);
output.close();
fileoutput.close();
}
private void validate_info(String newUserID, String newPin) {
// validates that the customer has put in the correct Customer name and PIN
if (newPin == null || newPin.length() != 4) {
// returns the Customer object right away if the pin number is wrong, which will cause
// the functions defined below to just pass through without doing anything
pin = newPin;
} else {
// Validate user information
for (Customer c : cust) {
// Checks to see if the customer is already in the database
String possibleCustID = c.returnID();
if (possibleCustID.equals(newUserID)) {
found = true;
String possibleCustPIN = c.returnPin(); // Sets possible customer PIN for validation
if (possibleCustPIN.equals(newPin)) {
customer = c;
pin = newPin;
}
pin = newPin; // so if customer ends up being null but the pin still has value, then the pin was incorrect
}
}
}
if (!found) { // calls the correct warning message if either the customer or pin is not correct
if (pin == null) {
jf.errorMessage("That customer is not in our database.");
} else {
jf.errorMessage("Invalid PIN number."); // if the customer has not been found but the pin has been set that means the pin was invalid
}
}
}
public void model_create_account() {
jf.dispose();
jf = new RunningFrame(this);
jf.createAccountScreen();
}
public void create_account(String name, String newPin){
// Actually creates the customer account
Customer customer = new Customer(starting_customer_number, newPin, name);
cust.add(customer);
String newCusID = customer.returnID();
String idString = String.format("Your new Customer ID is: %s\n", newCusID);
transaction_counter++;
add_interest();
try {
saveFile(cust, DBfile);
} catch (IOException e) {
e.printStackTrace();
}
jf.displayInfo(idString);
}
public void model_open_account(String customerID, String customerPIN) {
// calls the openAccountScreen function in RunningFrame class
validate_info(customerID, customerPIN);
if (customer != null) {
jf.dispose();
jf = new RunningFrame(this);
jf.openAccountScreen();
}
}
public void open_account(boolean save){
// actually opens the account
customer.addAccount(starting_account_number, save); // addAccount will create a new account based on whether it is savings/checkings
StringBuilder text = new StringBuilder();
text.append("<html>Account created!<br>");
String result = customer.returnInfo();
String subResult = result.substring(6);
text.append(subResult);
String infoText = text.toString();
jf.displayInfo(infoText);
transaction_counter++;
add_interest();
try {
saveFile(cust, DBfile);
saveFile(adminLogs, logFile);
} catch (IOException e) {
e.printStackTrace();
}
customer = null; // resets the customer and account after each transaction
pin = null;
}
public void model_deposit(String customerID, String customerPIN) {
// calls the depositScreen from the RunningFrame class
validate_info(customerID, customerPIN);
if (customer != null) {
jf.dispose();
jf = new RunningFrame(this);
String result = customer.returnInfo();
ArrayList<String> allAccounts = customer.getAllAccounts();
jf.depositScreen(result, allAccounts);
}
}
public void deposit(String accountNum, String depositAmount) {
// actually deposits the appropriate amount into the account
double deposit = Double.parseDouble(depositAmount); // the balance in the Account class is saved as a double so it must be converted here
boolean accountFound = customer.addMoney(deposit, accountNum);
if (accountFound == true) {
// create the log file
timestamp = date.getTime();
String customerID = customer.returnID();
AdminLog newTransaction = new AdminLog(timestamp, transaction_counter, customerID, accountNum, deposit);
adminLogs.add(newTransaction);
transaction_counter++;
add_interest();
String infoMessage = customer.builderToString();
jf.displayInfo(infoMessage);
try {
saveFile(cust, DBfile);
saveFile(adminLogs, logFile);
} catch (IOException e) {
e.printStackTrace();
}} else {
jf.errorMessage("We cannot find that account number in our database"); // pops up an error message if the account was not found
}
customer = null; // resets the customer and account after each transaction
pin = null;
}
public void model_withdraw(String customerID, String customerPIN) {
// calls the withdrawal screen from the RunningFrame class
validate_info(customerID, customerPIN);
if (customer != null) {
jf.dispose();
jf = new RunningFrame(this);
String result = customer.returnInfo();
ArrayList<String> allAccounts = customer.getAllAccounts();
jf.withdrawalScreen(result, allAccounts);
}
}
public void withdraw(String withdrawAmount, String accountNum) {
// actually performs the withdrawal service
double withdrawal = Double.parseDouble(withdrawAmount);
boolean accountFound = customer.removeMoney(withdrawal, accountNum);
if (accountFound == true) {
// creates the log file
double logAmount = -withdrawal;
timestamp = date.getTime();
String customerID = customer.returnID();
AdminLog newTransaction = new AdminLog(timestamp, transaction_counter, customerID, accountNum, logAmount);
adminLogs.add(newTransaction);
transaction_counter++;
add_interest();
String infoMessage = customer.builderToString();
jf.displayInfo(infoMessage);
try {
saveFile(cust, DBfile);
saveFile(adminLogs, logFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
jf.errorMessage("We cannot find that account number in our database"); // pops up an error message if the account was not found
}
customer = null; // resets the customer and account after each transaction
pin = null;
}
public void model_transfer(String customerID, String customerPIN) {
// calls the transfer screen from the RunningFrame class
validate_info(customerID, customerPIN);
if (customer != null) {
jf.dispose();
jf = new RunningFrame(this);
String result = customer.returnInfo();
ArrayList<String> allAccounts = customer.getAllAccounts();
jf.transferScreen(result, allAccounts);
}
}
public void transfer(String transferAmount, String accountFrom, String accountTo) {
// actually transfers the model
double transferDouble = Double.parseDouble(transferAmount);
boolean accountFromFound = customer.removeMoney(transferDouble, accountFrom);
boolean accountToFound = customer.addMoney(transferDouble, accountTo);
if (accountFromFound == true && accountToFound == true) {
// creates the log file
double logAmount = -transferDouble;
timestamp = date.getTime();
String customerID = customer.returnID();
AdminLog firstTransaction = new AdminLog(timestamp, transaction_counter, customerID, accountFrom, transferDouble);
timestamp = date.getTime();
AdminLog secondTransaction = new AdminLog(timestamp, transaction_counter, customerID, accountTo, logAmount);
adminLogs.add(firstTransaction);
adminLogs.add(secondTransaction);
for (AdminLog a : adminLogs) {
long timestampe = a.getTimestamp();
}
transaction_counter++;
add_interest();
String infoMessage = customer.transferMessage(accountFrom, accountTo, transferDouble);
jf.displayInfo(infoMessage);
try {
saveFile(cust, DBfile);
saveFile(adminLogs, logFile);
} catch (IOException e) {
e.printStackTrace();
}} else {
jf.errorMessage("We cannot find that account number in our database"); // pops up an error message if the account was not found
}
customer = null; // resets the customer and account after each transaction
pin = null;
}
public void model_account_info(String customerID, String customerPIN) {
// calls the transfer screen from the RunningFrame class
validate_info(customerID, customerPIN);
if (customer != null) {
jf.dispose();
jf = new RunningFrame(this);
String text = customer.printAccountInfo();
jf.accountInfoScreen(text, adminLogs, customerID);
}
}
public void model_close_account(String customerID, String customerPIN) {
// calls the transfer screen from the RunningFrame class
validate_info(customerID, customerPIN);
if (customer != null) {
jf.dispose();
jf = new RunningFrame(this);
ArrayList<String> allAccounts = customer.getAllAccounts();
jf.closeAccountScreen(allAccounts);
}
}
public String close_account(String accountNum) {
// actually closes the customer's account and returns a dialog box
customer.removeAccount(accountNum);
String cusInfo = customer.returnInfo();
StringBuilder result = new StringBuilder();
result.append("<html>Deleted account!<br>Updated information:<br>");
String subCusInfo = cusInfo.substring(7, cusInfo.length()); // removes the last html tag from returnInfo()
result.append(subCusInfo);
try {
saveFile(cust, DBfile);
} catch (IOException e) {
e.printStackTrace();
}
customer = null; // resets the customer and account after each transaction
pin = null;
return result.toString();
}
public void add_interest() {
if ((transaction_counter % 5) == 0) {
for (Customer c : cust) {
ArrayList<Tuple> accountsAddedTo = new ArrayList<>(100);
accountsAddedTo = c.addInterestToSavings(interest_rate);
timestamp = date.getTime();
if (!accountsAddedTo.isEmpty()) {
String customerID = c.returnID();
for (Tuple tuple : accountsAddedTo) {
String accountNumber = tuple.getFirst();
double logAmount = tuple.getSecond();
AdminLog newTransaction = new AdminLog(timestamp, transaction_counter, customerID, accountNumber, logAmount);
adminLogs.add(newTransaction);
}
}
try {
saveFile(cust, DBfile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void callStartPage() {
customer = null;
pin = null;
if (ajf != null) {
ajf.dispose();
}
if (jf != null){
jf.dispose();
}
jf = new RunningFrame(this);
jf.startPage();
}
}