Bank.java 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. package com.company;
  2. import java.io.*;
  3. import java.util.ArrayList;
  4. /**
  5. * Класс реализующий "банк"
  6. */
  7. public class Bank {
  8. /**
  9. * Список клиентов банка
  10. */
  11. private static ArrayList<User> users = new ArrayList<>();
  12. /**
  13. * Голова списка счетов банка
  14. */
  15. private static Bill head;
  16. /**
  17. * Счётчик клиентов банка. Обновлятся при добавлении нового клиента или удалении старого счёта.
  18. */
  19. private static int count;
  20. /**
  21. * Наименование банка
  22. */
  23. private static String name;
  24. /**
  25. * Сохранить в файл список всех зарегистрированных клиентов
  26. */
  27. public static void saveClients() {
  28. try {
  29. FileOutputStream fos = new FileOutputStream("clients.bin");
  30. ObjectOutputStream objectOutputStream = new ObjectOutputStream(fos);
  31. objectOutputStream.writeObject(users);
  32. objectOutputStream.close();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. /**
  38. * Загрузить из файла список всех зарегистрированных клиентов
  39. */
  40. public static void loadClients() {
  41. try {
  42. FileInputStream fos = new FileInputStream("clients.bin");
  43. ObjectInputStream objectOutputStream = new ObjectInputStream(fos);
  44. Object o = objectOutputStream.readObject();
  45. ArrayList<?> array;
  46. if (o instanceof ArrayList<?>) {
  47. array = (ArrayList<?>) o;
  48. for (Object object : array) {
  49. if (object instanceof User) {
  50. User user = (User) object;
  51. users.add(user);
  52. }
  53. }
  54. }
  55. for (User u : users) {
  56. System.out.println(u.getUuid());
  57. }
  58. objectOutputStream.close();
  59. } catch (IOException | ClassNotFoundException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. /**
  64. * Сохранить список всех счетов в файл
  65. */
  66. public static void saveBills() {
  67. // Пересчитать количество счетов
  68. count = 0;
  69. Bill current = head;
  70. while (current != null) {
  71. count++;
  72. current = current.next;
  73. }
  74. current = head;
  75. Bill[] bills = new Bill[count];
  76. count = 0;
  77. while (current != null) {
  78. bills[count++] = current;
  79. current = current.next;
  80. }
  81. try {
  82. FileOutputStream fos = new FileOutputStream("bills.bin");
  83. ObjectOutputStream objectOutputStream = new ObjectOutputStream(fos);
  84. objectOutputStream.writeObject(bills);
  85. objectOutputStream.close();
  86. } catch (IOException e) {
  87. e.printStackTrace();
  88. }
  89. }
  90. /**
  91. * Загрузить из файла список всех счетов
  92. */
  93. public static void loadBills() {
  94. try {
  95. FileInputStream fos = new FileInputStream("bills.bin");
  96. ObjectInputStream objectInputStream = new ObjectInputStream(fos);
  97. Object o = objectInputStream.readObject();
  98. if (o instanceof Bill[]) {
  99. Bill[] bills = (Bill[]) o;
  100. Bill current = head;
  101. count = 0;
  102. for (Object object : bills) {
  103. if (object instanceof Bill) {
  104. Bill bill = (Bill) object;
  105. if (count == 0) {
  106. head = bill;
  107. current = head;
  108. count++;
  109. } else {
  110. current.next = bill;
  111. current = current.next;
  112. }
  113. }
  114. }
  115. }
  116. objectInputStream.close();
  117. } catch (IOException | ClassNotFoundException e) {
  118. e.printStackTrace();
  119. }
  120. }
  121. /**
  122. * Возвращает количество клиентов
  123. *
  124. * @return размер списка
  125. */
  126. public static int getClientCount() {
  127. return count;
  128. }
  129. public static void registerUser(User user) {
  130. users.add(user);
  131. }
  132. public static boolean authorizedUser(String login, String password) {
  133. for (User u : users) {
  134. if (u.check(login, password)) {
  135. return true;
  136. }
  137. }
  138. return false;
  139. }
  140. /**
  141. * Возвращает наименование банка
  142. *
  143. * @return название
  144. */
  145. public static String getName() {
  146. return name;
  147. }
  148. /**
  149. * Задать наименование банка
  150. *
  151. * @param name имя банка
  152. */
  153. public static void setName(String name) {
  154. Bank.name = name;
  155. }
  156. /**
  157. * Авторизация клиента в системе
  158. *
  159. * @param bill номер счёта
  160. * @param pin пин-код
  161. * @return true, если данные верны
  162. */
  163. public static boolean authorization(String bill, String pin) {
  164. Bill pointer = head;
  165. while (pointer != null) {
  166. if (pointer.getNumber().equals(bill)) {
  167. if (pointer.checkPincode(pin)) {
  168. return true;
  169. }
  170. }
  171. pointer = pointer.next;
  172. }
  173. return false;
  174. }
  175. /**
  176. * Вставить новый элемент в конец списока (открытие нового счёта)
  177. *
  178. * @param user пользователь, открывающий счёт
  179. * @param balance начальный баланс
  180. * @return регистрационные данные
  181. */
  182. public static SecretData insert(User user, double balance) {
  183. Bill newBill = new Bill(user.getUuid(), balance, count);
  184. if (head == null) {
  185. head = newBill;
  186. } else {
  187. Bill last = head;
  188. while (last.next != null) {
  189. last = last.next;
  190. }
  191. last.next = newBill;
  192. }
  193. count++;
  194. return newBill.getSecretData();
  195. }
  196. /**
  197. * Вставить новый элемент после указанного indexAfter (открытие ранее удалённого счёта)
  198. *
  199. * @param user пользователь, открывающий счёт
  200. * @param indexAfter индекс элемента, после которого будет вставлен новыйа
  201. * @param balance начальный баланс
  202. */
  203. public static void insertAt(User user, int indexAfter, double balance) {
  204. Bill newBill = new Bill(user.getUuid(), balance, count);
  205. Bill current = head;
  206. if (indexAfter > count) {
  207. while (current.next != null) {
  208. current = current.next;
  209. }
  210. } else {
  211. int index = 1;
  212. while (index < indexAfter) {
  213. current = current.next;
  214. index++;
  215. }
  216. newBill.next = current.next;
  217. }
  218. current.next = newBill;
  219. }
  220. /**
  221. * Вывод информации о всех клиентах в консоль
  222. */
  223. public static void showClientsInfo() {
  224. Bill current = head;
  225. System.out.println("\nStart client list info:");
  226. while (current != null) {
  227. System.out.printf("Bill number: %s; Balance: %.2f;\n", current.getNumber(), current.getBalance());
  228. current = current.next;
  229. }
  230. System.out.println("End client list info.\n");
  231. }
  232. /**
  233. * Пополнить баланс (только свой счёт)
  234. *
  235. * @param value пополняемое значение
  236. * @param bill пополняемый номер счёта
  237. */
  238. public static void deposit(double value, String bill) {
  239. Bill current = head;
  240. while (current != null) {
  241. if (bill.equals(current.getNumber())) {
  242. current.deposit(value);
  243. break;
  244. }
  245. current = current.next;
  246. }
  247. }
  248. /**
  249. * Списать баланс
  250. *
  251. * @param value списываемое значение
  252. * @param bill номер счёта для списания
  253. */
  254. public static void withdraw(double value, String bill) {
  255. Bill current = head;
  256. while (current != null) {
  257. if (bill.equals(current.getNumber())) {
  258. current.withdraw(value);
  259. break;
  260. }
  261. current = current.next;
  262. }
  263. }
  264. /**
  265. * Разорвать договор с банком (удалить счёт)
  266. *
  267. * @param bill номер удаляемого счёта
  268. */
  269. public static void delete(String bill) {
  270. Bill current = head;
  271. Bill last = head;
  272. while (current != null) {
  273. if (bill.equals(current.getNumber())) {
  274. last.next = current.next;
  275. break;
  276. }
  277. last = current;
  278. current = current.next;
  279. }
  280. }
  281. }