<repo_name>haginus/pao-labs<file_sep>/lab2/ex2.java
package lab2;



public class ex2 {
    public static  void main(String[] args) {
        Person p1 = new Person("John", "Doe", 24, 1123444L, "student");
        Person p2 = new Person("Jane", "Roe", 56, 2233444L, "teacher");

        System.out.println(p1.getName() + " " + p1.getSurname() + "(age " + p1.getAge() + ") " + p1.getId() + " " + p1.getType());
        System.out.println(p2.getName() + " " + p2.getSurname() + " (age " + p2.getAge() + ") " + p2.getId() + " " + p2.getType());
    }
}
<file_sep>/proiect/src/databaseServices/ProductDatabaseService.java
package databaseServices;

import config.DatabaseConfiguration;
import priceConventions.PricePerQuantity;
import products.Product;

import java.sql.*;
import java.util.HashMap;

public class ProductDatabaseService
{
    private static ProductDatabaseService single_instance = null;
    HashMap<String, Product> products;

    private ProductDatabaseService() {
        try {
            this.products = this.loadFromDatabase();
        } catch (SQLException e) {
            e.printStackTrace();
            this.products = new HashMap<>();
        }
    }

    public HashMap<String, Product> getProducts() {
        return products;
    }

    public HashMap<String, Product> addToDatabase(Product product) throws SQLException {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        PreparedStatement stmt = databaseConnection.prepareStatement("INSERT INTO products VALUES (?, ?, ?, ?); ");
        stmt.setString(1, product.getBarcode());
        stmt.setString(2, product.getName());
        stmt.setDouble(3, product.getPrice().price);
        String unit = product.getPrice() instanceof PricePerQuantity ? ((PricePerQuantity) product.getPrice()).measureUnit : null;
        stmt.setString(4, unit);
        stmt.executeUpdate();
        return loadFromDatabase();
    }

    public HashMap<String, Product> editInDatabase(Product product) throws SQLException {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        PreparedStatement stmt = databaseConnection.prepareStatement("UPDATE products SET name = ?, price = ?, unit = ?" +
                " WHERE barcode = ?;");
        stmt.setString(4, product.getBarcode());
        stmt.setString(1, product.getName());
        stmt.setDouble(2, product.getPrice().price);
        String unit = product.getPrice() instanceof PricePerQuantity ? ((PricePerQuantity) product.getPrice()).measureUnit : null;
        stmt.setString(3, unit);
        stmt.executeUpdate();
        return loadFromDatabase();
    }

    public HashMap<String, Product> deleteFromDatabaseByBarcode(String barcode) throws SQLException {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        PreparedStatement stmt = databaseConnection.prepareStatement("DELETE FROM products WHERE barcode = ?;");
        stmt.setString(1, barcode);
        stmt.executeUpdate();
        return loadFromDatabase();
    }

    public HashMap<String, Product> loadFromDatabase() throws SQLException {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        Statement stmt = databaseConnection.createStatement();
        ResultSet rs = stmt.executeQuery( "SELECT * FROM products;");
        HashMap<String, Product> products = new HashMap<>();
        while(rs.next()) {
            Product product;
            String unit = rs.getString(4);
            if(unit == null) product = new Product(rs.getString(1), rs.getString(2), rs.getDouble(3));
            else product = new Product(rs.getString(1), rs.getString(2), rs.getDouble(3), unit);
            products.put(product.getBarcode(), product);
        }
        return products;
    }

    public static ProductDatabaseService getInstance()
    {
        if (single_instance == null)
            single_instance = new ProductDatabaseService();

        return single_instance;
    }


}<file_sep>/proiect/README.md
# Changelog
### Checkpoint 3
 - Șters servicii citire/ștergere în CSV
 - Adăugat baza de date
 - Adăugat clasă serviciu pentru configurarea inițială bază de date
 - Adăugat servicii pentru citire, inserare, editare, ștergere din baza de date

### Checkpoint 2
- Organizat în pachete
- Adăugat servicii de scriere/citire în CSV

# Detalii despre baza de date
 - Programul se conectează la baza de date MySQL ```register``` folosind user-ul ```register``` și parola ```register``` ce rulează pe ```localhost:3306```.
 - Rulați:
 
```mysql
CREATE DATABASE register;
CREATE USER 'register'@'localhost' IDENTIFIED BY 'register';
GRANT ALL PRIVILEGES ON * . * TO 'register'@'localhost';
```

# Instrucțiuni sintaxă comandă
 - ```+ <barcode> <quantity>```: Adaugă produsul corespunzător codului de bare în cantitatea specificată la comanda curentă;
 - ```- <barcode>```: Șterge produsul corespunzător codului de bare (în toată cantitatea) din comanda curentă;
 - ```?```: Afișează totalul comenzii;
 - - ```P Cash <handled_cash>```: Plătirea comenzii în numerar, cu suma specificată;
   - ```P Card <card_number> <card_type>```: Plătirea comenzii în numerar, cu un anume card (cele două câmpuri sunt date de umplutură);
 - ```D```: Anulează comanda curentă.
<file_sep>/lab2/ex4.java
package lab2;

public class ex4 {
    public static  void main(String[] args) {
        Room r1 = new Room("12A", "normal", 3);
        Person p1 = new Person("Jane", "Roe", 56, 2233444L, "teacher");
        Room r2 = new Room("15", "lab", 2);
        Person p2 = new Person("Alex", "Popescu", 42, 2237L, "teacher");

        Subject s1 = new Subject(r1, p1, 20);
        Subject s2 = new Subject(r2, p2, 14);

        System.out.println(s1);
        System.out.println();
        System.out.println(s2);

    }
}
<file_sep>/lab1/pb3_7.java
import java.util.Scanner;
public class pb3_7
{
    public static void t3() {
        Scanner scanner = new Scanner (System. in );
        String integ = scanner.nextLine();
        Integer n = Integer.parseInt(integ);
        Integer sum = 0;
        for(Integer i = 1; i <= n; i++) {
            if(i % 3 == 0 || i % 5 == 0) sum += i;
        }
        System.out.print(sum);
    }
   
    public static void t4() {
        Scanner scanner = new Scanner (System. in );
        String integ = scanner.nextLine();
        Integer n = Integer.parseInt(integ);
        Integer fact = 1;
        for(Integer i = 2; i <= n; i++) {
            fact *= i;
        }
        System.out.print(fact);
    }
   
    public static void t5() {
        Scanner scanner = new Scanner (System. in );
        String integ = scanner.nextLine();
        Integer n = Integer.parseInt(integ);
        Integer div = 2;
        Boolean f = true;
        while(f && div <= n/2) {
            if(n % div == 0) f = false;
            div++;
        }
        System.out.print(f);
    }
   
    public static Integer fib(Integer n) {
    if (n <= 1)
        return n;
    return fib(n-1) + fib(n-2);
}
   
    public static void t6() {
        Scanner scanner = new Scanner (System. in );
        String integ = scanner.nextLine();
        Integer n = Integer.parseInt(integ);
        System.out.print(fib(n));
       
    }
   
   
    public static void t7() {
        Scanner scanner = new Scanner (System. in );
        String integ = scanner.nextLine();
        Integer n = Integer.parseInt(integ);
        for(Integer i = n; i >= 2; i--) {
            if(n % i == 0) {
                Integer div = 2;
                Boolean f = true;
                while(f && div <= i/2) {
                    if(i % div == 0) f = false;
                    div++;
                }
                if(f) {
                    System.out.print(i);
                    break;
                }
            }
        }
    }
}<file_sep>/lab2/ex1.java
package lab2;

import java.util.Scanner;

public class ex1 {
    public static  void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] studentGrades = new int[20];

        int grade = scanner.nextInt();
        int i = 0;
        float avg = 0;
        while(grade != -1 && i < studentGrades.length) {
            studentGrades[i] = grade;
            i++;
            avg += grade;
            grade = scanner.nextInt();
        }
        if(i != 0) {
            avg /= i;
            System.out.println(avg);
        } else System.out.println("Nu se poate face media.");

    }
}
<file_sep>/proiect/src/paymentMethods/PaymentMethod.java
package paymentMethods;

public class PaymentMethod {
    protected double totalPaid;
}

<file_sep>/proiect/src/Driver.java
import order.Order;
import order.ProductItem;
import priceConventions.PricePerQuantity;
import priceConventions.PricePerUnit;
import products.Product;

import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

public class Driver {
    public static void main(String[] args) {
        CashRegister register = new CashRegister();
        menu(register);
    }

    public static void menu(CashRegister register) {
        System.out.println("\n1. Listati produsele\n2. Adauga produs\n3. Editeaza Produs\n4. Sterge produs\n5. Comanda noua\n6. Istoric comenzi\n7. Adauga categorie\n8. Listare categorii\n9. Audit\n10. Exit");
        Scanner scanner = new Scanner(System.in);
        int choice = scanner.nextInt();
        switch (choice) {
            case 1:
                listProducts(register);
                break;
            case 2:
                addProduct(register);
                break;
            case 3:
                editProduct(register);
                break;
            case 4:
                deleteProduct(register);
                break;
            case 5:
                newOrder(register);
                break;
            case 6:
                listOrders(register);
                break;
            case 7:
                addCategory(register);
                break;
            case 8:
                listCategories(register);
                break;
            case 9:
                listLogs(register);
                break;
            case 10:
                break;
            default:
                menu(register);
        }
    }

    private static void listLogs(CashRegister register) {
        register.listLogs();
        menu(register);
    }

    private static void listOrders(CashRegister register) {
        register.listOrders();
        menu(register);
    }

    private static void newOrder(CashRegister register) {
        register.createNewOrder();
        Scanner scanner = new Scanner(System.in);
        String line;
        while(scanner.hasNextLine()) {
            line = scanner.nextLine();
            String[] spl = line.split(" ");
            if(spl[0].equals("+")) {
                ProductItem pi = new ProductItem(register.getProduct(spl[1]), Double.parseDouble(spl[2]));
                if (register.addToOrder(spl[1], Double.parseDouble(spl[2]))) System.out.println(pi + "SUBTOTAL: " + register.getCurrentOrder().getTotalPrice() + " RON");
                else System.out.println("Produsul nu exista!");
            }
            if(spl[0].equals("?")) System.out.println(register.getCurrentOrder());
            if(spl[0].equals("-")) {
                if (register.removeFromOrder(spl[1])) System.out.println("Produs sters.");
                else System.out.println("Produsul nu era in comanda!");
            }
            if(spl[0].equals("P")) {
                if(spl[1].equals("Cash")) register.payCurrentOrderCash(Double.parseDouble(spl[2]));
                if(spl[1].equals("Card")) register.payCurrentOrderCard(spl[2], spl[3]);
                System.out.println(register.getCurrentOrder());
                System.out.println("Zi buna! Urmatoarea comanda.");
                break;
            }
            if(spl[0].equals("D")) {
                register.discardCurrentOrder();
                System.out.println("Comanda anulata.\nZi buna! Urmatoarea comanda.");
                break;
            }
        }
        menu(register);
    }

    private static void deleteProduct(CashRegister register) {
        Scanner scanner = new Scanner(System.in);
        String barcode;
        System.out.print("Cod bare produs: ");
        barcode = scanner.next();
        Product product = register.getProduct(barcode);
        boolean res = register.deleteProduct(barcode);
        if(res) System.out.println("Produsul a fost sters cu succes.");
        else System.out.println("Produsul nu exista.");
        menu(register);
    }

    private static void editProduct(CashRegister register) {
        String barcode, name, unit;
        String price;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Cod bare produs: ");
        barcode = scanner.next();
        Product product = register.getProduct(barcode);
        if(product != null) {
            System.out.print(String.format("Nume produs (%s): ", product.getName()));
            scanner.nextLine();
            name = scanner.nextLine();
            if(name.length() > 0) product.setName(name);
            unit = (product.getPrice() instanceof PricePerUnit) ? "bucata" : ((PricePerQuantity) product.getPrice()).measureUnit;
            System.out.print(String.format("Unitate masura (%s): ", unit));
            unit = scanner.nextLine();
            System.out.print(String.format("Pret (%.2f): ", product.getPrice().price));
            price = scanner.nextLine();
            double _price;
            if(price.length() > 0) _price = Double.parseDouble(price);
            else _price = product.getPrice().price;
            if(unit.length() == 0) unit = (product.getPrice() instanceof PricePerUnit) ? "bucata" : ((PricePerQuantity) product.getPrice()).measureUnit;
            if(unit.equals("bucata")) {
                product.setPrice(_price);
            } else product.setPrice(_price, unit);
            if(register.editProduct(product)) {
                System.out.println("Produsul a fost modificat cu succes.");
            } else System.out.println("Eroare.");
        } else System.out.println("Produsul nu exista.");
        menu(register);
    }

    private static void addProduct(CashRegister register) {
        String barcode, name, unit;
        double price;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Cod bare produs: ");
        barcode = scanner.next();
        scanner.nextLine();
        System.out.print("Nume produs: ");
        name = scanner.nextLine();
        System.out.print("Unitate masura (implicit bucata): ");
        unit = scanner.nextLine();
        System.out.print("Pret: ");
        price = scanner.nextDouble();
        boolean res;
        if(unit.length() == 0) {
            res = register.addProduct(barcode, name, price);
        } else {
            res = register.addProduct(barcode, name, price, unit);
        }
        if(res) System.out.println("Produs adaugat.");
        else System.out.println("Exista deja un produs cu acest cod de bare!");
        menu(register);
    }

    public static void listProducts(CashRegister register) {
        System.out.println("Produse in baza de date: ");
        register.listProducts();
        menu(register);
    }

    public static void addCategory(CashRegister register) {
        String name;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Nume categorie: ");
        name = scanner.nextLine();
        register.addCategory(name);
        menu(register);
    }

    public static void listCategories(CashRegister register) {
        register.listCategories();
        menu(register);
    }
}
<file_sep>/proiect/src/products/Product.java
package products;

import priceConventions.Price;
import priceConventions.PricePerQuantity;
import priceConventions.PricePerUnit;

public class Product {
    private String barcode;
    private String name;
    Price price;

    public Product(String barcode, String name, double price) {
        this.barcode = barcode;
        this.name = name;
        this.price = new PricePerUnit(price);
    }

    public Product(String barcode, String name, double price, String unit) {
        this.barcode = barcode;
        this.name = name;
        this.price = new PricePerQuantity(price, unit);
    }

    public String getBarcode() {
        return barcode;
    }

    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Price getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = new PricePerUnit(price);
    }

    public void setPrice(double price, String unit) {
        this.price = new PricePerQuantity(price, unit);
    }

    public void setPrice(Price price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return barcode + " | " + name + " | " + price.toString() + "\n";
    }
}






<file_sep>/proiect/src/config/Test.java
package config;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test {
    public static void main(String[] args) {
        Connection db = DatabaseConfiguration.getDatabaseConnection();
        try {
            DatabaseSetup.setup();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        /*try {
            Statement stmt = db.createStatement();
            ResultSet rs = stmt.executeQuery("select * from pet");
            while(rs.next())
                System.out.println(rs.getString(1)+"  "+rs.getString(2));
        } catch (SQLException e) {
            e.printStackTrace();
        } */
    }
}
<file_sep>/proiect/src/priceConventions/PricePerUnit.java
package priceConventions;

public class PricePerUnit extends Price {
    public PricePerUnit(double p) {
        this.price = p;
    }

    @Override
    public String toString() {
        return String.format("%.2f", price) + " RON";
    }
}
<file_sep>/proiect/src/config/DatabaseSetup.java
package config;

import java.sql.*;

public class DatabaseSetup {
    public static void setup() throws SQLException {
        DatabaseSetup.setupTableProducts();
        DatabaseSetup.setupTableCategories();
        DatabaseSetup.setupTableOrders();
        DatabaseSetup.setupTableAudit();
    }

    private static void setupTableProducts() {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        String sql = "CREATE TABLE IF NOT EXISTS products ( barcode varchar(40) NOT NULL PRIMARY KEY, name varchar(40) NOT NULL, " +
                "price double NOT NULL, unit varchar(40));";
        try {
            Statement stmt = databaseConnection.createStatement();
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void setupTableCategories() {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        String sql = "CREATE TABLE IF NOT EXISTS product_categories ( id integer AUTO_INCREMENT PRIMARY KEY, name varchar(40) NOT NULL);";
        try {
            Statement stmt = databaseConnection.createStatement();
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void setupTableOrders() {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        String sql = "CREATE TABLE IF NOT EXISTS orders (\n" +
                "id integer AUTO_INCREMENT PRIMARY KEY,\n" +
                "total_price double NOT NULL,\n" +
                "payment_method varchar(40) NOT NULL,\n" +
                "card_number varchar(40),\n" +
                "card_type varchar(40),\n" +
                "handled_cash varchar(40)\n" +
                ");";
        String sql2 = "CREATE TABLE IF NOT EXISTS order_products (\n" +
                "id integer AUTO_INCREMENT PRIMARY KEY,\n" +
                "order_id integer NOT NULL,\n" +
                "product_barcode varchar(40) NOT NULL REFERENCES products(id) ON DELETE CASCADE,\n" +
                "quantity double NOT NULL,\n" +
                "FOREIGN KEY (order_id)\n" +
                    "REFERENCES orders(id) ON DELETE CASCADE,\n" +
                "FOREIGN KEY (product_barcode)\n" +
                    "REFERENCES products(barcode) ON DELETE CASCADE);";
        try {
            Statement stmt = databaseConnection.createStatement();
            stmt.execute(sql);
            stmt.execute(sql2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void setupTableAudit() {
        Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection();
        String sql = "CREATE TABLE IF NOT EXISTS audit ( id integer AUTO_INCREMENT PRIMARY KEY, action_name varchar(40) NOT NULL, timestamp timestamp NOT NULL);";
        try {
            Statement stmt = databaseConnection.createStatement();
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
<file_sep>/lab1/pb2.java
import java.util.Scanner;
public class pb2
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner (System. in );
        String integ = scanner.nextLine();
        Integer a = Integer.parseInt(integ);
        integ = scanner.nextLine();
        Integer b = Integer.parseInt(integ);
        String r1 = a.toString();
        String r2 = a.toString();
        String r3 = a.toString();
        if(a == b) r1 += " == " + b;
        else r1 += " != " + b;
        if(a < b) {
            r2 += " < " + b;
            r3 += " <= " + b;
        }
        else {
            r2 += " > " + b;
            r3 += " >= " + b;
        }
       
        System.out.println(r1);
        System.out.println(r2);
        System.out.println(r3);
    }
 
}<file_sep>/README.md
# Teme la PAO
<NAME>, Gr. 231
<file_sep>/proiect/src/priceConventions/PricePerQuantity.java
package priceConventions;

public class PricePerQuantity extends Price {
    public String measureUnit;
    public PricePerQuantity(double p, String unit) {
        this.price = p;
        this.measureUnit = unit;
    }

    @Override
    public String toString() {
        return String.format("%.2f", price) + " RON/" + measureUnit;
    }
}
<file_sep>/lab1/pb1.java
public class pb1
{
    public static void main(String[] args) {
     for(Integer i = 1; i <= 99; i++)
        if(i % 2 == 1) {
            String myString = i.toString();
            System.out.println(myString);
        }  
    }
 
}<file_sep>/proiect/src/paymentMethods/PaymentMethodCard.java
package paymentMethods;

public class PaymentMethodCard extends PaymentMethod {
    String cardNumber;
    String cardType;

    public PaymentMethodCard(String cardNumber, String cardType, double totalPaid) {
        this.cardNumber = cardNumber;
        this.cardType = cardType;
        this.totalPaid = totalPaid;
    }

    public String getCardNumber() {
        return cardNumber;
    }

    public String getCardType() {
        return cardType;
    }

    @Override
    public String toString() {
        return String.format("Platit cu cardul %s %s. Total platit %.2f RON", cardType, cardNumber, totalPaid);
    }
}
