├── .gitignore ├── README.md ├── assets ├── treelogo.png └── treeschool_header.png ├── module_01 └── src │ ├── Factorial.java │ ├── HarmonicSum.java │ ├── PalindromeString.java │ └── PrimeNumber.java ├── module_02 └── src │ ├── 01-Diagonale │ ├── MatriciQuadrateDiagonali │ │ └── src │ │ │ ├── Main.java │ │ │ ├── MatriceQuadrata.java │ │ │ └── VersoDiagonale.java │ ├── README.MD │ └── diagonale.jpg │ ├── 02-Tabelline_in_matrice │ ├── README.MD │ └── tavola.png │ ├── 03-Tombola │ ├── README.MD │ └── Tombola.png │ ├── 04-MatchThree │ ├── README.MD │ └── candy.jpg │ ├── 05-CruciPuzzle │ ├── CruciPuzzle.java │ ├── CruciPuzzle.png │ └── README.md │ └── readme.md ├── module_03 └── src │ └── Labyrinth │ ├── Immagini │ ├── laby.gif │ ├── preview.png │ └── rogue.png │ ├── Labyrinth.java │ └── README.md ├── module_04 └── src │ ├── Automobile.java │ ├── Colore.java │ ├── FormeGeometriche.java │ ├── FormeGeometriche🛴.md │ ├── Frutto.java │ ├── Library.java │ ├── Library🛴.md │ ├── Pera.java │ ├── Persona.java │ ├── Pesca.java │ ├── Professore.java │ ├── Prova.java │ ├── StreamingService │ ├── Immagini │ │ └── netflix.png │ └── README.MD │ ├── Studente.java │ ├── lampadina │ ├── Impianto.java │ ├── Interruttore.java │ ├── Lampadina.java │ ├── README.MD │ └── StatoLampadina.java │ ├── negozio │ ├── Cliente.java │ ├── GenereProdotto.java │ ├── Giorno.java │ ├── Negozio.java │ ├── Negozio🏍.md │ └── Prodotto.java │ └── riparazioni │ ├── DittaRiparazioni.java │ ├── README.MD │ ├── Riparazione.java │ ├── StatoRiparazione.java │ ├── StatoTecnico.java │ └── Tecnico.java ├── module_05 └── src │ ├── distributore_bevande │ ├── Caffe.java │ ├── Cappuccino.java │ ├── DistributoreDiBevande.java │ ├── ProdottoDistributore.java │ └── readme.md │ └── gestione_veicoli │ ├── AutoCarro.java │ ├── AutoMobile.java │ ├── GestioneVeicoli.java │ ├── Veicolo.java │ └── readme.md ├── module_06 └── src │ ├── CompagniaSharedMobility │ └── README.md │ ├── esempioInterfacce │ ├── ClasseIterabile.java │ ├── ClasseIterabile2.java │ ├── InterfacciaIterabile.java │ ├── Main.java │ └── Persona.java │ ├── iterabile │ ├── TestIterabile.java │ ├── iterabile │ │ ├── Iterabile.java │ │ ├── IterabileAbstract.java │ │ ├── ListaDiInteri.java │ │ └── MiaStringa.java │ └── readme.md │ └── lista │ ├── TestLista.java │ └── readme.md ├── module_07 └── src │ └── supermarket │ ├── Customer.java │ ├── README.md │ └── Supermarket.java ├── module_09 └── src │ ├── EsempioReaderWriter │ ├── ReaderWriter.java │ └── test.txt │ ├── FileParole │ └── README.md │ ├── MappaDiRighe │ ├── README.md │ └── righe.txt │ └── RigheInverse │ ├── README.md │ └── righe.txt ├── module_12 └── src │ ├── civil_registry │ ├── CivilRegistry.java │ ├── Person.java │ └── README🛵.md │ └── letters_count │ ├── LettersCount.java │ └── README🛴.md ├── module_13 ├── pom.xml └── src │ └── main │ └── java │ ├── mini_ecommerce │ ├── MiniEcommerce.java │ ├── MiniEcommerce.postman_collection.json │ ├── Product.java │ └── README.md │ └── tree_express │ ├── Delivery.java │ ├── DeliveryType.java │ ├── README.md │ ├── TreeExpress.java │ ├── TreeExpress.postman_collection.json │ └── TreeExpressUser.java └── module_16 ├── ecommerce ├── README.md ├── ecommerce.drawio ├── ecommerce.sql └── ecommerce_er.png ├── movies ├── README.md ├── movies.drawio └── movies_er.png ├── pom.xml └── src └── main └── java └── ConnectionHandler.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Artifacts 2 | out 3 | *.class 4 | 5 | # IntelliJ IDEA 6 | .idea 7 | *.iml 8 | 9 | # Log file 10 | *.log 11 | 12 | # BlueJ files 13 | *.ctxt 14 | 15 | # Mobile Tools for Java (J2ME) 16 | .mtj.tmp/ 17 | 18 | # Package Files # 19 | *.jar 20 | *.war 21 | *.nar 22 | *.ear 23 | *.tar.gz 24 | *.rar 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![TreeSchool](assets/treeschool_header.png) 2 | 3 | # Corso-Java-Backend-2022-01 4 | 5 | This repo collects all the excercises produced and gathered by [Melvin Massotti](https://github.com/melvinm99), [Marco Adriani](https://github.com/MrSosu), [Pietro Marchetto](https://github.com/pimarchetto), [Andrea Gasparini](https://github.com/andrea-gasparini) and [Matteo Stabilini](https://github.com/mstab20) for the teaching of the 2022 Java Backend Course offered by [TreeSchool](https://tree.it/school/). 6 | 7 | # Index 8 | 9 | | Module | Subject | Contents | 10 | |--------|-------------------------|---------------------------------------------------------------------------------------------------------------| 11 | | 1 | Java Syntax and naming | [Esercizi](module_01/src) | 12 | | 2 | Control flow statements | [Esercizi matrici](module_02/src) | 13 | | 3 | Git | [Labyrinth](module_03/src/Labyrinth) | 14 | | 4 | OOP | [Esercizi](module_04/src) | 15 | | 5 | Ereditarietà Base | [Distributore Bevande](module_05/src/distributore_bevande), [Gestore Veicoli](module_05/src/gestione_veicoli) | 16 | | 6 | Ereditarietà Avanzata | [Esercizi](module_06/src), [Esempi interfacce](module_06/src/esempioInterfacce) | 17 | | 9 | Packages | [Esempio ReaderWriter](module_09/src/EsempioReaderWriter/ReaderWriter.java), [Esercizi](module_09/src) | 18 | | 13 | API | [Esercizi](module_13/src/main/java) | 19 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /assets/treelogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/assets/treelogo.png -------------------------------------------------------------------------------- /assets/treeschool_header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/assets/treeschool_header.png -------------------------------------------------------------------------------- /module_01/src/Factorial.java: -------------------------------------------------------------------------------- 1 | public class Factorial { 2 | public static void main(String[] args) { 3 | System.out.println(factorial(0) == (1)); 4 | System.out.println(factorial(2) == (2)); 5 | System.out.println(factorial(3) == (6)); 6 | System.out.println(factorial(5) == (120)); 7 | System.out.println(factorial(10) == (3628800)); 8 | System.out.println(factorial(20) == 2432902008176640000L); 9 | } 10 | 11 | private static long factorial(int n) { 12 | if (n == 0) return 1; 13 | long factorial = 1; 14 | for (int i=1; i<=n; i++) { 15 | factorial *= i; 16 | } 17 | return factorial; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /module_01/src/HarmonicSum.java: -------------------------------------------------------------------------------- 1 | public class HarmonicSum { 2 | public static void main(String[] args) { 3 | System.out.println(harmonicSum(1) == (1)); 4 | System.out.println(harmonicSum(2) == (3./2)); 5 | System.out.println(harmonicSum(20) == (55835135./15519504)); 6 | } 7 | 8 | private static double harmonicSum(int n) { 9 | if(n == 0) return 0; 10 | double sum = 0; 11 | for (double i=1; i<=n; i++) { 12 | sum += 1/i; 13 | } 14 | return sum; 15 | } 16 | } -------------------------------------------------------------------------------- /module_01/src/PalindromeString.java: -------------------------------------------------------------------------------- 1 | public class PalindromeString { 2 | public static void main(String[] args) { 3 | System.out.println(isPalindrome("c")); 4 | System.out.println(isPalindrome("ciic")); 5 | System.out.println(isPalindrome("aaaa")); 6 | System.out.println(!isPalindrome("absca")); 7 | System.out.println(!isPalindrome("abbaa")); 8 | System.out.println(isPalindrome("zzzzz")); 9 | System.out.println(isPalindrome("zzczz")); 10 | System.out.println(isPalindrome("aabbaa")); 11 | } 12 | 13 | private static boolean isPalindrome(String s) { 14 | for (int i=0; i 9 | 10 |

11 | -------------------------------------------------------------------------------- /module_02/src/01-Diagonale/diagonale.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_02/src/01-Diagonale/diagonale.jpg -------------------------------------------------------------------------------- /module_02/src/02-Tabelline_in_matrice/README.MD: -------------------------------------------------------------------------------- 1 | # Tabelline in matrice :kick_scooter: 2 | 3 | Realizzare un programma che crei e stampi la seguente matrice: 4 | 5 |

6 | 7 |

-------------------------------------------------------------------------------- /module_02/src/02-Tabelline_in_matrice/tavola.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_02/src/02-Tabelline_in_matrice/tavola.png -------------------------------------------------------------------------------- /module_02/src/03-Tombola/README.MD: -------------------------------------------------------------------------------- 1 | # Tombola :motor_scooter: 2 | 3 | * Scrivete una funzione che prende in input una cartella della tombola sotto forma di matrice 3*5 e un array di numeri estratti (almeno 20 numeri, non ripetuti). 4 | * La funzione controllerà quanti ambi, terni, quaterne e cinquine sono presenti nella scheda e restituirà la stringa «il giocatore ha totalizzato ambi: numero ambi etc.. 5 | * In caso di tombola invece, la funzione restituirà direttamente la stringa «TOMBOLA!!» 6 | 7 |

8 | 9 |

-------------------------------------------------------------------------------- /module_02/src/03-Tombola/Tombola.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_02/src/03-Tombola/Tombola.png -------------------------------------------------------------------------------- /module_02/src/04-MatchThree/README.MD: -------------------------------------------------------------------------------- 1 | # Match Three :motorcycle: 2 | 3 | * Scrivere un programma che data una matrice di interi ci dica quanti tris ci siano nelle righe della matrice (ATTENZIONE: 4 elementi di fila sono un tris e non due tris)! 4 | * BONUS 1: Farlo anche per le colonne 5 | * BONUS 2: Farlo anche per le diagonali 6 | 7 | * SUGGERIMENTO: Potete (e consiglio) dichiarare limitato i valori che possono stare nella matrice (per esempio i numeri da 1 a 5). 8 | 9 |

10 | 11 |

-------------------------------------------------------------------------------- /module_02/src/04-MatchThree/candy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_02/src/04-MatchThree/candy.jpg -------------------------------------------------------------------------------- /module_02/src/05-CruciPuzzle/CruciPuzzle.java: -------------------------------------------------------------------------------- 1 | public class CruciPuzzle { 2 | 3 | 4 | public static void printaMatrice(char[][] matrix) { 5 | for (int i = 0; i < matrix.length; i++) { 6 | for (int j = 0; j < matrix[0].length; j++) 7 | if(j < matrix[0].length - 1) 8 | System.out.print("" + matrix[i][j] + '-'); 9 | else 10 | System.out.print(matrix[i][j]); 11 | System.out.println(); 12 | } 13 | 14 | } 15 | 16 | public static boolean trovaParola(char[][] puzzle, String parola) { 17 | parola = parola.toUpperCase(); 18 | for (int row = 0; row < puzzle.length; row++) { 19 | for (int col = 0; col < puzzle[0].length; col++) { 20 | if (puzzle[row][col] != parola.charAt(0)) 21 | continue; 22 | if (verificaParola(puzzle, parola, row, col, 1, 0)) //Controllo orizzontale 23 | return true; 24 | if (verificaParola(puzzle, parola, row, col, -1, 0)) //Controllo orizzontale contrario 25 | return true; 26 | if (verificaParola(puzzle, parola, row, col, 0, 1)) //Controllo verticale 27 | return true; 28 | if (verificaParola(puzzle, parola, row, col, 0, -1)) //Controllo verticale contrario 29 | return true; 30 | if (verificaParola(puzzle, parola, row, col, -1, -1)) //Controllo diagonale SinistraSopra 31 | return true; 32 | if (verificaParola(puzzle, parola, row, col, 1, -1)) //Controllo diagonale DestraSopra 33 | return true; 34 | if (verificaParola(puzzle, parola, row, col, -1, 1)) //Controllo diagonale SinistraGiù 35 | return true; 36 | if (verificaParola(puzzle, parola, row, col, 1, 1)) //Controllo diagonale DestraGiù 37 | return true; 38 | } 39 | 40 | } 41 | return false; 42 | } 43 | 44 | public static boolean verificaParola(char[][] puzzle, String parola, int startRow, int startCol, int incRow, int incCol) 45 | { 46 | for(int charIndex = 1; charIndex < parola.length(); charIndex++) { 47 | int rowToCheck = startRow + charIndex * incRow; 48 | if (rowToCheck < 0 || rowToCheck >= puzzle.length) 49 | return false; 50 | int colToCheck = startCol + charIndex * incCol; 51 | if (colToCheck < 0 || colToCheck >= puzzle[0].length) 52 | return false; 53 | if(puzzle[rowToCheck][colToCheck] != parola.charAt(charIndex)) 54 | return false; 55 | } 56 | 57 | char[][] puzzleSolved = new char[puzzle.length][puzzle[0].length]; 58 | 59 | for (int row = 0; row < puzzleSolved.length; row++) 60 | for (int col = 0; col < puzzleSolved[0].length; col++) 61 | puzzleSolved[row][col] = '⬜'; 62 | 63 | for(int charIndex = 0; charIndex < parola.length(); charIndex++) { 64 | int row = startRow + charIndex * incRow; 65 | int col = startCol + charIndex * incCol; 66 | puzzleSolved[row][col] = parola.charAt(charIndex); 67 | } 68 | printaMatrice(puzzleSolved); 69 | return true; 70 | } 71 | 72 | 73 | public static void main(String[] args) { 74 | char[][] puzzle = {{'H','D','G','U','P','Y','S','P','A','O'}, 75 | {'T','S','A','K','O','Y','O','L','P','S'}, 76 | {'R','C','M','C','N','R','I','A','A','B'}, 77 | {'I','O','B','A','I','S','C','T','L','A'}, 78 | {'G','R','E','L','F','A','C','E','O','L'}, 79 | {'L','F','R','A','L','L','U','S','I','E'}, 80 | {'I','A','E','M','E','M','L','S','L','N'}, 81 | {'A','N','T','A','D','O','C','A','G','A'}, 82 | {'J','O','T','R','B','N','D','G','O','D'}, 83 | {'L','Y','O','O','U','E','S','M','S','M'}}; 84 | 85 | printaMatrice(puzzle); 86 | 87 | System.out.println(trovaParola(puzzle, "LUCCIO")); 88 | System.out.println(trovaParola(puzzle, "CALAMARO")); 89 | System.out.println(trovaParola(puzzle, "SOGLIOLA")); 90 | System.out.println(trovaParola(puzzle, "PLATESSA")); 91 | System.out.println(trovaParola(puzzle, "DELFINO")); 92 | System.out.println(trovaParola(puzzle, "GAMBERETTO")); 93 | System.out.println(trovaParola(puzzle, "SCORFANO")); 94 | System.out.println(trovaParola(puzzle, "SALMONE")); 95 | System.out.println(trovaParola(puzzle, "BALENA")); 96 | System.out.println(trovaParola(puzzle, "TRIGLIA")); 97 | System.out.println(trovaParola(puzzle, "EBAEFG")); 98 | System.out.println(trovaParola(puzzle, "GOMKP")); 99 | System.out.println(trovaParola(puzzle, "PYITOE")); 100 | System.out.println(trovaParola(puzzle, "OPACALMTOL")); 101 | System.out.println(trovaParola(puzzle, "SDA")); 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /module_02/src/05-CruciPuzzle/CruciPuzzle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_02/src/05-CruciPuzzle/CruciPuzzle.png -------------------------------------------------------------------------------- /module_02/src/05-CruciPuzzle/README.md: -------------------------------------------------------------------------------- 1 | # CruciPuzzle :motorcycle: 2 | 3 | ![Esempio](./CruciPuzzle.png) 4 | 5 | 6 | * Scrivete una funzione che prende in input una matrice di caratteri e una parola e restituisce true se la parola si trova all’interno della matrice sia verticalmente che orizzontalmente, false altrimenti. 7 | * Fatto questo fate in modo che il programma controlli anche se la parola è scritta al contrario 8 | * Bonus stage: controllate anche se la parola è presente in diagonale! 9 | 10 | 11 | 12 | ## :wink: Suggerimenti: 13 | * Scrivetevi una funzione che stampa a schermo la matrice 14 | * Quando trovate una parola stampatevi gli indici della prima lettera 15 | -------------------------------------------------------------------------------- /module_02/src/readme.md: -------------------------------------------------------------------------------- 1 | # Matrici 2 | 3 | Oggi faremo un'esercitazione sulle matrici 4 | 5 |

6 | 7 |

8 | 9 | ## Cosa sono le matrici? 10 | 11 | Le matrici sono zone di memoria contigua dove possiamo salvare in nostri dati in maniera molto analoga agli array. Non c'è alcuna differenza a livello di consumo di memoria tra un array di lunghezza 40 e una matrice 4\*10 (discorso identico ad una matrice 10\*4 o 20\*2), quello che cambia sarà il modo in cui accediamo ai dati che per la matrice sarà utilizzando due indici. Potete immaginare le matrici come array di array. 12 | 13 | ```java 14 | int[][] matrix = new int [5][10]; // Dichiaro e istanzio una matrice di interi 15 | matrix[0][0] = 5; // Inserisco il valore 5 nel primo elemento della prima riga 16 | System.out.println(matrix[0][0]); // stampo il primo elemento 17 | System.out.println(matrix[0]); // stampo la prima riga della matrice 18 | 19 | for(int row = 0; row < matrix.length; row++) 20 | for(int col = 0; col < matrix[0].length; col++) 21 | matrix[row][col] = 6; 22 | 23 | //Il doppio ciclo for scrive 6 dentro ogni cella della matrice 24 | ``` 25 | 26 | # F.A.Q. 27 | 28 | ## Posso avere una matrice le cui righe o colonne abbiano dimensioni diverse tra di loro (tipo che una riga sia lunga 20 e quella successiva 10)? 29 | 30 | Una matrice per definizione ha tutte le righe di una certa lunghezza e tutte le colonne di una certa lunghezza. È possibile creare una struttura dati come quella della domanda ma con strumenti diversi 31 | 32 | ## posso avere matrici di tipo di un oggetto Java da me creato? 33 | 34 | Assolutamente si! 35 | 36 | ## Posso avere una matrice 3D? 37 | 38 | Certo che si: 39 | 40 | ```java 41 | int[][][] matrix = new int [5][10][2]; 42 | ``` 43 | 44 | ## E 6D invece? 45 | 46 | Anche: 47 | 48 | ```java 49 | int[][][][][][] matrix = new int [5][10][2][5][1][18]; 50 | ``` 51 | 52 | 53 | 54 | # A che servono le matrici? 55 | 56 | In informatica le matrici sono largamente utilizzate in moltissimi ambiti. Sono una struttura dati base e molte strutture dati complesse all'interno immagazzinano dati in forma matriciale. Nella pratica moltissimi problemi se organizzati utilizzando una matrice risultano molto più semplici da risolvere per noi umani piuttosto che utilizzando un array. Pensate per esempio alle immagini che sono pixel salvati dentro una matrice (SPOILER: prossima settimana li vedremo per bene) 57 | 58 | # Kickstarter 59 | 60 | Qui di seguito un codice che istanzia la matrice di interi e vi permette di inserire i suoi valori a mano da tastiera: 61 | 62 | ```java 63 | import java.util.Scanner; 64 | 65 | public class MatriciCode { 66 | 67 | public static void main(String[] args) { 68 | int[][] matrix = new int[2][3]; //Istanzio matrice 69 | 70 | Scanner keyboard = new Scanner(System.in); 71 | 72 | //Riempio matrice 73 | for (int row = 0; row < matrix.length; row++) 74 | for (int col = 0; col < matrix[0].length; col++) 75 | matrix[row][col] = keyboard.nextInt(); 76 | 77 | //Stampo matrice sotto forma di matrice 78 | for (int row = 0; row < matrix.length; row++) 79 | { 80 | for (int col = 0; col < matrix[0].length; col++) 81 | System.out.print(matrix[row][col] + " "); 82 | System.out.println(); 83 | } 84 | } 85 | } 86 | ``` 87 | 88 | # Esercizi 89 | 90 | Esercizio | Difficoltà 91 | ------------ | ------------- 92 | [Diagonale](https://github.com/Backend-Developer-School-Tree/Corso-Java-Backend-2021-02/tree/main/module_02/Matrix/01-Diagonale) | :kick_scooter: 93 | [Tabelline](https://github.com/Backend-Developer-School-Tree/Corso-Java-Backend-2021-02/tree/main/module_02/Matrix/02-Tabelline_in_matrice) | :kick_scooter: 94 | [Tombola](https://github.com/Backend-Developer-School-Tree/Corso-Java-Backend-2021-02/tree/main/module_02/Matrix/03-Tombola) | :motor_scooter: 95 | [Match three](https://github.com/Backend-Developer-School-Tree/Corso-Java-Backend-2021-02/tree/main/module_02/Matrix/04-MatchThree) | :motorcycle: 96 | [Crucipuzzle](https://github.com/Backend-Developer-School-Tree/Corso-Java-Backend-2021-02/tree/main/module_02/Matrix/05-CruciPuzzle) | :motorcycle: -------------------------------------------------------------------------------- /module_03/src/Labyrinth/Immagini/laby.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_03/src/Labyrinth/Immagini/laby.gif -------------------------------------------------------------------------------- /module_03/src/Labyrinth/Immagini/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_03/src/Labyrinth/Immagini/preview.png -------------------------------------------------------------------------------- /module_03/src/Labyrinth/Immagini/rogue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_03/src/Labyrinth/Immagini/rogue.png -------------------------------------------------------------------------------- /module_03/src/Labyrinth/Labyrinth.java: -------------------------------------------------------------------------------- 1 | package Labyrinth; 2 | 3 | import java.util.Random; 4 | import java.util.Scanner; 5 | 6 | public class Labyrinth { 7 | 8 | public static void printaMatrice(char[][] labyrinth) { 9 | for (int i = 0; i < labyrinth.length; i++) { 10 | for (int j = 0; j < labyrinth[0].length; j++) 11 | System.out.print(labyrinth[i][j]); 12 | System.out.println(); 13 | } 14 | 15 | } 16 | 17 | public static boolean muoviGiocatore(char[][] labyrinth, char mossa) { 18 | int[] posizioneGiocatore = trovaGiocatore(labyrinth); 19 | int xP = posizioneGiocatore[1]; 20 | int yP = posizioneGiocatore[0]; 21 | switch (mossa) { 22 | case 'W': 23 | if (yP - 1 < 0 || labyrinth[yP - 1][xP] == 'W') 24 | return false; 25 | labyrinth[yP][xP] = '-'; 26 | labyrinth[yP - 1][xP] = 'P'; 27 | break; 28 | case 'A': 29 | if (xP - 1 < 0 || labyrinth[yP][xP - 1] == 'W') 30 | return false; 31 | labyrinth[yP][xP] = '-'; 32 | labyrinth[yP][xP - 1] = 'P'; 33 | break; 34 | case 'S': 35 | if (yP + 1 >= labyrinth.length || labyrinth[yP + 1][xP] == 'W') 36 | return false; 37 | labyrinth[yP][xP] = '-'; 38 | labyrinth[yP + 1][xP] = 'P'; 39 | break; 40 | case 'D': 41 | if (xP + 1 >= labyrinth[0].length || labyrinth[yP][xP + 1] == 'W') 42 | return false; 43 | labyrinth[yP][xP] = '-'; 44 | labyrinth[yP][xP + 1] = 'P'; 45 | break; 46 | default: 47 | return false; 48 | 49 | } 50 | return true; 51 | } 52 | 53 | public static boolean checkPlayerWin(char[][] labyrinth) { 54 | for (int i = 0; i < labyrinth.length; i++) 55 | for (int j = 0; j < labyrinth[0].length; j++) 56 | if (labyrinth[i][j] == 'E') 57 | return false; 58 | return true; 59 | } 60 | 61 | public static int[] trovaGiocatore(char[][] labyrinth) { 62 | int[] posizione = new int[2]; 63 | for (int i = 0; i < labyrinth.length; i++) 64 | for (int j = 0; j < labyrinth[0].length; j++) 65 | if (labyrinth[i][j] == 'P') { 66 | posizione[0] = i; 67 | posizione[1] = j; 68 | break; 69 | } 70 | return posizione; 71 | } 72 | 73 | public static void main(String[] args) { 74 | Scanner reader = new Scanner(System.in); 75 | /* 76 | char[][] labyrinth = new char[5][5]; 77 | for (int i = 0; i < labyrinth.length; i++) 78 | for (int j = 0; j < labyrinth[0].length; j++) 79 | labyrinth[i][j] = '-'; 80 | labyrinth[0][2] = 'W'; 81 | labyrinth[0][3] = 'W'; 82 | labyrinth[1][1] = 'W'; 83 | labyrinth[1][3] = 'W'; 84 | labyrinth[2][0] = 'P'; 85 | labyrinth[2][1] = 'W'; 86 | labyrinth[2][3] = 'W'; 87 | labyrinth[2][4] = 'W'; 88 | labyrinth[3][2] = 'W'; 89 | labyrinth[3][4] = 'E'; 90 | labyrinth[4][0] = 'W'; 91 | labyrinth[4][4] = 'W'; 92 | */ 93 | 94 | char[][] labyrinth = generaLabirintoRandom(5,8); 95 | printaMatrice(labyrinth); 96 | 97 | while (true) { 98 | char mossa = reader.next().charAt(0); 99 | muoviGiocatore(labyrinth, mossa); 100 | printaMatrice(labyrinth); 101 | if(checkPlayerWin(labyrinth)) 102 | break; 103 | } 104 | 105 | System.out.println("Hai vinto!"); 106 | } 107 | 108 | 109 | public static char[][] generaLabirintoRandom(int rows, int columns) // Non è detto sia risolvibile 110 | { 111 | Random random = new Random(); 112 | char[][] labyrinth = new char[rows][columns]; 113 | for (int i = 0; i < labyrinth.length; i++) 114 | for (int j = 0; j < labyrinth[0].length; j++) 115 | labyrinth[i][j] = '-'; 116 | 117 | int pRow = random.nextInt(rows); 118 | int eRow = random.nextInt(rows); 119 | 120 | labyrinth[pRow][0] = 'P'; 121 | labyrinth[eRow][columns - 1] = 'E'; 122 | 123 | for (int i = 0; i < labyrinth.length; i++) 124 | for (int j = 0; j < labyrinth[0].length; j++) 125 | { 126 | if(labyrinth[i][j] != '-') 127 | continue; 128 | int prob = random.nextInt(10); 129 | if (prob <= 2) 130 | labyrinth[i][j] = 'W'; 131 | } 132 | 133 | return labyrinth; 134 | } 135 | 136 | } -------------------------------------------------------------------------------- /module_03/src/Labyrinth/README.md: -------------------------------------------------------------------------------- 1 | # Labyrinth 2 | 3 | Negli anni 80 molti videogiochi :video_game: avevano una grafica "testuale" e cioè usavano i caratteri base del computer per disegnare a schermo. 4 | 5 | ![Rogue](Immagini/rogue.png) 6 | 7 | Possiamo rappresentare un labirinto come una matrice di caratteri, in cui il carattere "-" rappresenta uno spazio vuoto, la "P" la posizione del giocatore e la "E" l’uscita. 8 | 9 | 10 | ![Possibile labirinto](Immagini/preview.png) 11 | 12 | 13 | 14 | Scrivete un programma che permette ad un utente di giocare al vostro labirinto. Per farlo potrà scrivere sulla console di java le lettere «WASD» per muoversi (come in molti videogiochi per PC). Quando il giocatore raggiunge il traguardo, verrà avvisato di aver vinto e il programma termina. 15 | 16 | 17 | ## Esempio di come funziona 18 | ![test](Immagini/laby.gif) 19 | 20 | 21 | ## :smiling_face_with_three_hearts: Bonus stage: 22 | 23 | Generate il labirinto randomicamente 24 | 25 | # :skull_and_crossbones: Ultra mega bonus stage: 26 | ## Io ve lo dico, è difficile... 27 | Fate in modo che il computer sia in grado di risolvere da solo il labirinto. 28 | 29 | 30 | -------------------------------------------------------------------------------- /module_04/src/Automobile.java: -------------------------------------------------------------------------------- 1 | class Automobile { 2 | 3 | } 4 | -------------------------------------------------------------------------------- /module_04/src/Colore.java: -------------------------------------------------------------------------------- 1 | public class Colore { 2 | int r,g,b; 3 | 4 | public static final Colore nero = new Colore(0,0,0); 5 | 6 | public Colore(int r, int g, int b) { 7 | this.r = r; 8 | this.g = g; 9 | this.b = b; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /module_04/src/FormeGeometriche.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class FormeGeometriche { 4 | 5 | public static void main(String[] args) { 6 | Quadrato quadrato = new Quadrato(5); 7 | Rettangolo rettangolo = new Rettangolo(5,6); 8 | System.out.println(quadrato.toString()); 9 | System.out.println(quadrato.getArea()); 10 | } 11 | 12 | } 13 | 14 | class FormaGeometrica { 15 | private double x, y; 16 | 17 | public FormaGeometrica(double x, double y) { 18 | this.x = x; 19 | this.y = y; 20 | } 21 | 22 | public double getArea(){ 23 | return x * y; 24 | } 25 | 26 | public double getPerimeter(){ 27 | return (x + y) * 2; 28 | } 29 | } 30 | 31 | class Quadrato extends FormaGeometrica{ 32 | 33 | public Quadrato(double x) { 34 | super(x, x); 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | return "quadrato"; 40 | } 41 | } 42 | 43 | class Rettangolo extends FormaGeometrica{ 44 | 45 | public Rettangolo(double x, double y) { 46 | super(x, y); 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return "rettangolo"; 52 | } 53 | } -------------------------------------------------------------------------------- /module_04/src/FormeGeometriche🛴.md: -------------------------------------------------------------------------------- 1 | ListaOrdinata Forme Geometriche 🛴 2 | 3 | Scrivere un programma in grado di modellare il concetto di forma geometrica 4 | associato a quadrati e rettangoli. In particolare, create le classi 5 | Quadrato e Rettangolo entrambe con le seguenti caratteristiche: 6 | Ogni Quadrato deve esporre 3 metodi: 7 | - getArea: ritorna un intero 8 | - getPerimeter: ritorna il perimetro dell’oggetto 9 | - toString: ritorna «quadrato» o «rettangolo» a seconda del tipo di oggetto 10 | 11 | Deve essere possibile eseguire il seguente codice: 12 | 13 | ``` 14 | Quadrato quadrato = new Quadrato(5); 15 | Rettangolo rettangolo = new Rettangolo(5,6); 16 | ``` 17 | 18 | Suggerimento: usate l’ereditarietà 19 | -------------------------------------------------------------------------------- /module_04/src/Frutto.java: -------------------------------------------------------------------------------- 1 | public abstract class Frutto { 2 | 3 | private Colore colore; 4 | private boolean contieneSemi; 5 | 6 | public Frutto(Colore colore, boolean contieneSemi) { 7 | this.colore = colore; 8 | this.contieneSemi = contieneSemi; 9 | } 10 | 11 | public Colore getColore() { 12 | return colore; 13 | } 14 | 15 | public void setColore(Colore colore) { 16 | this.colore = colore; 17 | } 18 | 19 | public boolean contieneSemi() { 20 | return contieneSemi; 21 | } 22 | 23 | public void setContieneSemi(boolean contieneSemi) { 24 | this.contieneSemi = contieneSemi; 25 | } 26 | } -------------------------------------------------------------------------------- /module_04/src/Library.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Library { 4 | public static void main(String[] args) { 5 | int[] values = new int[7]; 6 | values[0] = 123; 7 | values[1] = 4; 8 | values[2] = 98; 9 | values[3] = 33; 10 | values[4] = 76; 11 | values[5] = 2; 12 | values[6] = 235; 13 | Library library = new Library(values); 14 | System.out.println(library.existsBook(76)); 15 | int[] booksIndexes = library.getOrderedBooksIndexes(); 16 | System.out.println(booksIndexes[0] == 2); 17 | System.out.println(booksIndexes[1] == 4); 18 | System.out.println(booksIndexes[2] == 33); 19 | System.out.println(booksIndexes[3] == 76); 20 | System.out.println(booksIndexes[4] == 98); 21 | System.out.println(booksIndexes[5] == 123); 22 | System.out.println(booksIndexes[6] == 235); 23 | } 24 | 25 | private int[] booksIndexes; 26 | 27 | public Library(int[] booksIndexes) { 28 | Arrays.sort(booksIndexes); 29 | this.booksIndexes = booksIndexes; 30 | } 31 | 32 | private boolean existsBook(int bookToFind) { 33 | for (int bookIndex : booksIndexes) { 34 | if(bookIndex == bookToFind) 35 | return true; 36 | } 37 | return false; 38 | } 39 | 40 | private int[] getOrderedBooksIndexes() { 41 | return booksIndexes; 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /module_04/src/Library🛴.md: -------------------------------------------------------------------------------- 1 | ListaOrdinata Biblioteca 🛴 2 | 3 | Scrivere un programma che permetta di gestire una Biblioteca semplificata, in grado di gestire un array 4 | di indici (interi) dei libri che contiene. La Biblioteca viene costruita a partire da un array di 5 | indici di libri. 6 | In particolare, implementare i seguenti metodi: 7 | - esisteLibro: prende un indice e restituisce true se esiste il libro con questo indice, false altrimenti 8 | - getIndiciLibriOrdinati: ritorna la lista degli indici di libri presenti nella library, in ordine ascendente 9 | 10 | Potete utilizzare il codice a questo indirizzo come test: 11 | 12 | ``` 13 | public static void main(String[] args) { 14 | int[] values = new int[7]; 15 | values[0] = 123; 16 | values[1] = 4; 17 | values[2] = 98; 18 | values[3] = 33; 19 | values[4] = 76; 20 | values[5] = 2; 21 | values[6] = 235; 22 | Biblioteca library = new Biblioteca(values); 23 | System.out.println(library.esisteLibro(76)); 24 | int[] libriOrdinati = library.getIndiciLibriOrdinati(); 25 | System.out.println(libriOrdinati[0] == 2); 26 | System.out.println(libriOrdinati[1] == 4); 27 | System.out.println(libriOrdinati[2] == 33); 28 | System.out.println(libriOrdinati[3] == 76); 29 | System.out.println(libriOrdinati[4] == 98); 30 | System.out.println(libriOrdinati[5] == 123); 31 | System.out.println(libriOrdinati[6] == 235); 32 | } 33 | ``` 34 | 35 | Suggerimento: riutilizzate il codice dei precedenti esercizi 36 | 37 | -------------------------------------------------------------------------------- /module_04/src/Pera.java: -------------------------------------------------------------------------------- 1 | public class Pera extends Frutto { 2 | public Pera(Colore colore, boolean contieneSemi) { 3 | super(colore, contieneSemi); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /module_04/src/Persona.java: -------------------------------------------------------------------------------- 1 | import java.util.Objects; 2 | 3 | public class Persona { 4 | private String nome, cognome, codiceFiscale; 5 | private int eta; 6 | 7 | //costruttore 1 8 | public Persona(String nome, String cognome, String codiceFiscale) { 9 | this.nome = nome; 10 | this.cognome = cognome; 11 | this.codiceFiscale = codiceFiscale; 12 | } 13 | 14 | //costruttore 2 piu specifico 15 | public Persona(String nome, String cognome, String codiceFiscale, int eta) { 16 | this(nome, cognome, codiceFiscale); 17 | this.eta = eta; 18 | } 19 | 20 | public String getNome() { 21 | return nome; 22 | } 23 | 24 | public void setNome(String nome) { 25 | this.nome = nome; 26 | } 27 | 28 | public String getCognome() { 29 | return cognome; 30 | } 31 | 32 | public void setCognome(String cognome) { 33 | if(cognome.isEmpty()) 34 | return; 35 | this.cognome = cognome; 36 | } 37 | 38 | public String getCodiceFiscale() { 39 | return codiceFiscale; 40 | } 41 | 42 | public void setCodiceFiscale(String codiceFiscale) { 43 | this.codiceFiscale = codiceFiscale; 44 | } 45 | 46 | //override (reimplementazione) del metodo tostring di Object 47 | @Override 48 | public String toString() { 49 | return "Persona{" + 50 | "nome='" + nome + '\'' + 51 | ", cognome='" + cognome + '\'' + 52 | ", codiceFiscale='" + codiceFiscale + '\'' + 53 | ", eta=" + eta + 54 | '}'; 55 | } 56 | 57 | //ritorna true se o è uguale a this 58 | @Override 59 | public boolean equals(Object o) { 60 | if (this == o) return true; //se è lo stesso identico oggetto (solo un diverso riferimento) 61 | if (o == null || getClass() != o.getClass()) return false; //controlla la classe es distributore e persona 62 | //se arriva qui, è sicuro di poter fare il cast senza errori 63 | Persona persona = (Persona) o; //es int -> Integer 64 | //boolean b = o instanceof Professore; 65 | //controllo effettivo 66 | return Objects.equals(codiceFiscale, persona.codiceFiscale); 67 | //return codiceFiscale.equals(persona.codiceFiscale); 68 | } 69 | 70 | //deve tornare un intero che rappresenta l'oggetto 71 | @Override 72 | public int hashCode() { 73 | return Objects.hash(codiceFiscale); 74 | //return codiceFiscale.hashCode(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /module_04/src/Pesca.java: -------------------------------------------------------------------------------- 1 | public class Pesca extends Frutto{ 2 | 3 | 4 | public Pesca(Colore colore, boolean contieneSemi) { 5 | super(colore, contieneSemi); 6 | } 7 | 8 | } 9 | -------------------------------------------------------------------------------- /module_04/src/Professore.java: -------------------------------------------------------------------------------- 1 | public class Professore { 2 | } 3 | -------------------------------------------------------------------------------- /module_04/src/Prova.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Prova { 4 | 5 | 6 | } 7 | -------------------------------------------------------------------------------- /module_04/src/StreamingService/Immagini/netflix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_04/src/StreamingService/Immagini/netflix.png -------------------------------------------------------------------------------- /module_04/src/StreamingService/README.MD: -------------------------------------------------------------------------------- 1 | # Streaming Service 2 | 3 | Siamo ormai abituati a usufruire sempre più spesso di servizi di streaming che ci permettono di vedere qualsiasi programma senza bisogno di cercarlo in televisione e senza dover aspettare che qualcuno decida di mandarlo in onda quando noi siamo liberi. 4 | 5 | Tra i più famosi possiamo citare _Netflix, Prime Video o Disney Plus_. 6 | 7 | 8 | ![Rogue](Immagini/netflix.png) 9 | 10 | Molti elementi che compongono questi servizi, possono essere ricondotti ad una struttura a classi tipica della programmazione ad oggetti. 11 | 12 | ## :kick_scooter: Abbonamento Basic 13 | 14 | Sfruttando le caratteristiche della OOP, creare delle classi che simulino un servizio di streaming classico. 15 | Prendete ispirazione da quello che conoscete meglio e sviluppate la "libreria" più adatta a contenere tutte le informazioni. 16 | 17 | Un esempio di alcune possibili classi (da integrare ed estendere con le informazioni mancanti): 18 | + _Profilo_ 19 | + Email 20 | + Password 21 | + Tipo di Offerta 22 | + Utenti 23 | + _Utente_ 24 | + Nome 25 | + Avatar 26 | + Tipo Utente (normale/kid) 27 | + Pin 28 | + _Prodotto in Catalogo_ 29 | + Titolo 30 | + Anno 31 | + Cast 32 | + Genere 33 | + PG 34 | + Originale 35 | + _Film_ 36 | + _Serie TV_ 37 | + Numero Stagioni 38 | + Numero Episodi per Stagione 39 | + _Documentario_ 40 | 41 | _**ATTENZIONE!** Una delle classi dell'esempio è astratta. Alcuni degli attributi indicati potrebbero essere ricondotti ad ulteriori classi invece che a tipi più semplici. Sfruttare anche gli enum dove possibile/sensato._ 42 | 43 | ## :motor_scooter: Abbonamento Standard 44 | 45 | + Aggiungere la funzionalità "La mia lista" che permette all'utente di memorizzare una lista personalizzata di prodotti da guardare; 46 | + Aggiungere lapossiblità ad un Utente di indicare se un prodotto gli piace o meno (si può anche decidere di fare una valutazione a stelle, da 1 a 5). 47 | 48 | _**ATTENZIONE!** Valutare sempre bene in quali classi inserire le informazioni e in quale modo._ 49 | 50 | ## :motorcycle: Abbonamento Premium 51 | 52 | + Creare un metodo che, dato un genere (es. Azione, Horror, Commedia) o una categoria (Film, Serie TV, Documentario), restituisce una lista di prodotti di quel genere o di quella categoria; 53 | + Creare un metodo che, dato un Utente, ritorni una lista di altri prodotti in catalogo che potrebbero interessargli basandosi sugli elementi presenti nella sua lista e sulle sue valutazioni dei prodotti; 54 | + Creare un metodo che, data una lista di Utenti, ritorna una lista dei 10 titoli più popolari basandosi sugli elementi presenti nelle loro liste e sulle valutazioni dei prodotti. 55 | 56 | _**Consiglio per stilare una classifica:** se avete inserito la valutazione a stella, potete scegliere quanti punti dare ad un elemento nella lista dell'utente (p.es. 3 punti che si sommano all'eventuale valutazione 1-5) oppure, nel caso di mi piace e non mi piace, dare 1 punto per i "mi piace", -1 punto i "non mi piace" e 1 punto extra se sono presenti nella lista dell'utente._ 57 | 58 | ## Nota Bene 59 | 60 | Questo esercizio dá la possibilità di sfruttare alcuni aspetti dell'ereditarietà, che vedremo nei moduli 5 e 6, e delle generics collection, del modulo 7. Una volta sostenuti questi moduli, è possibile riprendere in mano l'esercizio per migliorare il risultato sfruttando le nuove conoscenze. 61 | -------------------------------------------------------------------------------- /module_04/src/Studente.java: -------------------------------------------------------------------------------- 1 | public class Studente extends Persona{ 2 | private String matricola; 3 | 4 | public Studente(String nome, String cognome, String codiceFiscale, String matricola) { 5 | super(nome, cognome, codiceFiscale); 6 | this.matricola = matricola; 7 | } 8 | 9 | @Override 10 | public String toString() { 11 | System.out.println(getNome()); 12 | return super.toString() + "Studente{" + 13 | "matricola='" + matricola + '\'' + 14 | '}'; 15 | } 16 | 17 | public static void main(String[] args) { 18 | Persona p = new Persona("marco", "rossi", "MMM"); 19 | Persona s = p; 20 | System.out.println(p == s); 21 | p.setCognome(""); 22 | Persona p2 = new Persona("marco", "rossi", "MMM", 2); 23 | Persona[] persone = new Persona[3]; 24 | for (Persona persona : persone) { 25 | System.out.println(persona.toString()); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /module_04/src/lampadina/Impianto.java: -------------------------------------------------------------------------------- 1 | package lampadina; 2 | 3 | public class Impianto { 4 | 5 | public void staccaElettricita(){ 6 | Lampadina.hasElectricity = false; 7 | } 8 | 9 | public void attaccaElettricita(){ 10 | Lampadina.hasElectricity = true; 11 | } 12 | 13 | 14 | } 15 | -------------------------------------------------------------------------------- /module_04/src/lampadina/Interruttore.java: -------------------------------------------------------------------------------- 1 | package lampadina; 2 | 3 | public class Interruttore { 4 | 5 | private Lampadina lampadina; 6 | 7 | public Interruttore(Lampadina lampadina) { 8 | this.lampadina = lampadina; 9 | } 10 | 11 | public boolean click(){ 12 | return lampadina.click(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /module_04/src/lampadina/Lampadina.java: -------------------------------------------------------------------------------- 1 | package lampadina; 2 | 3 | import lampadina.StatoLampadina; 4 | 5 | public class Lampadina { 6 | 7 | private StatoLampadina stato; 8 | private int click; 9 | public static boolean hasElectricity; 10 | 11 | public Lampadina(int click) { 12 | this.click = click; 13 | stato = StatoLampadina.SPENTA; 14 | } 15 | 16 | public StatoLampadina getStatoLampadina(){ 17 | if (stato == StatoLampadina.ROTTA) 18 | return stato; 19 | 20 | if (!hasElectricity) 21 | return StatoLampadina.SPENTA; 22 | 23 | return stato; 24 | } 25 | 26 | public boolean click(){ 27 | 28 | if (!hasElectricity) 29 | return false; 30 | 31 | if (stato.equals(StatoLampadina.ROTTA)) 32 | return false; 33 | 34 | if (click == 0) 35 | stato = StatoLampadina.ROTTA; 36 | else 37 | { 38 | switch (stato){ 39 | case ACCESA: 40 | stato = StatoLampadina.SPENTA; 41 | break; 42 | case SPENTA: 43 | stato = StatoLampadina.ACCESA; 44 | break; 45 | } 46 | click--; 47 | } 48 | 49 | return true; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /module_04/src/lampadina/README.MD: -------------------------------------------------------------------------------- 1 | # Lampadina :bulb: 2 | 3 | ## ListaOrdinata 1 4 | Progettare una classe Lampadina, che modella una lampadina classica 5 | La lampadina può essere accesa, spenta o rotta 6 | La classe epone due metodi 7 | * ottenere lo stato corrente della lampadina 8 | * azionare la lampadina, quindi un metodo che cambia lo stato della lampadina da accesa a spenta o da spenta ad accesa, oppure che imposta lo stato a "rotta" se si è raggiunto il limite massimo di azionamenti per quella lampadina (il numero massimo di azionamenti viene definito in fase di costruzione dell'istanza) 9 | 10 | La classe deve contenere 11 | * i campi necessari a descriverne lo stato e il numero di azionamenti 12 | * un costruttore 13 | * i metodi indicati sopra 14 | 15 | Scrivere una classe di test che verifichi il funzionamento delle classi 16 | 17 | 18 | ## ListaOrdinata 2 19 | Progettare una classe Interruttore per la lampadina dell'esercizio 1 20 | 21 | * Ogni interruttore regola il comportamento di una lampadina 22 | * Definire campi e metodi necessari al funzionamento dell'interruttore 23 | * Creare una classe di test che, dopo aver istanziato due interruttori collegati alla stessa lampadina, permetta all'utente di utilizzare il primo o il secondo interruttore interagendo tramite la console, finchè non decide di interrompere l'interazione 24 | 25 | 26 | ## ListaOrdinata 3 27 | Modificare la classe Lampadina facendo in modo che tutte le lampadine condividano l'informazione relativa alla presenza di corrente all'interno di un ipotetico impianto. Possiamo immaginare che tutte le lampadine siano collegate allo stesso impianto di corrente 28 | 29 | Le lampadine devono comportarsi in modo coerente rispetto alla presenza o assenza di corrente all'interno dell'impianto 30 | 31 | Quando non c'è corrente una lampadina può essere solamente negli stati "rotto" o "spento" 32 | 33 | Scrivere una classe di test che verifichi il comportamento delle lampadine rispetto alla presenza di corrente nell'impianto -------------------------------------------------------------------------------- /module_04/src/lampadina/StatoLampadina.java: -------------------------------------------------------------------------------- 1 | package lampadina; 2 | 3 | public enum StatoLampadina { 4 | ACCESA, SPENTA, ROTTA 5 | } 6 | -------------------------------------------------------------------------------- /module_04/src/negozio/Cliente.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public class Cliente { 4 | private String codiceCliente; 5 | private String nome; 6 | private int eta; 7 | 8 | public Cliente(String codiceCliente, String nome, int eta) { 9 | this.codiceCliente = codiceCliente; 10 | this.nome = nome; 11 | this.eta = eta; 12 | } 13 | 14 | public String getCodiceCliente() { 15 | return codiceCliente; 16 | } 17 | 18 | public void setCodiceCliente(String codiceCliente) { 19 | this.codiceCliente = codiceCliente; 20 | } 21 | 22 | public String getNome() { 23 | return nome; 24 | } 25 | 26 | public void setNome(String nome) { 27 | this.nome = nome; 28 | } 29 | 30 | public int getEta() { 31 | return eta; 32 | } 33 | 34 | public void setEta(int eta) { 35 | this.eta = eta; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /module_04/src/negozio/GenereProdotto.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public enum GenereProdotto { 4 | ALIMENTARE, NON_ALIMENTARE 5 | } 6 | -------------------------------------------------------------------------------- /module_04/src/negozio/Giorno.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public enum Giorno { 4 | lunedì, martedì, mercoledì, giovedì, venerdì, sabato, domenica 5 | } 6 | -------------------------------------------------------------------------------- /module_04/src/negozio/Negozio.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | import negozio.Giorno; 4 | 5 | public class Negozio { 6 | 7 | private Prodotto[] prodotti; 8 | int numeroDiProdotti; 9 | 10 | public Negozio() { 11 | this.prodotti = new Prodotto[100]; 12 | numeroDiProdotti = 0; 13 | } 14 | 15 | public void aggiungiProdotto(Prodotto prodotto) { 16 | for(int i=0; i= 0) 40 | for(int i=indice; i= 0 ? prodotti[indice].getQuantita() : 0; 49 | } 50 | 51 | public double acquistaProdotti(Prodotto[] prodottiDaComprare, Cliente cliente, Giorno giorno) { 52 | double totale = 0; 53 | for (Prodotto prodotto : prodottiDaComprare) { 54 | int quantità = quantitàProdotto(prodotto); 55 | if(quantità >= prodotto.getQuantita()) { 56 | double subTotale = prodotto.getPrezzo() * prodotto.getQuantita(); 57 | if(cliente.getEta() >= 60 && 58 | prodotto.getGenereProdotto() == GenereProdotto.ALIMENTARE && 59 | (giorno == Giorno.lunedì || giorno == Giorno.mercoledì)) 60 | subTotale *= 0.8; 61 | totale += subTotale; 62 | int indice = getIndiceProdotto(prodotto); 63 | if(quantità - prodotto.getQuantita() == 0) 64 | rimuoviProdotto(prodotto); 65 | else 66 | prodotti[indice].setQuantita(quantità - prodotto.getQuantita()); 67 | } 68 | } 69 | return totale; 70 | 71 | } 72 | 73 | public static void main(String[] args) { 74 | Prodotto p = new Prodotto( "1", "gocciole", 2.5, 75 | GenereProdotto.ALIMENTARE, 2); 76 | Prodotto p2 = new Prodotto( "2", "Svelto", 1.5, 77 | GenereProdotto.NON_ALIMENTARE, 3); 78 | Cliente c = new Cliente("1", "Mario", 89); 79 | Cliente c2 = new Cliente("2", "Maria", 29); 80 | Negozio negozio = new Negozio(); 81 | negozio.aggiungiProdotto(p); 82 | negozio.aggiungiProdotto(p2); 83 | Prodotto p3 = new Prodotto( "1", "gocciole", 2.5, 84 | GenereProdotto.ALIMENTARE, 2); 85 | double prezzo = negozio.acquistaProdotti(new Prodotto[]{p3}, c, Giorno.venerdì); 86 | System.out.println(prezzo == 5.0); 87 | negozio.aggiungiProdotto(p); 88 | prezzo = negozio.acquistaProdotti(new Prodotto[]{p3}, c, Giorno.mercoledì); 89 | System.out.println(prezzo == 4.0); 90 | 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /module_04/src/negozio/Negozio🏍.md: -------------------------------------------------------------------------------- 1 | # Negozio 🏍 2 | 3 | Creare un sistema in grado di gestire i prodotti venduti in un negozio. Si tratta di un negozio in 4 | pieno centro storico, quindi potrà gestire al massimo 100 tipi diversi di prodotto. In particolare, il 5 | si tratta di un supermercato dove si vendono sia beni alimentari che non. Inoltre, il proprietario ha 6 | deciso di fare uno sconto del 20% sui prodotti di genere alimentare tutti i lunedì e mercoledì per 7 | i clienti con più di 60 anni. 8 | Ogni prodotto ha un nome e un prezzo. E' ovviamente possibile acquistare più prodotti simultaneamente. 9 | Deve essere possibile per il negoziante: 10 | - aggiungere un nuovo prodotto (Se un prodotto è già presente, 11 | va aggiornata solo la quantità rimanente) 12 | - rimuovere un prodotto 13 | - ottenere la quantità rimanente di ogni prodotto 14 | 15 | Deve essere possibile per il cliente: 16 | - acquistare uno o più prodotti (ottenendo il totale da pagare) 17 | 18 | Non deve essere possibile acquistare un prodotto se la quantità rimanente è 0. 19 | 20 | 21 | Plus 1: implementare una logica di pagamento rateizzato che in base al numero di mesi e all'importo 22 | da pagare restituisca l'ammontare mensile della rata 23 | 24 | Plus 2: "I regalissimi": ogni 10 euro spesi 1 punto regalo, ogni 10 punti regalo 1 euro di sconto -------------------------------------------------------------------------------- /module_04/src/negozio/Prodotto.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public class Prodotto { 4 | private String codiceProdotto, nome; 5 | private double prezzo; 6 | private GenereProdotto genereProdotto; 7 | private int quantita; 8 | 9 | public Prodotto(String codiceProdotto, String nome, double prezzo, 10 | GenereProdotto genereProdotto, int quantita) { 11 | this.codiceProdotto = codiceProdotto; 12 | this.nome = nome; 13 | this.prezzo = prezzo; 14 | this.genereProdotto = genereProdotto; 15 | this.quantita = quantita; 16 | } 17 | 18 | public String getCodiceProdotto() { 19 | return codiceProdotto; 20 | } 21 | 22 | public void setCodiceProdotto(String codiceProdotto) { 23 | this.codiceProdotto = codiceProdotto; 24 | } 25 | 26 | public String getNome() { 27 | return nome; 28 | } 29 | 30 | public void setNome(String nome) { 31 | this.nome = nome; 32 | } 33 | 34 | public double getPrezzo() { 35 | return prezzo; 36 | } 37 | 38 | public void setPrezzo(double prezzo) { 39 | this.prezzo = prezzo; 40 | } 41 | 42 | public GenereProdotto getGenereProdotto() { 43 | return genereProdotto; 44 | } 45 | 46 | public void setGenereProdotto(GenereProdotto genereProdotto) { 47 | this.genereProdotto = genereProdotto; 48 | } 49 | 50 | public int getQuantita() { 51 | return quantita; 52 | } 53 | 54 | public void setQuantita(int quantita) { 55 | this.quantita = quantita; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/DittaRiparazioni.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | 3 | import java.util.Arrays; 4 | 5 | public class DittaRiparazioni { 6 | 7 | private Tecnico[] tecnici; 8 | private int numTecnici; 9 | 10 | private Riparazione[] riparazioni; 11 | private int numRiparazioni; 12 | 13 | 14 | public DittaRiparazioni(Riparazione[] riparazioni, Tecnico[] tecnici){ 15 | this.tecnici = tecnici; 16 | this.riparazioni = riparazioni; 17 | numTecnici = 0; 18 | for(Tecnico t : tecnici) 19 | if(t != null) 20 | numTecnici++; 21 | numRiparazioni = 0; 22 | for(Riparazione r : riparazioni) 23 | if(r != null) 24 | numRiparazioni++; 25 | } 26 | 27 | public Tecnico[] getTecnici(){ 28 | return tecnici; 29 | } 30 | 31 | public boolean aggiungiRiparazione(Riparazione r){ 32 | if (esisteRiparazioneDatoIndirizzo(r.getIndirizzo())) 33 | return false; 34 | if(numRiparazioni == riparazioni.length) 35 | return false; 36 | riparazioni[numRiparazioni] = r; 37 | numRiparazioni++; 38 | return true; 39 | } 40 | 41 | 42 | private boolean esisteRiparazioneDatoIndirizzo(String indirizzo){ 43 | for (int i = 0; i < numRiparazioni; i++) { 44 | if (riparazioni[i].getIndirizzo().equals(indirizzo)) 45 | return true; 46 | } 47 | 48 | return false; 49 | } 50 | 51 | 52 | public boolean aggiungiTecnico(Tecnico t){ 53 | if (esisteTecnicoDatoNome(t.getNome())) 54 | return false; 55 | 56 | if (numTecnici == tecnici.length) 57 | return false; 58 | 59 | tecnici[numTecnici] = t; 60 | numTecnici++; 61 | return true; 62 | } 63 | 64 | 65 | private boolean esisteTecnicoDatoNome(String nome){ 66 | for (int i = 0; i < numTecnici; i++) { 67 | if (tecnici[i] == null) 68 | break; 69 | 70 | if (tecnici[i].getNome().equals(nome)) 71 | return true; 72 | } 73 | 74 | return false; 75 | } 76 | 77 | 78 | 79 | public Riparazione[] riparazioniInAttesa(){ 80 | Riparazione[] inAttesa = new Riparazione[riparazioni.length]; 81 | int countInAttesa = 0; 82 | 83 | for (int i = 0; i < numRiparazioni; i++) { 84 | if (riparazioni[i].getStato().equals(StatoRiparazione.inAttesa)) 85 | { 86 | inAttesa[countInAttesa] = riparazioni[i]; 87 | countInAttesa++; 88 | } 89 | } 90 | 91 | return inAttesa; 92 | } 93 | 94 | public Riparazione[] getRiparazioni() { 95 | return riparazioni; 96 | } 97 | 98 | public Riparazione getRiparazioneMaxPriorita(){ 99 | Riparazione risultato = null; 100 | 101 | for (int i = 0; i < numRiparazioni; i++) { 102 | 103 | if (riparazioni[i].getStato().equals(StatoRiparazione.inAttesa)) 104 | { 105 | if (risultato == null) 106 | risultato = riparazioni[i]; 107 | else if (riparazioni[i].getPriorita() > risultato.getPriorita()) 108 | risultato = riparazioni[i]; 109 | } 110 | } 111 | 112 | return risultato; 113 | } 114 | 115 | 116 | 117 | public boolean assegnaProssimaRiparazione(){ 118 | Tecnico tecnicoLibero = null; 119 | for (int i = 0; i < numTecnici; i++) { 120 | if (tecnici[i].getStato().equals(StatoTecnico.DISPONIBILE)) 121 | { 122 | tecnicoLibero = tecnici[i]; 123 | break; 124 | } 125 | } 126 | 127 | if (tecnicoLibero == null) 128 | return false; 129 | 130 | Riparazione maxPriorita = getRiparazioneMaxPriorita(); 131 | 132 | maxPriorita.setStato(StatoRiparazione.inCorso); 133 | tecnicoLibero.setRiparazione(maxPriorita); 134 | 135 | return true; 136 | } 137 | 138 | 139 | public boolean setRiparazioneTerminata(String nomeTecnico) { 140 | Tecnico tecnico = cercaTecnicoPerNome(nomeTecnico); 141 | 142 | if (tecnico == null){ 143 | System.out.println("nome tecnico non trovato"); 144 | return false; 145 | } 146 | 147 | if (tecnico.getRiparazione() == null) 148 | { 149 | System.out.println("il tecnico specificato non ha una riparazione in corso"); 150 | return false; 151 | } 152 | 153 | tecnico.getRiparazione().setStato(StatoRiparazione.terminata); 154 | tecnico.setRiparazione(null); 155 | 156 | return true; 157 | } 158 | 159 | private Tecnico cercaTecnicoPerNome(String nomeTecnico) { 160 | for (int i = 0; i < numTecnici; i++) { 161 | if (tecnici[i].getNome().equals(nomeTecnico)) 162 | return tecnici[i]; 163 | } 164 | 165 | return null; 166 | } 167 | 168 | public void mandaTecniciInFerie(String[] tecniciInFerie){ 169 | for (String tecnicoInFerie : tecniciInFerie) { 170 | Tecnico t = cercaTecnicoPerNome(tecnicoInFerie); 171 | if(t != null) 172 | t.mettiInFerie(); 173 | } 174 | } 175 | 176 | public static void main(String[] args) { 177 | Tecnico[] tecnici = {new Tecnico("mario"), new Tecnico("giorgio")}; 178 | DittaRiparazioni d = new DittaRiparazioni(new Riparazione[5], tecnici); 179 | d.aggiungiRiparazione(new Riparazione("via roma", 4)); 180 | d.aggiungiRiparazione(new Riparazione("via milano", 4)); 181 | d.aggiungiRiparazione(new Riparazione("via milano2", 4)); 182 | d.aggiungiRiparazione(new Riparazione("via milano3", 4)); 183 | d.aggiungiRiparazione(new Riparazione("via milan4", 4)); 184 | d.aggiungiRiparazione(new Riparazione("via milano5", 4)); 185 | System.out.println(Arrays.toString(d.getRiparazioni())); 186 | System.out.println(d.getRiparazioneMaxPriorita()); 187 | System.out.println(d.assegnaProssimaRiparazione()); 188 | System.out.println(d.assegnaProssimaRiparazione()); 189 | System.out.println(d.getRiparazioneMaxPriorita()); 190 | System.out.println(!d.assegnaProssimaRiparazione()); 191 | } 192 | 193 | } 194 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/README.MD: -------------------------------------------------------------------------------- 1 | # Ditta di Riparazioni 2 | 3 | ![Fix-it Felix](https://cdn.theatlantic.com/static/mt/assets/culture_test/wreck%20it%20urban%20615%20disney.png) 4 | 5 | Una ditta di riparazioni di caldaie vuole gestire gli interventi a domicilio. 6 | Progettare una classe Riparazione, che contiene l'indirizzo a cui recarsi, la priorità dell'intervento (es. un intero). 7 | Progettare una classe Tecnico, che rappresenta il tecnico che si occuperà della riparazione. 8 | 9 | Progettare quindi una classe DittaRiparazioni, che contiene un insieme di tecnici, che gestisce le seguenti funzioni: 10 | * aggiungere una nuova riparazione da fare 11 | * ottenere la lista delle riparazioni in attesa 12 | * ottenere la prossima riparazione con la maggior priorità 13 | * assegnare una riparazione ad un tecnico 14 | * marcare una riparazione come conclusa (può essere identificata dal nome del tecnico che la sta effettuando) 15 | * aggiungere un tecnico alla ditta 16 | * mandare in ferie un insieme di tecnici (identificati per nome) 17 | 18 | note: 19 | * dato che i tencici sono identificati per nome, non devono poter esistere due tecnici con lo stesso nome 20 | * non bisogna assegnare la stessa riparazione a due tecnici -------------------------------------------------------------------------------- /module_04/src/riparazioni/Riparazione.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | public class Riparazione { 3 | 4 | private String indirizzo; 5 | private int priorita; 6 | private StatoRiparazione stato; 7 | 8 | public Riparazione(String indirizzo, int priorita) { 9 | this.indirizzo = indirizzo; 10 | this.priorita = priorita; 11 | stato = StatoRiparazione.inAttesa; 12 | } 13 | 14 | public String getIndirizzo() { 15 | return indirizzo; 16 | } 17 | 18 | public int getPriorita() { 19 | return priorita; 20 | } 21 | 22 | public StatoRiparazione getStato() { 23 | return stato; 24 | } 25 | 26 | public void setStato(StatoRiparazione stato) { 27 | this.stato = stato; 28 | } 29 | 30 | 31 | @Override 32 | public String toString(){ 33 | return indirizzo+" "+priorita+" "+stato; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/StatoRiparazione.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | public enum StatoRiparazione { 3 | inAttesa, inCorso, terminata 4 | } 5 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/StatoTecnico.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | 3 | public enum StatoTecnico { 4 | DISPONIBILE, RIPARAZIONE, FERIE 5 | } 6 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/Tecnico.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | public class Tecnico { 3 | 4 | private String nome; 5 | private Riparazione riparazione; 6 | private StatoTecnico stato; 7 | 8 | public Tecnico(String nome) { 9 | this.nome = nome; 10 | stato = StatoTecnico.DISPONIBILE; 11 | } 12 | 13 | public String getNome() { 14 | return nome; 15 | } 16 | 17 | public Riparazione getRiparazione() { 18 | return riparazione; 19 | } 20 | 21 | public void setRiparazione(Riparazione riparazione) { 22 | this.riparazione = riparazione; 23 | 24 | if (riparazione == null) 25 | stato = StatoTecnico.DISPONIBILE; 26 | else 27 | stato = StatoTecnico.RIPARAZIONE; 28 | } 29 | 30 | public StatoTecnico getStato() { 31 | return stato; 32 | } 33 | 34 | public void mettiInFerie() { 35 | this.stato = StatoTecnico.FERIE; 36 | } 37 | 38 | 39 | 40 | 41 | @Override 42 | public String toString(){ 43 | return nome+" "+stato; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /module_05/src/distributore_bevande/Caffe.java: -------------------------------------------------------------------------------- 1 | package distributore_bevande; 2 | 3 | 4 | public class Caffe extends ProdottoDistributore { 5 | 6 | public Caffe(double prezzo) { 7 | super("caffe", prezzo); 8 | } 9 | 10 | } -------------------------------------------------------------------------------- /module_05/src/distributore_bevande/Cappuccino.java: -------------------------------------------------------------------------------- 1 | package distributore_bevande; 2 | 3 | public class Cappuccino extends ProdottoDistributore { 4 | 5 | public Cappuccino(double prezzo) { 6 | super("cappuccino", prezzo); 7 | } 8 | 9 | } -------------------------------------------------------------------------------- /module_05/src/distributore_bevande/DistributoreDiBevande.java: -------------------------------------------------------------------------------- 1 | package distributore_bevande; 2 | 3 | public class DistributoreDiBevande { 4 | 5 | private double importoAttuale; 6 | private ProdottoDistributore[] prodotti; 7 | 8 | public DistributoreDiBevande(int capienza) { 9 | this.prodotti = new ProdottoDistributore[capienza]; 10 | this.importoAttuale = 0; 11 | } 12 | 13 | public void caricaProdotto(ProdottoDistributore prodotto) { 14 | for(int i=0; i 4 | 5 |

6 | 7 | 8 | Una compagnia di [shared mobility](https://en.wikipedia.org/wiki/Shared_transport) vuole creare un'infrastruttura software per gestire i propri servizi e la proprio flotta. Il tipo di veicoli che offre agli utenti sono: automobili, moto scooter, biciclette, monopattini elettrici, furgoncini. La compagnia da un ID univoco interno ad ogni veicolo ma automobili, furgoncini e motorini hanno anche una targa. 9 | 10 | Eccetto le biciclette che non hanno bisogno di essere rifornite, automobili, scooter e furgoncini hanno bisogno di **carburante** mentre i monopattini elettrici hanno bisogno di **elettricità**. Inoltre biciclette e motorini hanno bisogno degli adeguati **caschi** per essere utilizzati mentre furgoni, automobili e scooter dell'adeguata **patente di guida**. 11 | 12 | La compagnia vuole poter conoscere per ogni veicolo la sua **posizione geografica**, se in un determinato momento è **affittato** o disponibile e infine lo stato del carburante o batteria (a seconda del tipo di veicolo). 13 | 14 | Un utente può affittare un veicolo pagando una certa tariffa al minuto (i prezzi li scegliete voi), **non è possibile affittare un veicolo per meno di 5 minuti.** 15 | 16 | Per quanto riguarda gli **utenti**, la compagnia vuole registrare i seguenti dati anagrafici: 17 | 18 | * Nome 19 | * Cognome 20 | * Data di nascita 21 | * Codice fiscale 22 | 23 | Oltre questi dati, l'azienda vuole dare un id univoco ad ogni utente, sapere quali patenti di guida possiede, se possiede un casco e permettere agli utenti di aggiungere del credito da spendere per gli affitti. 24 | 25 | Il sistema deve permettere ad un utente di registrarsi, cercare veicoli disponibili, affittare un veicolo, lasciare e cioè restituire un veicolo. 26 | 27 | 28 | Realizzate le classi e le funzionalità di questo sistema e fatevi un main dove testate il tutto. 29 | 30 | # DISCLAIMER 31 | 32 | Ovviamente un reale sistema del genere richiederebbe per gestire i dati un database che ancora non vi abbiamo spiegato. Createvi quindi una classe "Database" con all'interno liste degli oggetti che utilizzerete per questo sistema (lista utenti, lista automobili etc...). 33 | 34 | La traccia poi non è molto precisa su alcuni punti, questo perché vogliamo sia darvi la massima libertà per affrontare il problema e soprattutto darvi una situazione abbastanza realistica del mondo del lavoro reale, capita spesso che non soltanto vi possiate interfacciare con una persona non tecnica ma spesso il cliente non sa nemmeno di preciso cosa vuole veramente, sta a voi fare le domande giuste per arrivare ad un ottimo prodotto. 35 | 36 | # Modalità di lavoro 37 | 38 | Questo è un esercizio pensato per essere fatto in **gruppo** perciò ci aspettiamo una soluzione per ogni stanza. È obbligatorio creare una repository su cui aggiungere come collaboratore ogni membro del team. Massima libertà su come spartirvi il lavoro. Non è obbligatorio ma **fortemente gradito** un disegno con lo schema delle classi (va bene anche su carta, basta che si capisce). 39 | 40 | ## Suggerimenti 41 | 42 | HINT 1: Non esiste "la soluzione" di questo esercizio, è possibile tirare fuori due schemi di classi molto diversi tra di loro ed entrambi validi, esistono però soluzioni sbagliate che possono creare problemi di vario tipo. 43 | 44 | HINT 2: Se avete una domanda da fare sul sistema, fatela sul canale discord, è più veloce e potrebbe essere d'aiuto per altri gruppi. 45 | 46 | HINT 3: Se pensate che una certa libreria esterna può esservi utile per risolvere un determinato problema...Usatela! 47 | -------------------------------------------------------------------------------- /module_06/src/esempioInterfacce/ClasseIterabile.java: -------------------------------------------------------------------------------- 1 | public class ClasseIterabile implements InterfacciaIterabile { 2 | @Override 3 | public Object next() { 4 | System.out.println("Next classe Iterabile"); 5 | return null; 6 | } 7 | 8 | @Override 9 | public boolean hasNext() { 10 | return false; 11 | } 12 | 13 | @Override 14 | public void reset() { 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /module_06/src/esempioInterfacce/ClasseIterabile2.java: -------------------------------------------------------------------------------- 1 | public class ClasseIterabile2 implements InterfacciaIterabile { 2 | @Override 3 | public Object next() { 4 | System.out.println("Next class Iterabile 2"); 5 | return null; 6 | } 7 | 8 | @Override 9 | public boolean hasNext() { 10 | return false; 11 | } 12 | 13 | @Override 14 | public void reset() { 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /module_06/src/esempioInterfacce/InterfacciaIterabile.java: -------------------------------------------------------------------------------- 1 | /* 2 | Progettare un'interfaccia Iterabile che permette di fare le seguenti operazioni 3 | - Object next() che permette di ottenere il prossimo elemento 4 | - boolean hasNext() che indica se è presente un prossimo elemento nella sequenza 5 | - void reset() che fa resetta l'iterazione 6 | */ 7 | 8 | public interface InterfacciaIterabile { 9 | public abstract Object next(); 10 | public abstract boolean hasNext(); 11 | public abstract void reset(); 12 | } -------------------------------------------------------------------------------- /module_06/src/esempioInterfacce/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | InterfacciaIterabile oggettoIterabile = new ClasseIterabile(); 6 | ClasseIterabile2 oggettoIterabile2 = new ClasseIterabile2(); 7 | 8 | nextIterabile(oggettoIterabile); 9 | nextIterabile(oggettoIterabile2); 10 | 11 | compara(5, 2); 12 | compara('a', 'a'); 13 | Persona mario = new Persona("Mario", 18); 14 | Persona luigi = new Persona("Luigi", 20); 15 | Persona pippo = new Persona("Pippo", 6); 16 | Persona paperino = new Persona("Paperino", 6); 17 | compara(mario, luigi); 18 | 19 | List persone = new ArrayList(); 20 | persone.add(mario); 21 | persone.add(luigi); 22 | persone.add(pippo); 23 | persone.add(paperino); 24 | 25 | System.out.println("*****LISTA*****"); 26 | //ITERIAMO LA LISTA CON UN CICLO FOR 27 | /*for(Integer i = 0; i < persone.size(); i++) { 28 | Persona persona = persone.get(i); 29 | System.out.println(persona); 30 | }*/ 31 | 32 | //ITERIAMO LA LISTA CON UN ITERATORE 33 | /*Iterator iteratore = persone.iterator(); 34 | while(iteratore.hasNext()) { 35 | Persona persona = iteratore.next(); 36 | System.out.println(persona); 37 | }*/ 38 | 39 | //ITERIAMO LA LISTA CON UN CICLO FOREACH 40 | for (Persona persona: persone) { 41 | System.out.println(persona); 42 | } 43 | 44 | Set setPersone = new TreeSet(); 45 | setPersone.add(luigi); 46 | setPersone.add(mario); 47 | setPersone.add(pippo); 48 | setPersone.add(paperino); 49 | 50 | System.out.println("*****SET*****"); 51 | for (Persona persona: setPersone) { 52 | System.out.println(persona); 53 | } 54 | 55 | Map mappaPersone = new TreeMap(); 56 | 57 | mappaPersone.put("1", luigi); 58 | mappaPersone.put("40", mario); 59 | mappaPersone.put("7", pippo); 60 | 61 | System.out.println("*****MAP*****"); 62 | for (String key: mappaPersone.keySet()) { 63 | System.out.println(mappaPersone.get(key)); 64 | } 65 | 66 | if(mappaPersone.containsValue(paperino)) 67 | System.out.println("Paperino Presente"); 68 | else 69 | System.out.println("Paperino NON Presente"); 70 | } 71 | 72 | public static void nextIterabile(InterfacciaIterabile oggetto) { 73 | oggetto.next(); 74 | } 75 | 76 | public static void compara(Comparable comparable1, Comparable comparable2) { 77 | int risultatoComparazione = comparable1.compareTo(comparable2); 78 | 79 | if(risultatoComparazione > 0) 80 | System.out.println("Pippo"); 81 | else if(risultatoComparazione < 0) 82 | System.out.println("Pluto"); 83 | else 84 | System.out.println("Paperino"); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /module_06/src/esempioInterfacce/Persona.java: -------------------------------------------------------------------------------- 1 | import java.util.Objects; 2 | 3 | public class Persona implements Comparable { 4 | private String nome; 5 | private int eta; 6 | 7 | public Persona(String nome, int eta) { 8 | this.nome = nome; 9 | this.eta = eta; 10 | } 11 | 12 | public String getNome() { 13 | return nome; 14 | } 15 | 16 | public void setNome(String nome) { 17 | this.nome = nome; 18 | } 19 | 20 | public int getEta() { 21 | return eta; 22 | } 23 | 24 | public void setEta(int eta) { 25 | this.eta = eta; 26 | } 27 | 28 | @Override 29 | public int compareTo(Object o) { 30 | Persona persona = (Persona) o; 31 | 32 | if(this.getEta() > persona.getEta()) 33 | return 1; 34 | 35 | if(this.getEta() < persona.getEta()) 36 | return -1; 37 | 38 | return 0; 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return "Persona{" + 44 | "nome='" + nome + '\'' + 45 | ", eta=" + eta + 46 | '}'; 47 | } 48 | 49 | @Override 50 | public boolean equals(Object o) { 51 | if (this == o) 52 | return true; 53 | 54 | if (o == null || getClass() != o.getClass()) 55 | return false; 56 | 57 | Persona persona = (Persona) o; 58 | 59 | return eta == persona.eta; 60 | } 61 | 62 | @Override 63 | public int hashCode() { 64 | return Objects.hash(eta); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /module_06/src/iterabile/TestIterabile.java: -------------------------------------------------------------------------------- 1 | package iterabile; 2 | 3 | import iterabile.iterabile.Iterabile; 4 | import iterabile.iterabile.ListaDiInteri; 5 | import iterabile.iterabile.MiaStringa; 6 | 7 | public class TestIterabile { 8 | 9 | 10 | public static void main(String[] args) { 11 | 12 | int[] elementi = new int[]{5, 7}; 13 | ListaDiInteri lista = new ListaDiInteri(elementi); 14 | 15 | checkLista(lista); 16 | lista.reset(); 17 | checkLista(lista); 18 | 19 | 20 | String s = "ab"; 21 | MiaStringa miaStringa = new MiaStringa(s); 22 | 23 | checkStringa(miaStringa); 24 | miaStringa.reset(); 25 | checkStringa(miaStringa); 26 | } 27 | 28 | 29 | 30 | private static void checkStringa(Iterabile stringa){ 31 | 32 | if (stringa.hasNext()) 33 | System.out.println("OK"); 34 | else 35 | System.out.println("ERRORE"); 36 | 37 | 38 | if ((char)stringa.next() == 'a') 39 | System.out.println("OK"); 40 | else 41 | System.out.println("ERRORE"); 42 | 43 | 44 | if ((char)stringa.next() == 'b') 45 | System.out.println("OK"); 46 | else 47 | System.out.println("ERRORE"); 48 | 49 | 50 | if (!stringa.hasNext()) 51 | System.out.println("OK"); 52 | else 53 | System.out.println("ERRORE"); 54 | } 55 | 56 | 57 | private static void checkLista(Iterabile lista){ 58 | 59 | if (lista.hasNext()) 60 | System.out.println("OK"); 61 | else 62 | System.out.println("ERRORE"); 63 | 64 | 65 | if ((int)lista.next() == 5) 66 | System.out.println("OK"); 67 | else 68 | System.out.println("ERRORE"); 69 | 70 | 71 | if ((int)lista.next() == 7) 72 | System.out.println("OK"); 73 | else 74 | System.out.println("ERRORE"); 75 | 76 | 77 | if (!lista.hasNext()) 78 | System.out.println("OK"); 79 | else 80 | System.out.println("ERRORE"); 81 | } 82 | 83 | 84 | 85 | } 86 | -------------------------------------------------------------------------------- /module_06/src/iterabile/iterabile/Iterabile.java: -------------------------------------------------------------------------------- 1 | package iterabile.iterabile; 2 | 3 | public interface Iterabile { 4 | public Object next(); 5 | public boolean hasNext(); 6 | public void reset(); 7 | } 8 | -------------------------------------------------------------------------------- /module_06/src/iterabile/iterabile/IterabileAbstract.java: -------------------------------------------------------------------------------- 1 | package iterabile.iterabile; 2 | 3 | public abstract class IterabileAbstract implements Iterabile { 4 | protected int currentIndex; 5 | 6 | protected IterabileAbstract() { 7 | this.currentIndex = 0; 8 | } 9 | 10 | @Override 11 | public void reset() { 12 | this.currentIndex = 0; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /module_06/src/iterabile/iterabile/ListaDiInteri.java: -------------------------------------------------------------------------------- 1 | package iterabile.iterabile; 2 | 3 | public class ListaDiInteri extends IterabileAbstract { 4 | private int[] interi; 5 | 6 | public ListaDiInteri(int[] interi) { 7 | super(); 8 | this.interi = interi; 9 | } 10 | 11 | @Override 12 | public Object next() { 13 | if (hasNext()) { 14 | int i = interi[currentIndex]; 15 | currentIndex++; 16 | return i; 17 | } else { 18 | System.out.println("Non ci sono più elementi!"); 19 | return null; 20 | } 21 | } 22 | 23 | @Override 24 | public boolean hasNext() { 25 | return currentIndex < interi.length; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /module_06/src/iterabile/iterabile/MiaStringa.java: -------------------------------------------------------------------------------- 1 | package iterabile.iterabile; 2 | 3 | public class MiaStringa extends IterabileAbstract { 4 | private char[] stringa; 5 | 6 | public MiaStringa(String str) { 7 | super(); 8 | this.stringa = str.toCharArray(); 9 | } 10 | 11 | @Override 12 | public Object next() { 13 | if (hasNext()) { 14 | char c = stringa[currentIndex]; 15 | currentIndex++; 16 | return c; 17 | } else { 18 | System.out.println("Non ci sono più elementi!"); 19 | return null; 20 | } 21 | } 22 | 23 | @Override 24 | public boolean hasNext() { 25 | return currentIndex < stringa.length; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /module_06/src/iterabile/readme.md: -------------------------------------------------------------------------------- 1 | ## Iterabile 🛴 2 | 3 | Progettare un'interfaccia Iterabile che permette di fare le seguenti operazioni 4 | * Object next() che permette di ottenere il prossimo elemento 5 | * boolean hasNext() che indica se è presente un prossimo elemento nella sequenza 6 | * void reset() che fa resetta l'iterazione 7 | 8 | Progettare due classi ListaDiInteri, costruita con un array di interi, e MiaStringa, costruita con una stringa, che usano l'interfaccia Iterabile e ne implementano i metodi 9 | (Considerare una stringa come una sequenza di char) 10 | 11 | Usare il codice di test per verificare le funzioni -------------------------------------------------------------------------------- /module_06/src/lista/TestLista.java: -------------------------------------------------------------------------------- 1 | package lista; 2 | 3 | import lista.lista.ListaDiInteri; 4 | import lista.lista.Lista; 5 | import lista.lista.MiaStringa; 6 | 7 | public class TestLista { 8 | 9 | public static void main(String[] args) { 10 | 11 | ListaDiInteri lista = new ListaDiInteri(); 12 | 13 | checkListaInteri(lista); 14 | 15 | 16 | MiaStringa stringa = new MiaStringa(); 17 | checkMiaStringa(stringa); 18 | 19 | } 20 | 21 | 22 | private static void checkMiaStringa(Lista stringa){ 23 | System.out.println(stringa.size() == 0 ? "OK" : "ERRORE"); 24 | 25 | stringa.add('a'); 26 | System.out.println(stringa.size() == 1 ? "OK" : "ERRORE"); 27 | 28 | System.out.println((char)stringa.get(0) == 'a' ? "OK" : "ERRORE"); 29 | 30 | stringa.add('b'); 31 | stringa.add('c'); 32 | 33 | System.out.println(stringa.remove(0) ? "OK" : "ERRORE"); 34 | 35 | System.out.println(stringa.contains('b') ? "OK" : "ERRORE"); 36 | System.out.println(!stringa.contains('d') ? "OK" : "ERRORE"); 37 | 38 | stringa.clear(); 39 | 40 | System.out.println(stringa.size() == 0 ? "OK" : "ERRORE"); 41 | 42 | System.out.println(!stringa.contains('a') ? "OK" : "ERRORE"); 43 | } 44 | 45 | private static void checkListaInteri(Lista lista){ 46 | System.out.println(lista.size() == 0 ? "OK" : "ERRORE"); 47 | 48 | lista.add(5); 49 | System.out.println(lista.size() == 1 ? "OK" : "ERRORE"); 50 | 51 | System.out.println((int)lista.get(0) == 5 ? "OK" : "ERRORE"); 52 | 53 | lista.add(10); 54 | lista.add(40); 55 | 56 | System.out.println(lista.remove(1) ? "OK" : "ERRORE"); 57 | 58 | System.out.println(lista.contains(40) ? "OK" : "ERRORE"); 59 | System.out.println(!lista.contains(56) ? "OK" : "ERRORE"); 60 | 61 | lista.clear(); 62 | 63 | System.out.println(lista.size() == 0 ? "OK" : "ERRORE"); 64 | 65 | System.out.println(!lista.contains(5) ? "OK" : "ERRORE"); 66 | } 67 | 68 | } 69 | //get contains size add remove clear 70 | -------------------------------------------------------------------------------- /module_06/src/lista/readme.md: -------------------------------------------------------------------------------- 1 | ## Lista 🛴 2 | 3 | Progettare un'interfaccia Lista che permette di fare le seguenti operazioni 4 | * get(int i) che restituisce l'elemento alla posizione i della sequenza 5 | * contains(Object o) che restituisce true se l'elemento o è presente nella sequenza 6 | * size() che restituisce quanti elementi sono presenti all'interno della sequenza 7 | * add(Object o) che aggiunge un elemento alla sequenza 8 | * remove(int i) che rimuove l'elemento alla posizione i della sequenza, torna true se l'elemento è stato rimosso, false se non l'ha trovato 9 | * clear() rimuove tutti gli elementi dalla sequenza 10 | 11 | Aggiungere l'interfaccia Lista alle classi ListaDiInteri e MiaStringa, ed implementarne i metodi 12 | 13 | Usare il codice di test per verificare le funzioni -------------------------------------------------------------------------------- /module_07/src/supermarket/Customer.java: -------------------------------------------------------------------------------- 1 | package supermarket; 2 | 3 | import java.util.Comparator; 4 | import java.util.Objects; 5 | 6 | public class Customer implements Comparable{ 7 | private String id, name, surname; 8 | private int age; 9 | 10 | public Customer(String id, String name, String surname, int age) { 11 | this.id = id; 12 | this.name = name; 13 | this.surname = surname; 14 | this.age = age; 15 | } 16 | 17 | public String getId() { 18 | return id; 19 | } 20 | 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public String getSurname() { 26 | return surname; 27 | } 28 | 29 | public int getAge() { 30 | return age; 31 | } 32 | 33 | @Override 34 | public boolean equals(Object o) { 35 | if (this == o) return true; 36 | if (o == null || getClass() != o.getClass()) return false; 37 | Customer customer = (Customer) o; 38 | return Objects.equals(id, customer.id); 39 | } 40 | 41 | @Override 42 | public int hashCode() { 43 | return Objects.hash(id); 44 | } 45 | 46 | @Override 47 | public int compareTo(Customer o) { 48 | return Comparator.comparing((Customer c)->c.getAge()).reversed() 49 | .thenComparing(Customer::getId).compare(this, o); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /module_07/src/supermarket/README.md: -------------------------------------------------------------------------------- 1 | Esercizio Supermercato versione 2 🛴 2 | 3 | Scrivere un programma Java che permetta di gestire la coda di un supermercato. 4 | In particolare, deve essere possibile eseguire le seguenti operazioni: 5 | 6 | - inserimento in coda di un cliente 7 | - rimozione dalla coda di un cliente 8 | - ottenere prossimo cliente da servire 9 | - ottenere il numero di clienti attualmente in coda 10 | 11 | Ogni cliente ha nome, cognome, età e un id univoco. 12 | La coda, ovviamente, va gestita secondo la politica FIFO. 13 | 14 | PLUS 🏍 : Modificare la coda per favorire le persone più anziane 15 | 16 | Suggerimento: scegliete bene la struttura dati (una possibile soluzione potrebbe 17 | essere la PriorityQueue, che è un tipo di coda fornito da Java ad esempio...) 18 | -------------------------------------------------------------------------------- /module_07/src/supermarket/Supermarket.java: -------------------------------------------------------------------------------- 1 | package supermarket; 2 | 3 | import java.util.*; 4 | 5 | public class Supermarket { 6 | //Queue queue = new PriorityQueue<>(); //queue version 7 | TreeSet queue = new TreeSet<>(); 8 | 9 | public void addCustomer(Customer customer) { 10 | //queue.offer(customer); //queue version 11 | queue.add(customer); 12 | } 13 | 14 | public void removeCustomer(Customer customer) { 15 | queue.remove(customer); 16 | } 17 | 18 | public Customer getNextCustomer() { 19 | return queue.pollFirst(); 20 | //return queue.poll(); //queue version 21 | } 22 | 23 | public int getTotalCustomersCount() { 24 | return queue.size(); 25 | } 26 | 27 | public static void main(String[] args) { 28 | Customer c1 = new Customer("123", "mario", "rossi",18); 29 | Customer c2 = new Customer("112", "maria", "rossi",88); 30 | Customer c3 = new Customer("133", "marione", "rossi",25); 31 | Customer c4 = new Customer("134", "marco", "bianchi",18); 32 | Supermarket supermarket = new Supermarket(); 33 | supermarket.addCustomer(c1); 34 | supermarket.addCustomer(c2); 35 | supermarket.addCustomer(c3); 36 | supermarket.addCustomer(c4); 37 | System.out.println(supermarket.getTotalCustomersCount() == 4); 38 | Customer next = supermarket.getNextCustomer(); 39 | System.out.println(next.getName().equals("maria")); 40 | next = supermarket.getNextCustomer(); 41 | System.out.println(next.getName().equals("marione")); 42 | next = supermarket.getNextCustomer(); 43 | System.out.println(next.getName().equals("mario")); 44 | System.out.println(supermarket.getTotalCustomersCount() == 1); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /module_09/src/EsempioReaderWriter/ReaderWriter.java: -------------------------------------------------------------------------------- 1 | package EsempioReaderWriter; 2 | 3 | import java.io.*; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class ReaderWriter 11 | { 12 | private static final Path FILE_TO_READ = Paths.get("module_09", "src", "EsempioReaderWriter", "test.txt"); 13 | private static final Path FILE_TO_WRITE = Paths.get("module_09", "src", "EsempioReaderWriter", "new_test.txt"); 14 | 15 | /** 16 | * Read all lines from a file and return them. 17 | * 18 | * P.S. per leggere semplicemente tutte le righe di un file avremmo potuto anche utilizzare: 19 | * 20 | * List lines = Files.readAllLines(pathToFile); 21 | * 22 | * leggere una riga per volta è comunque l'utilizzo più consigliato per non leggere 23 | * interamente file di grandi dimensioni 24 | */ 25 | private List readFile(Path pathToFile) 26 | { 27 | List lines = new ArrayList<>(); 28 | 29 | try (BufferedReader br = Files.newBufferedReader(pathToFile)) 30 | { 31 | while (br.ready()) 32 | { 33 | // leggo una riga del file e passo alla successiva 34 | String line = br.readLine(); 35 | lines.add(line); 36 | } 37 | } 38 | catch (IOException e) 39 | { 40 | e.printStackTrace(); 41 | } 42 | 43 | return lines; 44 | } 45 | 46 | /** 47 | * Write in a file the given strings, one per line. 48 | * Creates a new file if one with the given file name does not exist already. 49 | */ 50 | private void writeFile(Path pathToFile, List lines) 51 | { 52 | try (BufferedWriter br = Files.newBufferedWriter(pathToFile)) 53 | { 54 | for (String line : lines) 55 | { 56 | // scrivo una stringa nel file 57 | br.write(line); 58 | // passo alla riga successiva 59 | br.newLine(); 60 | } 61 | } 62 | catch (IOException e) 63 | { 64 | e.printStackTrace(); 65 | } 66 | } 67 | 68 | public static void main(String[] args) 69 | { 70 | ReaderWriter rw = new ReaderWriter(); 71 | List lines = rw.readFile(FILE_TO_READ); 72 | rw.writeFile(FILE_TO_WRITE, lines); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /module_09/src/EsempioReaderWriter/test.txt: -------------------------------------------------------------------------------- 1 | Prima riga di un file di testo 2 | Seconda riga di un file di testo 3 | Terza riga di un file di testo 4 | Quarta riga di un file di testo -------------------------------------------------------------------------------- /module_09/src/FileParole/README.md: -------------------------------------------------------------------------------- 1 | # File e parole 🛵 2 | 3 | Spesso è interessante analizzare uno o più file di testo in una determinata lingua per comprendere quali siano le parole più frequenti (o anche le lettere più frequenti). Questo tipo di lavoro è molto utilizzato in vari ambiti, dalla crittografia alla linguistica al Natural Language Processing. La seguente classe da realizzare, la classe FileAndParole effettua alcune di queste operazioni. Essa è composta dai seguenti metodi: 4 | 5 | -stampaParole(Path file): questo metodo prende in input un oggetto della classe Path del package java.nio.file rappresentante un file di testo e stampa riga per riga tutte le parole contenute nel testo. Si supponga che ogni parola sia separata da spazio e non vi siano segni di punteggiatura. 6 | 7 | -occorrenzeParole(Path file): questo metodo prende in input un oggetto della classe Path del package java.nio.file rappresentante un file di testo e ritorna una HashMap dove le chiavi sono le parole e i valori sono il numero di occorrenze delle parole stesse nel testo. Si supponga che ogni parola sia separata da spazio, siano tutte minuscole e non vi siano segni di punteggiatura. 8 | 9 | -occorrenzeParoleTesto(Path file): questo metodo prende in input un oggetto della classe Path del package java.nio.file rappresentante un file di testo e ritorna una HashMap dove le chiavi sono le parole e i valori sono il numero di occorrenze delle parole stesse nel testo. In questo caso il testo può comprendere punteggiatura e lettere maiuscole. SUGGERIMENTO: per eliminare la punteggiatura da una riga di testo utilizzare il metodo riga.split("\W+"). 10 | 11 | -paroleInRima(Path file): questo metodo prende in input un oggetto della classe Path del package java.nio.file rappresentante un file di testo in italiano e il suo obiettivo è quello di catalogare le parole in rima. Due parole in italiano di intendono in rima se: -Terminano con una sequenza vocale-consonante-vocale identica. -Terminano con una sequenza vocale-consonante-consonante-vocale identica. Il metodo deve ritornare una HashMap dove le chiavi sono i dittonghi finali (le rime) e i valori sono ArrayList contenenti tutte le parole che terminano con quel dittongo (rima). Ad esempio se il testo è il seguente: 12 | 13 | "Il soldato è tornato passando per un ponte vicino a una fonte" 14 | 15 | Il metodo deve tornare: 16 | 17 | {"ato": ["soldato", "tornato"], "ando": ["passando"], "onte": ["ponte", "fonte"], 18 | "ino": ["vicino"] } 19 | 20 | NB: ignorare completamente le parole con lunghezza minore di 4 lettere. -------------------------------------------------------------------------------- /module_09/src/MappaDiRighe/README.md: -------------------------------------------------------------------------------- 1 | ## Mappa di righe da file 🛴 2 | 3 | Leggere il file righe.txt usando le classi del package java.nio 4 | Ogni riga segue la formattazione k:v,v,v,v,v 5 | 6 | Creare una Map> 7 | 8 | Per ogni riga del file, aggiungere la chiave col valore della stringa "k" associata ai valori "v,v,v,v,v" della riga 9 | 10 | Es. 11 | ciao:come,va,come,stai -> map.put("ciao", ["come", "va", "come", "stai"]) -------------------------------------------------------------------------------- /module_09/src/MappaDiRighe/righe.txt: -------------------------------------------------------------------------------- 1 | 9fe8a868:Quod,totum,contra,est.,Duo 2 | bc4fdbb8:vocem,Epicure,sed,quid,tibi 3 | 8f175dd9:non,sunt,in,potestate,sapientis. 4 | f56d9caa:earum,rerum,quae,sibi,conducant 5 | f5aad08f:Quid,ergo?,,Eademne,quae 6 | 9beff6c6:tamen,esse,possunt.,Duarum,enim 7 | db206b06:At,multis,malis,affectus.,Nam 8 | 92cc0fad:quicquam,extra,virtutem,habeatur,in 9 | 422b5664:sint,in,voluptate,et,ea 10 | 6f158547:dedocendi,esse,videantur.,Virtutis,magnitudinis 11 | 3a8820f2:causa,fieri,nihil,putandum,est. 12 | 5af0134f:esse,numquam,probabis;,Sed,nimis 13 | adf06271:animi,patientiae,fortitudinis,fomentis,dolor 14 | 9252272d:virtutes,qui,habent,ingeniosi,vocantur. 15 | b52400b9:Ut,proverbia,non,nulla,veriora 16 | c94e986b:inquit,omnisque,qui,sine,dolore 17 | 6e62e4cb:enim,depravatae,non,sint,pravae 18 | 94aed34a:ea,difficultate,illae,fallaciloquae,ut 19 | e30b31b0:Aeque,enim,contingit,omnibus,fidibus 20 | 0c98bcd0:dicis,et,Philodemum,cum,optimos 21 | 924ec99d:eundem,illum,Torquatum?,Hoc,tu 22 | 0a16549a:dicendum,sit,oblitus,es.,Ex 23 | 0f037ab8:probaturum,esse,confidam.,Illud,dico 24 | bf0b9934:amittere.,Familiares,nostros,credo,Sironem 25 | 04aa89e1:te,de,amicitia,dicta,sunt. 26 | 64fdbf36:ea,quae,dicat,praeclare,inter 27 | 4f69605d:non,liceat,liceat,illis.,Virtutis 28 | 96c54c05:mitigari,solet.,Quae,fere,omnia 29 | b0f84894:ut,incontentae,sint.,Lorem,ipsum 30 | 483a245e:affecit,quanto,L.,Quorum,sine 31 | 4bc42fb7:bonis.,Sed,plane,dicit,quod 32 | f8a7be2d:elit.,Quae,cum,ita,sint 33 | 2f9979b2:quidem,summa,esse,dico.,Potius 34 | 5d8494bc:magnitudinis,animi,patientiae,fortitudinis,fomentis 35 | 9e5b371f:restincta,siti?,Ita,relinquet,duas 36 | 402d4c3b:ea,tamen,quae,te,ipsum 37 | 058b7267:locus,est,Piso,tibi,etiam 38 | e3e6cf08:effectum,est,nihil,esse,malum 39 | 02368b38:Tria,genera,bonorum;,Nunc,dicam 40 | afe003d4:post,Tarentum,ad,Archytam?, 41 | 682eb511:de,voluptate,nihil,scilicet,novi 42 | 81d0325b:nunc,in,illo,probas.,Cur 43 | cbc08d0f:intellegit.,Paulum,cum,regem,Persem 44 | 2f79b620:destiterit,non,erit;,, 45 | 01002413:nostrum,est-quod,nostrum,dico,artis 46 | 0e77da64:est-ad,ea,principia,quae,accepimus. 47 | 9719bdfd:vitarum,nobis,erunt,instituta,capienda. 48 | 8aef7b6a:,Non,igitur,de,improbo 49 | 0e37b6c1:dolor,sit,amet,consectetur,adipiscing 50 | 84061704:inflammat,ut,coercendi,magis,quam 51 | 3627de80:appellantur,uno,ingenii,nomine,easque 52 | 195bbf85:hoc,modo,vir,optimus,tuique 53 | 0a759030:quod,turpe,non,sit.,Itaque 54 | 8768388b:atque,etiam,confirmandus,inquam;,Quamvis 55 | 68ad3174:Nec,enim,dum,metuit,iustus 56 | f678ac16:dolor,mitigari,solet.,Piso,igitur 57 | 19ec594f:nisi,constanter,loquare?,Prioris,generis 58 | b5608d37:iam,a,me,expectare,noli. 59 | 09964b51:qualis,Q.,Audio,equidem,philosophi 60 | 757e5ec3:Reges:,constructio,interrete.,Atqui,iste 61 | 3c7563c8:Quis,est,tam,dissimile,homini. 62 | 99018076:Eaedem,res,maneant,alio,modo. 63 | 520ea091:Quid,ergo,attinet,gloriose,loqui 64 | 7e8b31b0:tamen,est,aliquid,quod,nobis 65 | df16e705:est,et,certe,si,metuere 66 | bd198a23:festo,illo,die,tanto,gaudio 67 | 93aee621:sed,de,callido,improbo,quaerimus 68 | 959dfb49:ut,scis,amantissimus.,Non,prorsus 69 | 69573c47:multa.,Nam,prius,a,se 70 | 6d0ffd6c:esse,dicit,neque,ea,ratione 71 | c860657b:,Qui,ita,affectus,beatum 72 | 20d255eb:inquit.,Bestiarum,vero,nullum,iudicium 73 | c38ade5d:sint,quam,vestra,dogmata.,Si 74 | 8e37292f:de,quibus,etiam,atque,etiam 75 | 59a88d53:ait,Accius,malitiae,natae,sunt. 76 | dfb4f716:quibus,rebus,efficiuntur,voluptates,eae 77 | 121fd19d:est,docilitas,memoria;,Portenta,haec 78 | c3d470ce:se,cohaerere.,Fortemne,possumus,dicere 79 | ac224d32:Indicant,pueri,in,quibus,ut 80 | e201f7cd:consideret.,Illa,videamus,quae,a 81 | 42bfb4a0:viros,tum,homines,doctissimos.,Quod 82 | 8c42577e:ullo,modo,posse,vivi;,Beatum 83 | f039018a:puto.,,Quem,Tiberina,descensio 84 | 9fbd66fe:poterit,quisque,discedere,quam,appetitum 85 | 3f1aff74:in,speculis,natura,cernitur.,Sed 86 | cdd06cdb:captum,adduceret,eodem,flumine,invectio? -------------------------------------------------------------------------------- /module_09/src/RigheInverse/README.md: -------------------------------------------------------------------------------- 1 | ## Righe inverse 🛴 2 | 3 | Leggere il file righe.txt usando le classi del package java.nio 4 | 5 | Scrivere le righe nel file righeInverse.txt in ordine inverso, quindi l'ultima riga del file righe.txt deve essere la prima riga del file righeInverse.txt -------------------------------------------------------------------------------- /module_09/src/RigheInverse/righe.txt: -------------------------------------------------------------------------------- 1 | 0 Aeque enim 2 | 1 contingit omnibus 3 | 2 fidibus, ut 4 | 3 incontentae sint. 5 | 4 Lorem ipsum 6 | 5 dolor sit 7 | 6 amet, consectetur 8 | 7 adipiscing elit. 9 | 8 Quae cum 10 | 9 ita sint, 11 | 10 effectum est 12 | 11 nihil esse 13 | 12 malum, quod 14 | 13 turpe non 15 | 14 sit. Itaque 16 | 15 nostrum est-quod 17 | 16 nostrum dico, 18 | 17 artis est-ad 19 | 18 ea principia, 20 | 19 quae accepimus. 21 | 20 Quod totum 22 | 21 contra est. 23 | 22 Duo Reges: 24 | 23 constructio interrete. 25 | 24 Atqui iste 26 | 25 locus est, 27 | 26 Piso, tibi 28 | 27 etiam atque 29 | 28 etiam confirmandus, 30 | 29 inquam; Quamvis 31 | 30 enim depravatae 32 | 31 non sint, 33 | 32 pravae tamen 34 | 33 esse possunt. 35 | 34 Duarum enim 36 | 35 vitarum nobis 37 | 36 erunt instituta 38 | 37 Non igitur 39 | 38 de improbo, 40 | 39 sed de 41 | 40 callido improbo 42 | 41 quaerimus, qualis 43 | 42 Q. Audio 44 | 43 equidem philosophi 45 | 44 vocem, Epicure, 46 | 45 sed quid 47 | 46 tibi dicendum 48 | 47 sit oblitus 49 | 48 es. Ex 50 | 49 ea difficultate 51 | 50 illae fallaciloquae, 52 | 51 ut ait 53 | 52 Accius, malitiae 54 | 53 natae sunt. 55 | 54 At multis 56 | 55 malis affectus. 57 | 56 Nam quibus 58 | 57 rebus efficiuntur 59 | 58 voluptates, eae 60 | 59 non sunt 61 | 60 in potestate 62 | 61 sapientis. Quis 63 | 62 est tam 64 | 63 dissimile homini. 65 | 64 Ut proverbia 66 | 65 non nulla 67 | 66 veriora sint 68 | 67 quam vestra 69 | 68 dogmata. Si 70 | 69 quicquam extra 71 | 70 virtutem habeatur 72 | 71 in bonis. 73 | 72 Sed plane 74 | 73 dicit quod 75 | 74 intellegit. Paulum, 76 | 75 cum regem 77 | 76 Persem captum 78 | 77 adduceret, eodem 79 | 78 flumine invectio? 80 | 79 Qui ita 81 | 80 affectus, beatum 82 | 81 esse numquam 83 | 82 probabis; Sed 84 | 83 nimis multa. 85 | 84 Nam prius 86 | 85 a se 87 | 86 poterit quisque 88 | 87 discedere quam 89 | 88 appetitum earum 90 | 89 rerum, quae 91 | 90 sibi conducant, 92 | 91 amittere. Familiares 93 | 92 nostros, credo, 94 | 93 Sironem dicis 95 | 94 et Philodemum, 96 | 95 cum optimos 97 | 96 viros, tum 98 | 97 homines doctissimos. 99 | 98 Quod iam 100 | 99 a me 101 | 100 expectare noli. 102 | 101 Quid ergo? 103 | 102 Eademne, quae 104 | 103 restincta siti? 105 | 104 Ita relinquet 106 | 105 duas, de 107 | 106 quibus etiam 108 | 107 atque etiam 109 | 108 consideret. Illa 110 | 109 videamus, quae 111 | 110 a te 112 | 111 de amicitia 113 | 112 dicta sunt. 114 | 113 Eaedem res 115 | 114 maneant alio 116 | 115 modo. Quid 117 | 116 ergo attinet 118 | 117 gloriose loqui, 119 | 118 nisi constanter 120 | 119 loquare? Prioris 121 | 120 generis est 122 | 121 docilitas, memoria; 123 | 122 Portenta haec 124 | 123 esse dicit, 125 | 124 neque ea 126 | 125 ratione ullo 127 | 126 modo posse 128 | 127 vivi; Beatum, 129 | 128 inquit. Bestiarum 130 | 129 vero nullum 131 | 130 iudicium puto. 132 | 131 Quem Tiberina 133 | 132 descensio festo 134 | 133 illo die 135 | 134 tanto gaudio 136 | 135 affecit, quanto 137 | 136 L. Quorum 138 | 137 sine causa 139 | 138 fieri nihil 140 | 139 putandum est. 141 | 140 Tria genera 142 | 141 bonorum; Nunc 143 | 142 dicam de 144 | 143 voluptate, nihil 145 | 144 scilicet novi, 146 | 145 ea tamen, 147 | 146 quae te 148 | 147 ipsum probaturum 149 | 148 esse confidam. 150 | 149 Illud dico, 151 | 150 ea, quae 152 | 151 dicat, praeclare 153 | 152 inter se 154 | 153 cohaerere. Fortemne 155 | 154 possumus dicere 156 | 155 eundem illum 157 | 156 Torquatum? Hoc 158 | 157 tu nunc 159 | 158 in illo 160 | 159 probas. Cur 161 | 160 post Tarentum 162 | 161 ad Archytam? 163 | 162 Indicant pueri, 164 | 163 in quibus 165 | 164 ut in 166 | 165 speculis natura 167 | 166 Sed tamen 168 | 167 est aliquid, 169 | 168 quod nobis 170 | 169 non liceat, 171 | 170 liceat illis. 172 | 171 Virtutis, magnitudinis 173 | 172 animi, patientiae, 174 | 173 fortitudinis fomentis 175 | 174 dolor mitigari 176 | 175 solet. Piso 177 | 176 igitur hoc 178 | 177 modo, vir 179 | 178 optimus tuique, 180 | 179 ut scis, 181 | 180 amantissimus. Non 182 | 181 prorsus, inquit, 183 | 182 omnisque, qui 184 | 183 sine dolore 185 | 184 sint, in 186 | 185 voluptate, et 187 | 186 ea quidem 188 | 187 summa, esse 189 | 188 dico. Potius 190 | 189 inflammat, ut 191 | 190 coercendi magis 192 | 191 quam dedocendi 193 | 192 esse videantur. 194 | 193 Virtutis, magnitudinis 195 | 194 animi, patientiae, 196 | 195 fortitudinis fomentis 197 | 196 dolor mitigari 198 | 197 solet. Quae 199 | 198 fere omnia 200 | 199 appellantur uno 201 | 200 ingenii nomine, 202 | 201 easque virtutes 203 | 202 qui habent, 204 | 203 ingeniosi vocantur. 205 | 204 Nec enim, 206 | 205 dum metuit, 207 | 206 iustus est, 208 | 207 et certe, 209 | 208 si metuere 210 | 209 destiterit, non -------------------------------------------------------------------------------- /module_12/src/civil_registry/CivilRegistry.java: -------------------------------------------------------------------------------- 1 | 2 | package civil_registry; 3 | 4 | import java.time.LocalDate; 5 | import java.util.*; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | public class CivilRegistry { 10 | private static Set registry = new HashSet<>(); 11 | 12 | private static CivilRegistry instance; 13 | 14 | public static CivilRegistry getInstance() { 15 | if(instance == null) 16 | instance = new CivilRegistry(); 17 | return instance; 18 | } 19 | 20 | public void insertPerson(Person person) { 21 | registry.add(person); 22 | } 23 | 24 | public void removePerson(String fiscalCode) { 25 | registry = registry.stream() 26 | .filter(person -> !person.getFiscalCode().equals(fiscalCode)) 27 | .collect(Collectors.toSet()); 28 | //ANOTHER SOLUTION 29 | //registry.removeIf(person -> person.getFiscalCode().equals(fiscalCode)); 30 | //BOTH ARE SLOWER THAN SIMPLE ITERATION + BREAK WHEN FOUND 31 | } 32 | 33 | public Set getPeopleByName(String name) { 34 | return registry.stream() 35 | .filter(person -> person.getName().equals(name) || person.getName().startsWith(name)) 36 | .collect(Collectors.toSet()); 37 | } 38 | 39 | public Set getOldestPeople() { 40 | return registry.stream() 41 | .sorted(Comparator.comparing(Person::getBirthDate)) 42 | //ANOTHER VERSION 43 | //.sorted((o1, o2) -> o1.getBirthDate().compareTo(o2.getBirthDate())) 44 | .limit(3) 45 | .collect(Collectors.toSet()); 46 | } 47 | 48 | public Set getAddressesByName(String name) { 49 | return getPeopleByName(name).stream() 50 | .map(Person::getAddress) 51 | .collect(Collectors.toSet()); 52 | } 53 | 54 | public Set getChildren(String name) { 55 | return getPeopleByName(name).stream() 56 | .map(Person::getChildren) 57 | .flatMap(Collection::stream) 58 | .collect(Collectors.toSet()); 59 | } 60 | 61 | public static void main(String[] args) { 62 | Person p0 = new Person("chiara", "rossi", "0", 63 | "Via Torino", LocalDate.of(1997, 12, 22), new HashSet<>()); 64 | Person p3 = new Person("marta", "rossi", "3", 65 | "Via Torino", LocalDate.of(1985, 12, 22), new HashSet<>()); 66 | Person p4 = new Person("piero", "rossi", "4", 67 | "Via Ragusa", LocalDate.of(1995, 12, 22), new HashSet<>()); 68 | Person p1 = new Person("cristina", "rossi", "1", 69 | "Via Roma", LocalDate.of(1945, 12, 22), new HashSet<>()); 70 | Person p2 = new Person("mario", "rossi", "2", 71 | "Via Milano", LocalDate.of(1935, 12, 22), Stream.of(p3).collect(Collectors.toSet())); 72 | Person p5 = new Person("mario alberto", "rossi", "5", 73 | "Via Palermo", LocalDate.of(1946, 12, 22), Stream.of(p4, p0).collect(Collectors.toSet())); 74 | CivilRegistry civilRegistry = CivilRegistry.getInstance(); 75 | civilRegistry.insertPerson(p1); 76 | civilRegistry.insertPerson(p2); 77 | civilRegistry.insertPerson(p3); 78 | civilRegistry.insertPerson(p4); 79 | civilRegistry.insertPerson(p5); 80 | Set oldest = civilRegistry.getOldestPeople(); 81 | System.out.println(oldest.size() == 3); 82 | System.out.println(oldest.contains(p1) && oldest.contains(p2) && oldest.contains(p5)); 83 | Set marios = civilRegistry.getPeopleByName("mario"); 84 | System.out.println(marios.size() == 2); 85 | Set addresses = civilRegistry.getAddressesByName("mario"); 86 | System.out.println(addresses.size() == 2); 87 | Set children = civilRegistry.getChildren("mario"); 88 | System.out.println(children.size() == 3); 89 | } 90 | 91 | 92 | } 93 | 94 | -------------------------------------------------------------------------------- /module_12/src/civil_registry/Person.java: -------------------------------------------------------------------------------- 1 | package civil_registry; 2 | import java.time.LocalDate; 3 | import java.util.Comparator; 4 | import java.util.List; 5 | import java.util.Objects; 6 | import java.util.Set; 7 | 8 | public class Person implements Comparable { 9 | private String name, surname, fiscalCode, address; 10 | private LocalDate birthDate; 11 | private Set children; 12 | 13 | public Person(String name, String surname, String fiscalCode, 14 | String address, LocalDate birthDate, Set children) { 15 | this.name = name; 16 | this.surname = surname; 17 | this.fiscalCode = fiscalCode; 18 | this.address = address; 19 | this.birthDate = birthDate; 20 | this.children = children; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public String getSurname() { 28 | return surname; 29 | } 30 | 31 | public String getFiscalCode() { 32 | return fiscalCode; 33 | } 34 | 35 | public String getAddress() { 36 | return address; 37 | } 38 | 39 | public LocalDate getBirthDate() { 40 | return birthDate; 41 | } 42 | 43 | public Set getChildren() { 44 | return children; 45 | } 46 | 47 | @Override 48 | public boolean equals(Object o) { 49 | if (this == o) return true; 50 | if (o == null || getClass() != o.getClass()) return false; 51 | Person person = (Person) o; 52 | return Objects.equals(fiscalCode, person.fiscalCode); 53 | } 54 | 55 | @Override 56 | public int hashCode() { 57 | return Objects.hash(fiscalCode); 58 | } 59 | 60 | @Override 61 | public int compareTo(Person o) { 62 | return Comparator 63 | .comparing(Person::getFiscalCode) 64 | .compare(this, o); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /module_12/src/civil_registry/README🛵.md: -------------------------------------------------------------------------------- 1 | Esercizio Civil Registry 🛵 2 | 3 | Scrivere un programma che permetta di gestire un ufficio dell'anagrafe. In particolare, bisogna 4 | gestire una lista di persone, ognuna con nome, cognome, età, codice fiscale e indirizzo di residenza. 5 | Inoltre, devono essere possibili le seguenti operazioni: 6 | 7 | - inserisci persona: inserisce la persona nel sistema 8 | - rimuovi persona da codice fiscale: rimuove una persona con il corrispondente codice fiscale dal sistema 9 | - ottieni persone per nome: dato un nome, ritorna le persone che hanno un nome che corrisponde 10 | o inizia con quello in input 11 | - ottieni le 3 persone più anziane: ritorna le 3 persone più anziane presenti nel sistema 12 | - ottieni indirizzi per nome: dato un nome, ritorna l'indirizzo di tutte le persone con nome 13 | corrispondente a quello in input 14 | 15 | PLUS 🏍: gestire, per ogni persona, la lista dei figli ed implementare un metodo getFigli(nome) 16 | che ritorna la lista di persone il cui genitore ha il nome che corrisponde o inizia con quello in input 17 | Esempio: 18 | 19 | ``` 20 | andrea rossi -> [cristina, giorgio] 21 | andrea bianchi -> [mario] 22 | getFigli("andrea") -> [cristina, giorgio, mario] 23 | ``` 24 | -------------------------------------------------------------------------------- /module_12/src/letters_count/LettersCount.java: -------------------------------------------------------------------------------- 1 | package letters_count; 2 | 3 | import java.util.List; 4 | 5 | public class LettersCount { 6 | 7 | static int lettersCount(List names) { 8 | return names.stream() 9 | .filter(name -> name.toLowerCase().startsWith("f")) 10 | .map(String::length) 11 | .reduce(0, Integer::sum); 12 | 13 | } 14 | 15 | public static void main(String[] args) { 16 | List names = List.of("marco", "franco", "federico", "mario"); 17 | System.out.println(lettersCount(names) == 14); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /module_12/src/letters_count/README🛴.md: -------------------------------------------------------------------------------- 1 | Esercizio Letters Count 🛴 2 | 3 | Scrivere un programma Java che restituisca, a partire da una lista di nomi, la somma totale 4 | delle lettere contenute in ogni nome che inizia con la lettera "f" 5 | 6 | Suggerimento: realizzatelo prima senza Stream, poi con Stream 7 | 8 | -------------------------------------------------------------------------------- /module_13/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | module_13 9 | 1.0-SNAPSHOT 10 | 11 | 12 | com.google.code.gson 13 | gson 14 | 2.8.6 15 | 16 | 17 | com.sparkjava 18 | spark-core 19 | 2.9.3 20 | 21 | 22 | org.slf4j 23 | slf4j-api 24 | 1.7.36 25 | 26 | 27 | org.slf4j 28 | slf4j-simple 29 | 1.7.36 30 | 31 | 32 | 33 | 34 | 17 35 | 17 36 | 37 | 38 | -------------------------------------------------------------------------------- /module_13/src/main/java/mini_ecommerce/MiniEcommerce.java: -------------------------------------------------------------------------------- 1 | package mini_ecommerce; 2 | 3 | import com.google.gson.Gson; 4 | 5 | import java.util.*; 6 | 7 | import static spark.Spark.*; 8 | 9 | public class MiniEcommerce { 10 | 11 | private static Gson gson = new Gson(); 12 | 13 | private static Set products = new HashSet<>(); 14 | 15 | public static void main(String[] args) { 16 | path("/module_13/ecommerce", () -> { 17 | path("/product", () -> { 18 | post("/add", (req, res) -> { 19 | Product product = gson.fromJson(req.body(), Product.class); 20 | if(products.contains(product)){ 21 | res.status(400); 22 | return "already present"; 23 | } 24 | products.add(product); 25 | res.status(200); 26 | return "ok"; 27 | }); 28 | delete("/remove", (req, res) -> { 29 | String productId = req.queryParams("id"); 30 | 31 | products.removeIf(p->p.getId().equals(productId)); 32 | res.status(200); 33 | return "ok"; 34 | }); 35 | post("/buy", (req, res) -> { 36 | String productId = req.queryParams("id"); 37 | String quantityString = req.queryParams("quantity"); 38 | if(productId == null || quantityString == null) { 39 | res.status(400); 40 | return "malformed request"; 41 | } 42 | int quantity = Integer.parseInt(quantityString); 43 | Optional productIdOptional = getProduct(productId); 44 | if(productIdOptional.isPresent()) { 45 | res.status(404); 46 | return "not found"; 47 | } 48 | Product product = productIdOptional.get(); 49 | if(product.getStockAvailability() < quantity) { 50 | res.status(404); 51 | return "out of stock"; 52 | } 53 | product.decreaseStockAvailability(quantity); 54 | res.status(200); 55 | return "ok"; 56 | }); 57 | }); 58 | path("/products", () -> { 59 | get("/available", (req, res) -> { 60 | res.type("application/json"); 61 | res.status(200); 62 | return gson.toJson(products); 63 | }); 64 | }); 65 | }); 66 | 67 | } 68 | 69 | private static Optional getProduct(String productId) { 70 | return products.stream() 71 | .filter(prod -> prod.getId().equals(productId)) 72 | .findFirst(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /module_13/src/main/java/mini_ecommerce/MiniEcommerce.postman_collection.json: -------------------------------------------------------------------------------- 1 | 2 | "info": { 3 | "_postman_id": "582dc870-f0da-41da-bc65-ed62d44f6023", 4 | "name": "MiniEcommerce", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "add product", 10 | "request": { 11 | "method": "POST", 12 | "header": [], 13 | "body": { 14 | "mode": "raw", 15 | "raw": "{\n \"id\": \"1\",\n \"name\": \"ciaone\",\n \"description\": \"ciao ciao\",\n \"stockAvailability\": \"5\"\n}", 16 | "options": { 17 | "raw": { 18 | "language": "json" 19 | } 20 | } 21 | }, 22 | "url": { 23 | "raw": "http://localhost:4567/ecommerce/product/add", 24 | "protocol": "http", 25 | "host": [ 26 | "localhost" 27 | ], 28 | "port": "4567", 29 | "path": [ 30 | "ecommerce", 31 | "product", 32 | "add" 33 | ] 34 | } 35 | }, 36 | "response": [] 37 | }, 38 | { 39 | "name": "available products", 40 | "request": { 41 | "method": "GET", 42 | "header": [], 43 | "url": { 44 | "raw": "http://localhost:4567/ecommerce/products/available", 45 | "protocol": "http", 46 | "host": [ 47 | "localhost" 48 | ], 49 | "port": "4567", 50 | "path": [ 51 | "ecommerce", 52 | "products", 53 | "available" 54 | ] 55 | } 56 | }, 57 | "response": [] 58 | }, 59 | { 60 | "name": "buy product", 61 | "request": { 62 | "method": "POST", 63 | "header": [], 64 | "url": { 65 | "raw": "http://localhost:4567/ecommerce/product/buy?id=1&quantity=1", 66 | "protocol": "http", 67 | "host": [ 68 | "localhost" 69 | ], 70 | "port": "4567", 71 | "path": [ 72 | "ecommerce", 73 | "product", 74 | "buy" 75 | ], 76 | "query": [ 77 | { 78 | "key": "id", 79 | "value": "1" 80 | }, 81 | { 82 | "key": "quantity", 83 | "value": "1" 84 | } 85 | ] 86 | } 87 | }, 88 | "response": [] 89 | } 90 | ] 91 | } -------------------------------------------------------------------------------- /module_13/src/main/java/mini_ecommerce/Product.java: -------------------------------------------------------------------------------- 1 | package mini_ecommerce; 2 | 3 | import java.util.Objects; 4 | 5 | public class Product { 6 | private String id; 7 | private String name, description; 8 | private double price; 9 | private int stockAvailability; 10 | 11 | public Product(String id, String name, String description, 12 | double price, int stockAvailability) { 13 | this.id = id; 14 | this.name = name; 15 | this.description = description; 16 | this.price = price; 17 | this.stockAvailability = stockAvailability; 18 | } 19 | 20 | public String getId() { 21 | return id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public String getDescription() { 29 | return description; 30 | } 31 | 32 | public double getPrice() { 33 | return price; 34 | } 35 | 36 | public int getStockAvailability() { 37 | return stockAvailability; 38 | } 39 | 40 | public void decreaseStockAvailability(int quantity) { 41 | stockAvailability -= quantity; 42 | } 43 | 44 | @Override 45 | public boolean equals(Object o) { 46 | if (this == o) return true; 47 | if (o == null || getClass() != o.getClass()) return false; 48 | Product product = (Product) o; 49 | return Objects.equals(id, product.id); 50 | } 51 | 52 | @Override 53 | public int hashCode() { 54 | return Objects.hash(id); 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return name + " - " + description; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /module_13/src/main/java/mini_ecommerce/README.md: -------------------------------------------------------------------------------- 1 | # Esercizio Mini E-Commerce 🛴 2 | 3 | Creare un Web Service in grado di gestire una piccola piattaforma di e-commerce dedicata 4 | alla vendita di prodotti. Ogni prodotto acquistabile possiede un id univoco, un nome, una breve 5 | descrizione, una quantità di disponibilità in stock e un prezzo. 6 | In particolare, devono essere esposte tramite API le seguenti operazioni: 7 | 8 | - aggiungi prodotto: aggiunge un prodotto alla lista dei prodotti disponibili 9 | - elimina prodotto: rimuove un prodotto dalla lista dei prodotti disponibili 10 | - elenco prodotti disponibili: ritorna la lista dei prodotti disponibili 11 | - PLUS 🛵: acquista prodotto (specificando l'id del prodotto e la quantità) 12 | 13 | Utilizzate i giusti codici di stato per gestire ad esempio prodotti inesistenti, stock 14 | terminato ecc. 15 | 16 | Se avete difficoltà col formato JSON, chiamatemi e lo facciamo insieme :) 17 | -------------------------------------------------------------------------------- /module_13/src/main/java/tree_express/Delivery.java: -------------------------------------------------------------------------------- 1 | package tree_express; 2 | 3 | import java.util.Objects; 4 | import java.util.UUID; 5 | 6 | public class Delivery { 7 | private UUID id; 8 | private TreeExpressUser sender; 9 | private TreeExpressUser receiver; 10 | private double weight; 11 | private DeliveryType deliveryType; 12 | 13 | public Delivery(UUID id, TreeExpressUser sender, TreeExpressUser receiver, double weight, DeliveryType deliveryType) { 14 | this.id = id; 15 | this.sender = sender; 16 | this.receiver = receiver; 17 | this.weight = weight; 18 | this.deliveryType = deliveryType; 19 | } 20 | 21 | public UUID getId() { 22 | return id; 23 | } 24 | 25 | public TreeExpressUser getSender() { 26 | return sender; 27 | } 28 | 29 | public TreeExpressUser getReceiver() { 30 | return receiver; 31 | } 32 | 33 | public double getWeight() { 34 | return weight; 35 | } 36 | 37 | public DeliveryType getDeliveryType() { 38 | return deliveryType; 39 | } 40 | 41 | public void setDeliveryType(DeliveryType deliveryType) { 42 | this.deliveryType = deliveryType; 43 | } 44 | 45 | @Override 46 | public boolean equals(Object o) { 47 | if (this == o) return true; 48 | if (o == null || getClass() != o.getClass()) return false; 49 | Delivery delivery = (Delivery) o; 50 | return Objects.equals(id, delivery.id); 51 | } 52 | 53 | @Override 54 | public int hashCode() { 55 | return Objects.hash(id); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /module_13/src/main/java/tree_express/DeliveryType.java: -------------------------------------------------------------------------------- 1 | package tree_express; 2 | 3 | public enum DeliveryType { 4 | SHIPPING, SHIPPED 5 | } 6 | -------------------------------------------------------------------------------- /module_13/src/main/java/tree_express/README.md: -------------------------------------------------------------------------------- 1 | # Esercizio TreeExpress 🛵 2 | 3 | Creare un Web Service in grado di gestire un servizio di spedizione di pacchi. Ogni spedizione 4 | può avere 2 stati: in consegna e consegnata. Ogni utente possiede un nome, un cognome e 5 | un indirizzo. 6 | In particolare, devono essere esposte tramite API le seguenti operazioni: 7 | 8 | - crea utente: crea un utente 9 | - crea spedizione: crea una nuova spedizione a partire da un codice 10 | utente mittente, un codice utente destinatario e un peso. Inoltre, la mette in consegna. 11 | - annulla spedizione: rimuove una spedizione, se non è già stata consegnata 12 | - consegna spedizione: imposta una spedizione come consegnata 13 | - spedizioni in transito: restituisce le spedizioni in transito 14 | - spedizioni in ingresso di un utente: dato un utente, ritorna la sua lista di spedizioni 15 | delle quali è destinatario 16 | 17 | Ogni spedizione ha un codice, un peso, un mittente e un destinatario. 18 | 19 | Utilizzate i giusti codici di stato per gestire ad esempio prodotti inesistenti, stock 20 | terminato ecc. 21 | 22 | Se avete difficoltà col formato JSON, chiamatemi e lo facciamo insieme -------------------------------------------------------------------------------- /module_13/src/main/java/tree_express/TreeExpress.java: -------------------------------------------------------------------------------- 1 | package tree_express; 2 | 3 | import com.google.gson.Gson; 4 | 5 | import java.util.*; 6 | import java.util.stream.Collectors; 7 | 8 | import static spark.Spark.*; 9 | 10 | public class TreeExpress { 11 | 12 | private static TreeExpress instance; 13 | 14 | private static Gson gson = new Gson(); 15 | 16 | Map TreeExpressUsers = new HashMap<>(); 17 | List deliveries = new ArrayList<>(); 18 | 19 | private TreeExpress() { 20 | } 21 | 22 | public static TreeExpress getInstance() { 23 | if (instance == null) 24 | instance = new TreeExpress(); 25 | return instance; 26 | } 27 | 28 | public void startTreeExpressService() { 29 | path("/express", () -> { 30 | path("/TreeExpressUsers", () -> { 31 | post("/add", (req, res) -> { 32 | TreeExpressUser TreeExpressUser = gson.fromJson(req.body(), TreeExpressUser.class); 33 | if (TreeExpressUsers.containsKey(TreeExpressUser.getUuid().toString())) { 34 | res.status(400); 35 | return "already present"; 36 | } 37 | TreeExpressUsers.put(TreeExpressUser.getUuid().toString(), TreeExpressUser); 38 | res.status(201); 39 | return "ok"; 40 | }); 41 | }); 42 | path("/delivery", () -> { 43 | post("/create", (req, res) -> { 44 | String senderId = req.queryParams("senderId"); 45 | String receiverId = req.queryParams("receiverId"); 46 | if(!TreeExpressUsers.containsKey(senderId) || !TreeExpressUsers.containsKey(receiverId)) { 47 | res.status(400); 48 | return "bad request"; 49 | } 50 | TreeExpressUser sender = TreeExpressUsers.get(senderId); 51 | TreeExpressUser receiver = TreeExpressUsers.get(receiverId); 52 | String weight = req.queryParams("weight"); 53 | if(weight == null) { 54 | res.status(400); 55 | return "bad request"; 56 | } 57 | Double w = Double.parseDouble(weight); 58 | if (sender == null || receiver == null) { 59 | res.status(404); 60 | return "TreeExpressUser not found"; 61 | } 62 | Delivery delivery = new Delivery(UUID.randomUUID(), sender, receiver, 63 | w, DeliveryType.SHIPPING); 64 | if (deliveries.contains(delivery)) { 65 | res.status(400); 66 | return "already present"; 67 | } 68 | deliveries.add(delivery); 69 | res.status(201); 70 | return "ok"; 71 | }); 72 | delete("/remove", (req, res) -> { 73 | String deliveryId = req.queryParams("id"); 74 | Optional delivery = deliveries.stream() 75 | .filter(d -> d.getId().toString().equals(deliveryId)) 76 | .findFirst(); 77 | if (delivery.isPresent()) { 78 | res.status(404); 79 | return "not found"; 80 | } 81 | if (delivery.get().getDeliveryType() == DeliveryType.SHIPPED) { 82 | res.status(403); 83 | return "not allowed"; 84 | } 85 | deliveries.remove(delivery.get()); 86 | res.status(200); 87 | return "ok"; 88 | }); 89 | put("/shipped", (req, res) -> { 90 | String deliveryId = req.queryParams("id"); 91 | Optional delivery = deliveries.stream() 92 | .filter(d -> d.getId().toString().equals(deliveryId)) 93 | .findFirst(); 94 | if (delivery.isPresent()) { 95 | res.status(404); 96 | return "not found"; 97 | } 98 | delivery.get().setDeliveryType(DeliveryType.SHIPPED); 99 | res.status(201); 100 | return "ok"; 101 | }); 102 | 103 | }); 104 | 105 | path("/deliveries", () -> { 106 | get("/shipping", (req, res) -> { 107 | List shippingDeliveries = deliveries.stream() 108 | .filter(delivery -> delivery.getDeliveryType().equals(DeliveryType.SHIPPING)) 109 | .collect(Collectors.toList()); 110 | res.type("application/json"); 111 | res.body(); 112 | res.status(200); 113 | return gson.toJson(shippingDeliveries); 114 | }); 115 | get("/TreeExpressUser", (req, res) -> { 116 | String receiverId = req.queryParams("receiver"); 117 | if(!TreeExpressUsers.containsKey(receiverId)) { 118 | res.status(400); 119 | return "bad request"; 120 | } 121 | TreeExpressUser receiver = TreeExpressUsers.get(receiverId); 122 | List TreeExpressUserDeliveries = deliveries.stream() 123 | .filter(delivery -> delivery.getReceiver().equals(receiver)) 124 | .collect(Collectors.toList()); 125 | res.type("application/json"); 126 | res.body(); 127 | res.status(200); 128 | return gson.toJson(TreeExpressUserDeliveries); 129 | }); 130 | }); 131 | 132 | }); 133 | } 134 | 135 | public static void main(String[] args) { 136 | TreeExpress treeExpress = TreeExpress.getInstance(); 137 | treeExpress.startTreeExpressService(); 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /module_13/src/main/java/tree_express/TreeExpress.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "9584f714-dc9a-4668-aec9-b0427a54edcc", 4 | "name": "TreeExpress", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "add user 1", 10 | "request": { 11 | "method": "POST", 12 | "header": [], 13 | "body": { 14 | "mode": "raw", 15 | "raw": "{\n \"uuid\": \"433f493d-205d-4a7a-9551-438954f31991\",\n \"name\": \"marco\",\n \"lastname\": \"bianchi\",\n \"address\": \"via rosis 3\"\n}", 16 | "options": { 17 | "raw": { 18 | "language": "json" 19 | } 20 | } 21 | }, 22 | "url": { 23 | "raw": "http://localhost:4567/express/users/add", 24 | "protocol": "http", 25 | "host": [ 26 | "localhost" 27 | ], 28 | "port": "4567", 29 | "path": [ 30 | "express", 31 | "users", 32 | "add" 33 | ] 34 | } 35 | }, 36 | "response": [] 37 | }, 38 | { 39 | "name": "add user 2", 40 | "request": { 41 | "method": "POST", 42 | "header": [], 43 | "body": { 44 | "mode": "raw", 45 | "raw": "{\n \"uuid\": \"10705d39-07c8-40a9-beab-2a5ad0f647bd\",\n \"name\": \"mario\",\n \"lastname\": \"rossi\",\n \"address\": \"via rosis 3\"\n}", 46 | "options": { 47 | "raw": { 48 | "language": "json" 49 | } 50 | } 51 | }, 52 | "url": { 53 | "raw": "http://localhost:4567/express/users/add", 54 | "protocol": "http", 55 | "host": [ 56 | "localhost" 57 | ], 58 | "port": "4567", 59 | "path": [ 60 | "express", 61 | "users", 62 | "add" 63 | ] 64 | } 65 | }, 66 | "response": [] 67 | }, 68 | { 69 | "name": "create delivery", 70 | "request": { 71 | "method": "POST", 72 | "header": [], 73 | "url": { 74 | "raw": "http://localhost:4567/express/delivery/create?senderId=433f493d-205d-4a7a-9551-438954f31991&receiverId=10705d39-07c8-40a9-beab-2a5ad0f647bd&weight=25", 75 | "protocol": "http", 76 | "host": [ 77 | "localhost" 78 | ], 79 | "port": "4567", 80 | "path": [ 81 | "express", 82 | "delivery", 83 | "create" 84 | ], 85 | "query": [ 86 | { 87 | "key": "senderId", 88 | "value": "433f493d-205d-4a7a-9551-438954f31991" 89 | }, 90 | { 91 | "key": "receiverId", 92 | "value": "10705d39-07c8-40a9-beab-2a5ad0f647bd" 93 | }, 94 | { 95 | "key": "weight", 96 | "value": "25" 97 | } 98 | ] 99 | } 100 | }, 101 | "response": [] 102 | }, 103 | { 104 | "name": "get shipping deliveries", 105 | "request": { 106 | "method": "GET", 107 | "header": [], 108 | "url": { 109 | "raw": "http://localhost:4567/express/deliveries/shipping", 110 | "protocol": "http", 111 | "host": [ 112 | "localhost" 113 | ], 114 | "port": "4567", 115 | "path": [ 116 | "express", 117 | "deliveries", 118 | "shipping" 119 | ] 120 | } 121 | }, 122 | "response": [] 123 | }, 124 | { 125 | "name": "set shipped delivery", 126 | "request": { 127 | "method": "PUT", 128 | "header": [], 129 | "url": { 130 | "raw": "http://localhost:4567/express/delivery/shipped?id=1f9b3208-a7e9-458e-814d-885858be589e", 131 | "protocol": "http", 132 | "host": [ 133 | "localhost" 134 | ], 135 | "port": "4567", 136 | "path": [ 137 | "express", 138 | "delivery", 139 | "shipped" 140 | ], 141 | "query": [ 142 | { 143 | "key": "id", 144 | "value": "1f9b3208-a7e9-458e-814d-885858be589e" 145 | } 146 | ] 147 | } 148 | }, 149 | "response": [] 150 | }, 151 | { 152 | "name": "user inbound deliveries", 153 | "request": { 154 | "method": "GET", 155 | "header": [], 156 | "url": { 157 | "raw": "http://localhost:4567/express/deliveries/user?receiver=10705d39-07c8-40a9-beab-2a5ad0f647bd", 158 | "protocol": "http", 159 | "host": [ 160 | "localhost" 161 | ], 162 | "port": "4567", 163 | "path": [ 164 | "express", 165 | "deliveries", 166 | "user" 167 | ], 168 | "query": [ 169 | { 170 | "key": "receiver", 171 | "value": "10705d39-07c8-40a9-beab-2a5ad0f647bd" 172 | } 173 | ] 174 | } 175 | }, 176 | "response": [] 177 | } 178 | ] 179 | } -------------------------------------------------------------------------------- /module_13/src/main/java/tree_express/TreeExpressUser.java: -------------------------------------------------------------------------------- 1 | package tree_express; 2 | 3 | import java.util.Objects; 4 | import java.util.UUID; 5 | 6 | public class TreeExpressUser { 7 | private UUID uuid; 8 | private String name, lastname, address; 9 | 10 | public TreeExpressUser(UUID uuid, String name, String lastname, String address) { 11 | this.uuid = uuid; 12 | this.name = name; 13 | this.lastname = lastname; 14 | this.address = address; 15 | } 16 | 17 | public UUID getUuid() { 18 | return uuid; 19 | } 20 | 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public String getLastname() { 26 | return lastname; 27 | } 28 | 29 | public String getAddress() { 30 | return address; 31 | } 32 | 33 | @Override 34 | public boolean equals(Object o) { 35 | if (this == o) return true; 36 | if (o == null || getClass() != o.getClass()) return false; 37 | TreeExpressUser user = (TreeExpressUser) o; 38 | return Objects.equals(uuid, user.uuid); 39 | } 40 | 41 | @Override 42 | public int hashCode() { 43 | return Objects.hash(uuid); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /module_16/ecommerce/README.md: -------------------------------------------------------------------------------- 1 | Realizzare un database per modellare una piattaforma di ecommerce dove vengono venduti dei prodotti. Ogni prodotto ha un nome e un prezzo. 2 | Ogni utente ha un id e un nome e può comprare prodotti. 3 | Ogni utente può effettuare la recensione di un prodotto. Ogni recensione ha un testo e un punteggio da 1 a 5. 4 | 5 | PLUS: 6 | Scrivere la seguente query: 7 | - ottenere il prezzo medio dei prodotti 8 | - ottenere il numero di prodotti disponibili -------------------------------------------------------------------------------- /module_16/ecommerce/ecommerce.drawio: -------------------------------------------------------------------------------- 1 | 5Vpbc6M2GP01nmkfnAGEAD8mTtqdabezbZrZzb7sKEYLSgBRIWJ7f30lEOYiJ3YzMXLtl0T6dEE657tJ1gTM09WvDOXxRxriZOJY4WoCrieO4wAPin9Ssq4lvu3UgoiRsBbZreCW/MBKaClpSUJc9DpyShNO8r5wQbMML3hPhhijy3637zTpfzVHEdYEtwuU6NLPJORxLQ0cv5V/wCSKmy/b3qxuSVHTWe2kiFFIlx0RuJmAOaOU16V0NceJBK/BpR73ywutm4UxnPF9Blw+Lct/ps6CPn74/vwbuvv65zSdemofBV83O8ahAEBVKeMxjWiGkptWesVomYVYTmuJWtvnd0pzIbSF8BFzvlZsopJTIYp5mqhWvCL8S6d8L6e6gKp2vVIzV5V1U8k4W28GyUpnlKy2w6paM67en9zUi7gpUUFLtsCvgAU8pYCIRZi/0tH1N/wKw8A0xWJFYiDDCeLkub8SpDQ02vRrSRQFxeN/4LRZ5jNKSvWpvxnKCrTghGYa3302lzHh+DZHFRBLYdN95tTMmHG8eh1PffdqAPDcekjjEZR9LFvzshubiTum5VmHwiswaQOt3t93WnbYgGXOBmZ72gD0jNrATLOBuwIz48rvWj3d3yi1MeVvrO8YlN/aU/kvXAf2DWAWBDtMoKp9wowI2IQevLtdNMQeeWxoltmxi0+MhqXInEybhmf3bQMYDwyurYEypm28JTnqxIL7btvhA4ML9jSA2jUbMwDn/5LwGuHGaNBultlxTg/lWndMMU0fymIUp2SDvlOybd0pBVt8UnAwn+RqGP0kvjX/42cNJ7Fr3gcEJSTKRHkhdi+D4JXEhojD7qVqSEkY1hqPC/IDPVRTSWXMKcl4tRd4NYHXci6h5EWt73LqgjP6hOc0oTK4ZjTD70MAHCRMjo6/uwV/52D4Qx1/sYO5faL4g0FU3hKUx8Xf1/DP6wTmG28PuYVRpwGD3Upre6N6jeC8vIYbHJnW6sfRk8bfG+APXMMEQD1s/oWfCV7qjmLs67BBhuFucxajHns8o/dhhlJkuO/dbq1JplJkqN/tskqPP1Lx12jUswep2rbz+6ipMjwzp2tbAwJM58qNhzqXXNkJdrvycQlwzosAFx4bAfqNhujvzGWgkYBXJSbiRhadJiNgyMhMZ2Q2KiN6IigZ8RKJ9QMTpUiWMpTq0fQkGJkODvTbzkZwCyPgYIzoNyrbGCFpLrLK0+QEzGb9yG2aEj3LfNlIhtKckcWJ2o4Phiku3IsoeCiifEcD+tifLph7vuM378eO+4jnA5OcvulJ1tS6sGy/T6wHwA5qD/2T/N58u5ZRvm3d2RYvXU6NeJ4fJtPA0qPSqOd5/9x++vIHBAQHO82IavsQtWrrPOcFN/8C -------------------------------------------------------------------------------- /module_16/ecommerce/ecommerce.sql: -------------------------------------------------------------------------------- 1 | PGDMP 2 | y ecommerce13.313.2� 00ENCODINGENCODINGSET client_encoding = 'UTF8'; 3 | false� 00 4 | STDSTRINGS 5 | STDSTRINGS(SET standard_conforming_strings = 'on'; 6 | false� 00 7 | SEARCHPATH 8 | SEARCHPATH8SELECT pg_catalog.set_config('search_path', '', false); 9 | false� 126224844 ecommerceDATABASE^CREATE DATABASE ecommerce WITH TEMPLATE = template0 ENCODING = 'UTF8' LOCALE = 'en_US.UTF-8'; 10 | DROP DATABASE ecommerce; 11 | postgresfalse�125924858productTABLEpCREATE TABLE public.product ( 12 | id bigint NOT NULL, 13 | name character varying, 14 | price double precision 15 | ); 16 | DROP TABLE public.product; 17 | publicheappostgresfalse�125924866product_transactionsTABLEoCREATE TABLE public.product_transactions ( 18 | idproduct bigint NOT NULL, 19 | idtransaction bigint NOT NULL 20 | ); 21 | (DROP TABLE public.product_transactions; 22 | publicheappostgresfalse�125924871reviewTABLE�CREATE TABLE public.review ( 23 | id bigint NOT NULL, 24 | iduser bigint, 25 | idproduct bigint, 26 | text character varying, 27 | rating bigint 28 | ); 29 | DROP TABLE public.review; 30 | publicheappostgresfalse�125924853 transactionTABLElCREATE TABLE public.transaction ( 31 | id bigint NOT NULL, 32 | iduser bigint, 33 | import double precision 34 | ); 35 | DROP TABLE public.transaction; 36 | publicheappostgresfalse�125924845userTABLESCREATE TABLE public."user" ( 37 | id bigint NOT NULL, 38 | name character varying 39 | ); 40 | DROP TABLE public."user"; 41 | publicheappostgresfalseA 260624865product product_pkey 42 | CONSTRAINTRALTER TABLE ONLY public.product 43 | ADD CONSTRAINT product_pkey PRIMARY KEY (id); 44 | >ALTER TABLE ONLY public.product DROP CONSTRAINT product_pkey; 45 | publicpostgresfalse202C 260624870.product_transactions product_transactions_pkey 46 | CONSTRAINT�ALTER TABLE ONLY public.product_transactions 47 | ADD CONSTRAINT product_transactions_pkey PRIMARY KEY (idtransaction, idproduct); 48 | XALTER TABLE ONLY public.product_transactions DROP CONSTRAINT product_transactions_pkey; 49 | publicpostgresfalse203203E 260624875review review_pkey 50 | CONSTRAINTPALTER TABLE ONLY public.review 51 | ADD CONSTRAINT review_pkey PRIMARY KEY (id); 52 | <ALTER TABLE ONLY public.review DROP CONSTRAINT review_pkey; 53 | publicpostgresfalse204? 260624857transaction transaction_pkey 54 | CONSTRAINTZALTER TABLE ONLY public.transaction 55 | ADD CONSTRAINT transaction_pkey PRIMARY KEY (id); 56 | FALTER TABLE ONLY public.transaction DROP CONSTRAINT transaction_pkey; 57 | publicpostgresfalse201= 260624852user user_pkey 58 | CONSTRAINTNALTER TABLE ONLY public."user" 59 | ADD CONSTRAINT user_pkey PRIMARY KEY (id); 60 | :ALTER TABLE ONLY public."user" DROP CONSTRAINT user_pkey; 61 | publicpostgresfalse200 -------------------------------------------------------------------------------- /module_16/ecommerce/ecommerce_er.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_16/ecommerce/ecommerce_er.png -------------------------------------------------------------------------------- /module_16/movies/README.md: -------------------------------------------------------------------------------- 1 | Realizzare un db per una piattaforma di gestione di film: ogni film deve avere un nome e un direttore. 2 | Gli utenti della piattaforma hanno un nome, un cognome e possono salvare una serie di film preferiti, oltre che naturalmente guardare film. 3 | Infine, ogni utente può lasciare una recensione di un film. -------------------------------------------------------------------------------- /module_16/movies/movies.drawio: -------------------------------------------------------------------------------- 1 | 5Vtdb5swFP01kbqHTLENJHlsk26Vtk7aqmrt3tzgglvAmXG++utnwISASZpVLU7CU+3rD/A5l3Ov7aaDRuHyK8dT/5q5JOjAnrvsoHEHQogcW/5JLKvM0neGmcHj1M1MoDDc0BeijD1lnVGXxKWOgrFA0GnZOGFRRCaiZMOcs0W52yMLyk+dYo9ohpsJDnTrb+oKP7MOYL+wXxHq+fmTQb6+EOed1UpiH7tssWFClx004oyJrBQuRyRIwMtxycZ92dK6fjFOIrHPgPPnxexvF07Y09Xj/Bu+/fOzG3ZzmGOxyldMXAmAqjIufOaxCAeXhfWCs1nkkmTanqwVfb4zNpVGII1PRIiVYhPPBJMmX4SBaiVLKu42yvfJVJ9tVRsv1cxpZZVXIsFXd5uVjVFJtRiW1vJx2fqSRW3FTZliNuMTsgss5X+Ye0Ts6Ddcsys/C8JCIt9HjuMkwILOy++BlX96634FhbKgWPwPRqF1OIz2d1NqgBqITHKj5p3jYKaedM3mlGiElelY+FSQmylOAVhImS1Dr+YkXJDlbhz1ZasByFZOo0TaUaqwKBQP5DLmb6hd3u/9gbIPx4kPXpbgnr4PLKO6BExSWtB4v9Fy9JRuJBImKNXk7DYm3Lya9UpiBm3TaoY0nMaUy2SVmcfKGR4aWEaVv/cm5S+U4b4kDB8uE9a+MmFSJZxjCeUGiNnycTZDjKXJ0gKLia9rks/Ch1nciB6ttUbpEejpejSokaPBR8lRXwPpTD5q9OOTBpNctCjjgQPqRbI8kYuXcRFdJNDQCQ7OVUNIXTfzdxLTF/yQTpW44pTRSKRLsS869jiZS7p4nHl7MnUsOHsmIxbIGILGEYvI++BvVcIB0OG3auCHHwX/oF3wo14Z/5qNWKPwA6NJuyHxHu4p3kaPEobah0Hj7VllgwrugIqC10hIowoO9G3KmVzCCJyohlj9A9MQfftz0hredw4shoI2ZuDgKFJwoOfgj3gu1yZV2qiKw4oTg6FpFW9ZIg7siorUHMw0qyJtS8UrYXS9MzVGgJ7y/SJzSha6UDR94Fo5cUU1YtHsISKELQx5OcKvhzyzF9Q9zY956sdb7kKbPH2yX3fkRqMeNHsa/pZLM9AxdmmGjsP/9f1QmHj+NjFv0P+t6talb9r/nXYlHZXbOGR66whrsu5TPjtZe/KOANAsAS3LuqsKZDzrhnrWfdJfQJUACxkmAOnpouwPR0mgTwBPS1zG7cg7TUaQZZcZqTnQHTbKiP5vjAkjTpBg/cBlyUtKEQ71bP4kGOlWLqnrjtjtGkbQhzECW84IGgzLjJgmRM/x20XIoLlPRFaLH1GkbRs/RUGX/wA= -------------------------------------------------------------------------------- /module_16/movies/movies_er.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-backend-2022-01/fb667b2bf9e8c4b9e3fc5e2652f4815d246e01a0/module_16/movies/movies_er.png -------------------------------------------------------------------------------- /module_16/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | module_16 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 8 13 | 8 14 | 15 | 16 | 17 | 18 | org.postgresql 19 | postgresql 20 | 42.3.3 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /module_16/src/main/java/ConnectionHandler.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | 3 | public class ConnectionHandler { 4 | public static final String DB_URL = "jdbc:postgresql://localhost:5432/my_db"; 5 | 6 | private final String connectionUrl; 7 | 8 | private Connection connection; 9 | 10 | 11 | public ConnectionHandler(String dbUrl, String schema, String username, String password) throws ClassNotFoundException { 12 | this.connectionUrl = dbUrl 13 | + "?currentSchema="+ schema 14 | + "&user="+username 15 | + "&password=" + password; 16 | 17 | // Occorre conoscere il nome del driver e il suo package 18 | Class.forName("org.postgresql.Driver"); 19 | } 20 | 21 | public Connection getConnection() throws SQLException { 22 | if ( this.connection == null || this.connection.isClosed() ) { 23 | // Se la connessione non esiste o e' chiusa, la crea 24 | this.connection = DriverManager.getConnection(connectionUrl); 25 | } 26 | // Ritorna la connessione 27 | return this.connection; 28 | 29 | } 30 | 31 | public void closeConnection() throws SQLException { 32 | if ( this.connection != null && !this.connection.isClosed()) { 33 | this.connection.close(); 34 | this.connection = null; 35 | } 36 | } 37 | 38 | public PreparedStatement getPreparedStatement(String query) throws SQLException { 39 | // Uso il metodo getConnection invece di accedere direttamente per 40 | // garantire che la connection sia attiva 41 | Connection conn = getConnection(); 42 | 43 | PreparedStatement stmnt = conn.prepareStatement(query); 44 | 45 | return stmnt; 46 | } 47 | 48 | public static void main(String[] args) throws ClassNotFoundException, SQLException { 49 | ConnectionHandler connectionHandler = new ConnectionHandler( 50 | ConnectionHandler.DB_URL, "public", "postgres", "postgres" 51 | ); 52 | //Connection c = connectionHandler.getConnection(); 53 | String query = "select * from tabella"; 54 | PreparedStatement p = connectionHandler.getPreparedStatement(query); 55 | ResultSet rs = p.executeQuery(); 56 | while(rs.next()) { 57 | System.out.println(rs.getString("col")); 58 | } 59 | 60 | } 61 | 62 | } 63 | --------------------------------------------------------------------------------