package com.company; import java.io.*; import java.util.ArrayList; /** * Класс реализующий "банк" */ public class Bank { /** * Список клиентов банка */ private static ArrayList users = new ArrayList<>(); /** * Голова списка счетов банка */ private static Bill head; /** * Счётчик клиентов банка. Обновлятся при добавлении нового клиента или удалении старого счёта. */ private static int count; /** * Наименование банка */ private static String name; /** * Сохранить в файл список всех зарегистрированных клиентов */ public static void saveClients() { try { FileOutputStream fos = new FileOutputStream("clients.bin"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fos); objectOutputStream.writeObject(users); objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Загрузить из файла список всех зарегистрированных клиентов */ public static void loadClients() { try { FileInputStream fos = new FileInputStream("clients.bin"); ObjectInputStream objectOutputStream = new ObjectInputStream(fos); Object o = objectOutputStream.readObject(); ArrayList array; if (o instanceof ArrayList) { array = (ArrayList) o; for (Object object : array) { if (object instanceof User) { User user = (User) object; users.add(user); } } } for (User u : users) { System.out.println(u.getUuid()); } objectOutputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * Сохранить список всех счетов в файл */ public static void saveBills() { // Пересчитать количество счетов count = 0; Bill current = head; while (current != null) { count++; current = current.next; } current = head; Bill[] bills = new Bill[count]; count = 0; while (current != null) { bills[count++] = current; current = current.next; } try { FileOutputStream fos = new FileOutputStream("bills.bin"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fos); objectOutputStream.writeObject(bills); objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Загрузить из файла список всех счетов */ public static void loadBills() { try { FileInputStream fos = new FileInputStream("bills.bin"); ObjectInputStream objectInputStream = new ObjectInputStream(fos); Object o = objectInputStream.readObject(); if (o instanceof Bill[]) { Bill[] bills = (Bill[]) o; Bill current = head; count = 0; for (Object object : bills) { if (object instanceof Bill) { Bill bill = (Bill) object; if (count == 0) { head = bill; current = head; count++; } else { current.next = bill; current = current.next; } } } } objectInputStream.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * Возвращает количество клиентов * * @return размер списка */ public static int getClientCount() { return count; } public static void registerUser(User user) { users.add(user); } public static boolean authorizedUser(String login, String password) { for (User u : users) { if (u.check(login, password)) { return true; } } return false; } /** * Возвращает наименование банка * * @return название */ public static String getName() { return name; } /** * Задать наименование банка * * @param name имя банка */ public static void setName(String name) { Bank.name = name; } /** * Авторизация клиента в системе * * @param bill номер счёта * @param pin пин-код * @return true, если данные верны */ public static boolean authorization(String bill, String pin) { Bill pointer = head; while (pointer != null) { if (pointer.getNumber().equals(bill)) { if (pointer.checkPincode(pin)) { return true; } } pointer = pointer.next; } return false; } /** * Вставить новый элемент в конец списока (открытие нового счёта) * * @param user пользователь, открывающий счёт * @param balance начальный баланс * @return регистрационные данные */ public static SecretData insert(User user, double balance) { Bill newBill = new Bill(user.getUuid(), balance, count); if (head == null) { head = newBill; } else { Bill last = head; while (last.next != null) { last = last.next; } last.next = newBill; } count++; return newBill.getSecretData(); } /** * Вставить новый элемент после указанного indexAfter (открытие ранее удалённого счёта) * * @param user пользователь, открывающий счёт * @param indexAfter индекс элемента, после которого будет вставлен новыйа * @param balance начальный баланс */ public static void insertAt(User user, int indexAfter, double balance) { Bill newBill = new Bill(user.getUuid(), balance, count); Bill current = head; if (indexAfter > count) { while (current.next != null) { current = current.next; } } else { int index = 1; while (index < indexAfter) { current = current.next; index++; } newBill.next = current.next; } current.next = newBill; } /** * Вывод информации о всех клиентах в консоль */ public static void showClientsInfo() { Bill current = head; System.out.println("\nStart client list info:"); while (current != null) { System.out.printf("Bill number: %s; Balance: %.2f;\n", current.getNumber(), current.getBalance()); current = current.next; } System.out.println("End client list info.\n"); } /** * Пополнить баланс (только свой счёт) * * @param value пополняемое значение * @param bill пополняемый номер счёта */ public static void deposit(double value, String bill) { Bill current = head; while (current != null) { if (bill.equals(current.getNumber())) { current.deposit(value); break; } current = current.next; } } /** * Списать баланс * * @param value списываемое значение * @param bill номер счёта для списания */ public static void withdraw(double value, String bill) { Bill current = head; while (current != null) { if (bill.equals(current.getNumber())) { current.withdraw(value); break; } current = current.next; } } /** * Разорвать договор с банком (удалить счёт) * * @param bill номер удаляемого счёта */ public static void delete(String bill) { Bill current = head; Bill last = head; while (current != null) { if (bill.equals(current.getNumber())) { last.next = current.next; break; } last = current; current = current.next; } } }