Aaa

mail@pastecode.io avatar
unknown
plain_text
a month ago
12 kB
2
Indexable
Never
package bankserver;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.Buffer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;

public class BankClientHandler implements Runnable {
    private Socket socket;
    private BankManager bankManager;
    private String login = null;


    public BankClientHandler(Socket socket) {
        this.socket = socket;
        this.bankManager = BankManager.getInstance();
    }

    @Override
    public void run() {

        //Deklaracje zmiennych
        BufferedReader brinp = null;
        DataOutputStream out = null;

        //inicjalizacja strumieni
        try {
            brinp = new BufferedReader(
                    new InputStreamReader(
                            socket.getInputStream()
                    )
            );
            out = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            System.out.println("| Błąd przy tworzeniu strumieni " + e);
            return;
        }
        String line = null;
        String response = null;
        //pętla główna
        while (true) {
            try {
                line = brinp.readLine();
                if ((line == null) || "quit".equals(line)) {
                    System.out.println("Zakończenie pracy z klientem: " + socket);
                    socket.close();
                    return;
                } else {
                    switch (line) {
                        case "login":
                            while (true) {
                                if (!handleUserLoginAndAuthentication(brinp, out)) {
                                    out.writeBytes("Wrong login/password! Press ENTER to try again! \n");
                                    brinp.readLine();
                                } else {
                                    out.writeBytes("Login succeed! Press ENTER to continue! \n");
                                    brinp.readLine();
                                    break;
                                }
                            }
                            out.writeBytes(" Choose your operations: \n");
//                                    1. QUERY BALANCE
//                                    2. ADD MONEY
//                                    3. WITHDRAW MONEY
//                                    4. TRANSFER MONEY"""
                            out.flush();
                            line = brinp.readLine();
                            response = processCommand(line, brinp, out);
                            out.writeBytes(response);
                            out.flush();
                        case "register":
                            handleUserRegistration(brinp, out);
                            out.writeBytes("Registration completed! \n");
                            break;
                        default:
                            out.writeBytes("WRONG! Type in operation correctly! \n");
                            out.flush();
                    }
                }
            } catch (IOException | SQLException e) {
                System.out.println("IO error in client handler: " + e.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("Error closing socket: " + e.getMessage());
                }
            }
        }
    }

    private void handleUserRegistration(BufferedReader brinp, DataOutputStream out) throws IOException, SQLException {
        String username = null;
        boolean exists = false;
        do {
            out.writeBytes("Your login: \n");
            out.flush();
            username = brinp.readLine();
            String queryCount = "SELECT COUNT(*) AS count FROM account WHERE login = '" + username + "'";
            ResultSet resultSet = DataStorage.statement.executeQuery(queryCount);
            resultSet.next();
            int count = resultSet.getInt(1);
            if (count > 0) {
                exists = true;
                out.writeBytes("Login already exists! Type ENTER to continue! \n");
                out.flush();
                brinp.readLine();
            } else {
                exists = false;
            }
        } while (exists);
        out.writeBytes("Your password: \n");
        out.flush();
        String password = brinp.readLine();
        while (!isValidPassword(password, brinp, out)) {
            password = brinp.readLine();
        }
        out.writeBytes("Your name: \n");
        out.flush();
        String name = brinp.readLine();
        out.writeBytes("Your surname: \n");
        out.flush();
        String surname = brinp.readLine();
        out.writeBytes("Your PESEL: \n");
        out.flush();
        String pesel = brinp.readLine();
        while (pesel.length() != 11) {
            out.writeBytes("Too short/long PESEL number! Type in different one \n");
            pesel = brinp.readLine();
        }
        String queryAccount = "INSERT INTO Account VALUES ('" + username + "','"
                + name + "','" + surname + "','"
                + pesel + "','" + generateTransferNumber()
                + "'," + 0.0 + ");";
        String queryCredential = "INSERT INTO Credential VALUES ('" + username + "','"
                + password + "');";
        DataStorage.statement.executeUpdate(queryAccount);
        DataStorage.statement.executeUpdate(queryCredential);
    }

    private boolean handleUserLoginAndAuthentication(BufferedReader brinp, DataOutputStream out) throws IOException, SQLException {
        out.writeBytes("Enter your login: \n");
        out.flush();
        String username = brinp.readLine();
        out.writeBytes("Enter your password: \n");
        out.flush();
        String password = brinp.readLine();

        String queryCorrectPassword = "SELECT COUNT(*) FROM credential WHERE login = '" + username +
                "' AND password = '" + password + "'";
        ResultSet resultSet = DataStorage.statement.executeQuery(queryCorrectPassword);
        resultSet.next();
        int count = resultSet.getInt(1);
        if (count > 0) {
            login = username;
            return true;
        } else {
            return false;
        }
    }

    private String processCommand(String line, BufferedReader brinp, DataOutputStream out) throws SQLException, IOException {
        String[] parts = line.split(" ");

        String command = parts[0];

        switch (command) {
            case "queryBalance":
                return bankManager.queryBalance(login);
            case "addMoney":
                if (parts.length == 2) {
                    double amount = Double.parseDouble(parts[1]);
                    while (amount <= 0) {
                        out.writeBytes("Wrong input! Type in value above zero: \n");
                        amount = Double.parseDouble(brinp.readLine());
                    }
                    return bankManager.addMoney(login, amount);
                }
                return "Invalid addMoney command format. \n";
            case "withdrawMoney":
                if (parts.length == 2) {
                    double amount = Double.parseDouble(parts[1]);
                    while (!isWithdrawValid(amount, brinp, out)) {
                        amount = Double.parseDouble(brinp.readLine());
                    }
                    return bankManager.withdrawMoney(login, amount);
                }
                return "Invalid withdrawMoney command format. \n";
            case "transferMoney":
                if (parts.length == 3) {
                    String targetTransferNumber = parts[1];
                    double amount = Double.parseDouble(parts[2]);
                    while(!isTransferValid(targetTransferNumber, amount, brinp, out)){
                        String [] innerParts = brinp.readLine().split(" ");
                        if(innerParts.length == 2){
                            targetTransferNumber = parts[0];
                            amount = Double.parseDouble(parts[1]);
                        }
                        else{
                            out.writeBytes("Wrong formula! Type in transfer number and value! \n");
                            innerParts = brinp.readLine().split(" ");
                            targetTransferNumber = parts[0];
                            amount = Double.parseDouble(parts[1]);
                        }
                    }
                    return bankManager.transferMoney(login, targetTransferNumber, amount);
                }
                return "Invalid transferMoney command format. \n";
            default:
                return "Unknown command. \n";
        }
    }

    private boolean isEnoughMoney(double moneyToWithdraw) throws SQLException {
        String queryCurrentMoney = "SELECT balance FROM account WHERE login = '" + login + "'";
        ResultSet resultSetMoney = DataStorage.statement.executeQuery(queryCurrentMoney);
        resultSetMoney.next();
        double currentBalance = resultSetMoney.getDouble(1);
        if ((currentBalance - moneyToWithdraw) < 0) {
            return false;
        } else {
            return true;
        }
    }

    private boolean doesTransferNumberExists(String targetTransferNumber) throws SQLException {
        String queryTransferNumber = "SELECT COUNT(*) FROM account WHERE transfer_number = '"
                + targetTransferNumber + "'";
        ResultSet resultSet = DataStorage.statement.executeQuery(queryTransferNumber);
        resultSet.next();
        int count = resultSet.getInt(1);
        if (count > 0) {
            return true;
        } else {
            return false;
        }

    }

    private String generateTransferNumber() throws SQLException {
        Random random = new Random();
        StringBuilder accountNumber = new StringBuilder();
        do {
            for (int i = 0; i < 25; i++) {
                int digit = random.nextInt(10);
                accountNumber.append(digit);
            }

            int firstDigit = random.nextInt(9) + 1;
            accountNumber.insert(0, firstDigit);

        } while (doesTransferNumberExists(accountNumber.toString()));

        return accountNumber.toString();
    }

    private boolean isValidPassword(String password, BufferedReader brinp, DataOutputStream out) throws IOException {
        if (password.length() < 8) {
            out.writeBytes("Password need to be at least 8 characters! Type in new one: \n");
            return false;
        }

        if (!password.matches(".*[A-Z].*") || !password.matches(".*[a-z].*")) {
            out.writeBytes("Password need to have one big and small character! Type in new one: \n");
            return false;
        }

        if (!password.matches(".*\\d.*")) {
            out.writeBytes("Password need to contains at least one digit! Type in new one: \n");
            return false;
        }
        return true;
    }

    private boolean isWithdrawValid(double moneyToWithdraw, BufferedReader brinp, DataOutputStream out) throws IOException, SQLException {
        if (moneyToWithdraw <= 0) {
            out.writeBytes("Wrong input! Type in value above zero: \n");
            return false;
        }
        if (!isEnoughMoney(moneyToWithdraw)) {
            out.writeBytes("You don't have enough money! Type in different value: \n");
            return false;
        }
        return true;
    }

    private boolean isTransferValid(String toTransferNumber, double moneyToTransfer, BufferedReader brinp, DataOutputStream out) throws IOException, SQLException {
        if (moneyToTransfer <= 0) {
            out.writeBytes("Your input need to be above zero. Type in transfer number and value once again: \n");
            return false;
        }
        if (!doesTransferNumberExists(toTransferNumber)) {
            out.writeBytes("Transfer number doesn't exists! Type in transfer number and value once again: \n");
            return false;
        }
        if (!isEnoughMoney(moneyToTransfer)) {
            out.writeBytes("You don't have enough money! Type in transfer number and value once again: \n");
            return false;
        }
        return true;
    }
}
Leave a Comment