Bank.java 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. /**
  133. * Авторизация пользователя
  134. *
  135. * @param login введеный логин
  136. * @param password введеный пароль
  137. * @return null или объект пользователя
  138. */
  139. public static User authorizedUser(String login, String password) {
  140. for (User u : users) {
  141. if (u.check(login, password)) {
  142. return u;
  143. }
  144. }
  145. return null;
  146. }
  147. /**
  148. * Возвращает наименование банка
  149. *
  150. * @return название
  151. */
  152. public static String getName() {
  153. return name;
  154. }
  155. /**
  156. * Задать наименование банка
  157. *
  158. * @param name имя банка
  159. */
  160. public static void setName(String name) {
  161. Bank.name = name;
  162. }
  163. /**
  164. * Авторизация клиента в системе
  165. *
  166. * @param bill номер счёта
  167. * @param pin пин-код
  168. * @return true, если данные верны
  169. */
  170. public static boolean authorization(String bill, String pin) {
  171. Bill pointer = head;
  172. while (pointer != null) {
  173. if (pointer.getNumber().equals(bill)) {
  174. if (pointer.checkPincode(pin)) {
  175. return true;
  176. } else {
  177. return false;
  178. }
  179. }
  180. pointer = pointer.next;
  181. }
  182. return false;
  183. }
  184. /**
  185. * Вставить новый элемент в конец списока (открытие нового счёта)
  186. *
  187. * @param user пользователь, открывающий счёт
  188. * @param balance начальный баланс
  189. * @return регистрационные данные
  190. */
  191. public static SecretData insert(User user, double balance) {
  192. Bill newBill = new Bill(user.getUuid(), balance, count);
  193. if (head == null) {
  194. head = newBill;
  195. } else {
  196. Bill last = head;
  197. while (last.next != null) {
  198. last = last.next;
  199. }
  200. last.next = newBill;
  201. }
  202. count++;
  203. return newBill.getSecretData();
  204. }
  205. /**
  206. * Вставить новый элемент после указанного indexAfter (открытие ранее удалённого счёта)
  207. *
  208. * @param user пользователь, открывающий счёт
  209. * @param indexAfter индекс элемента, после которого будет вставлен новыйа
  210. * @param balance начальный баланс
  211. */
  212. public static void insertAt(User user, int indexAfter, double balance) {
  213. Bill newBill = new Bill(user.getUuid(), balance, count);
  214. Bill current = head;
  215. if (indexAfter > count) {
  216. while (current.next != null) {
  217. current = current.next;
  218. }
  219. } else {
  220. int index = 1;
  221. while (index < indexAfter) {
  222. current = current.next;
  223. index++;
  224. }
  225. newBill.next = current.next;
  226. }
  227. current.next = newBill;
  228. }
  229. /**
  230. * Вывод информации о всех клиентах в консоль
  231. */
  232. public static void showClientsInfo() {
  233. Bill current = head;
  234. System.out.println("\nStart client list info:");
  235. while (current != null) {
  236. System.out.printf("Bill number: %s; Balance: %.2f;\n", current.getNumber(), current.getBalance());
  237. current = current.next;
  238. }
  239. System.out.println("End client list info.\n");
  240. }
  241. /**
  242. * Пополнить баланс (только свой счёт)
  243. *
  244. * @param value пополняемое значение
  245. * @param bill пополняемый номер счёта
  246. */
  247. public static void deposit(double value, String bill) {
  248. Bill current = head;
  249. while (current != null) {
  250. if (bill.equals(current.getNumber())) {
  251. current.deposit(value);
  252. break;
  253. }
  254. current = current.next;
  255. }
  256. }
  257. /**
  258. * Списать баланс
  259. *
  260. * @param value списываемое значение
  261. * @param bill номер счёта для списания
  262. */
  263. public static void withdraw(double value, String bill) {
  264. Bill current = head;
  265. while (current != null) {
  266. if (bill.equals(current.getNumber())) {
  267. current.withdraw(value);
  268. break;
  269. }
  270. current = current.next;
  271. }
  272. }
  273. /**
  274. * Разорвать договор с банком (удалить счёт)
  275. *
  276. * @param bill номер удаляемого счёта
  277. */
  278. public static void delete(String bill) {
  279. Bill current = head;
  280. Bill last = head;
  281. while (current != null) {
  282. if (bill.equals(current.getNumber())) {
  283. last.next = current.next;
  284. break;
  285. }
  286. last = current;
  287. current = current.next;
  288. }
  289. }
  290. }