├── .gitignore ├── README.md ├── assets ├── treelogo.png └── treeschool_header.png ├── module_01 └── src │ └── .gitkeep ├── module_02 └── src │ ├── cruciverba │ ├── Cruciverba.java │ ├── Main.java │ └── README.txt │ ├── esempi │ ├── Array.java │ ├── EstensioneArray.java │ ├── Overloading.java │ └── Ricorsione.java │ └── labirinto │ ├── Immagini │ ├── laby.gif │ ├── preview.png │ └── rogue.png │ └── README.md ├── module_04 └── src │ ├── biblioteca │ ├── Biblioteca.java │ ├── BibliotecaSemplificata.java │ ├── Libro.java │ └── README.md │ ├── lampadina │ ├── Interruttore.java │ ├── Lampadina.java │ ├── README.MD │ └── StatoLampadina.java │ ├── negozio │ ├── Carrello.java │ ├── Cliente.java │ ├── DayOfWeek.java │ ├── Prodotto.java │ ├── README.md │ ├── Supermercato.java │ └── Test.java │ └── riparazioni │ ├── DittaRiparazioni.java │ ├── ListaDiRiparazioni.java │ ├── ListaDiTecnici.java │ ├── README.MD │ ├── Riparazione.java │ ├── StatoRiparazione.java │ ├── StatoTecnico.java │ └── Tecnico.java ├── module_05 └── src │ ├── distributoreBevande │ └── distributoreBevande.md │ ├── formeGeometriche │ └── formeGeometriche.md │ ├── gestoreVeicoli │ └── gestoreVeicoli.md │ └── serieA │ └── serieA.md ├── module_06 └── src │ ├── dragonball │ └── README.md │ └── turista_facoltoso │ ├── README.md │ ├── admin │ └── AirBnB.java │ ├── database │ └── Database.java │ ├── entities │ ├── Abitazione.java │ ├── Feedback.java │ ├── Prenotazione.java │ └── users │ │ ├── Host.java │ │ └── Utente.java │ ├── enumerators │ └── Voto.java │ └── main │ └── Main.java ├── module_07 └── src │ ├── esempi │ ├── comparable │ │ ├── Word.java │ │ └── WordComparator.java │ └── generics │ │ ├── Coppia.java │ │ ├── CoppiaDiversa.java │ │ ├── Main.java │ │ └── davide │ │ ├── App.java │ │ └── Scatola.java │ ├── supermercato │ ├── Cliente.java │ ├── Main.java │ ├── Supermercato.java │ └── readme.md │ └── tinderlike │ ├── Interest.java │ ├── README.md │ ├── TinderLike.java │ └── User.java ├── module_08 └── src │ ├── dictionary │ ├── CharacterNotPresentException.java │ ├── Dictionary.java │ ├── ElementNotPresentException.java │ ├── README.md │ └── WordNotPresentException.java │ └── floppydisk │ ├── README.md │ └── floppy.jpg ├── module_09 └── src │ ├── esempi │ └── ReaderWriter.java │ ├── fileandparole │ └── README.md │ ├── mappadirighe │ ├── README.md │ └── righe.txt │ └── righeinverse │ ├── README.md │ └── righe.txt ├── module_10 └── src │ ├── esempi │ ├── builder │ │ ├── Main.java │ │ ├── User.java │ │ └── UserBuilder.java │ ├── dao │ │ ├── User.java │ │ ├── UserDao.java │ │ ├── UserDaoCsv.java │ │ ├── UserDaoSql.java │ │ └── users.csv │ └── observer │ │ ├── ConnectionNotifier.java │ │ ├── Main.java │ │ ├── Observable.java │ │ ├── Observer.java │ │ └── User.java │ └── sharedmobility │ ├── Database.java │ ├── DatabaseInstanceNotDefined.java │ ├── README.md │ ├── User.java │ └── users.csv ├── module_11 ├── resources │ └── testuccio.txt └── src │ ├── EsempiStream.java │ └── MonstersAndTreasures │ └── README.md ├── module_12 └── src │ ├── AndiamoATeatro.pdf │ └── esempi │ ├── DatabaseConnection.java │ └── connectionhandler │ ├── ConnectionHandler.java │ ├── Dao.java │ ├── User.java │ ├── UserDao.java │ ├── UserDaoSql.java │ ├── config.properties │ └── config.properties.example ├── module_13 ├── Live Coding │ └── demo_rest_api │ │ ├── .DS_Store │ │ ├── pom.xml │ │ └── src │ │ ├── main │ │ └── java │ │ │ └── org │ │ │ └── example │ │ │ ├── App.java │ │ │ └── model │ │ │ ├── ErrorResponse.java │ │ │ └── User.java │ │ └── test │ │ └── java │ │ └── org │ │ └── example │ │ └── AppTest.java ├── simple-ecommerce │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── myecommerce │ │ │ ├── App.java │ │ │ └── model │ │ │ └── Product.java │ │ └── test │ │ └── java │ │ └── com │ │ └── myecommerce │ │ └── AppTest.java └── tree_express │ ├── pom.xml │ └── src │ ├── main │ └── java │ │ └── org │ │ └── treeexpress │ │ ├── App.java │ │ └── model │ │ ├── Delivery.java │ │ ├── DeliveryType.java │ │ └── TreeExpressUser.java │ └── test │ └── java │ └── org │ └── treeexpress │ └── AppTest.java └── module_14 └── demo-junit ├── pom.xml └── src ├── main └── java │ └── com │ └── demo │ └── junit │ └── App.java └── test └── java └── com └── demo └── junit └── AppTest.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-2023-01 4 | 5 | This repo collects all the exercises produced and gathered by [Marco Adriani](https://github.com/MrSosu), [Andrea Gasparini](https://github.com/andrea-gasparini) and [Davide Fella](https://github.com/davidefella) for the teaching of the 2023 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 | | 12 | | 2 | ABC dell'informatica in Java | [Esempi](module_02/src/esempi/) | 13 | | 3 | Git | | 14 | | 4 | Object-Oriented Programming | [Esercizi](module_04/src/) | 15 | | 5 | Ereditarietà Base | [Esercizi](module_05/src) | 16 | | 6 | Ereditarietà Avanzata | [Esercizi](module_06/src) | 17 | | 7 | Generics & Collections | [Esempi](module_07/src/esempi), [Esercizi](module_07/src) | 18 | | 8 | Eccezioni e annotazioni | [Esercizi](module_08/src) | 19 | | 9 | Input & Output | [Esempi](module_09/src/esempi), [Esercizi](module_09/src) | 20 | | 10 | Design Patterns | [Esempi](module_10/src/esempi), [Esercizi](module_10/src) | 21 | | 11 | Java Stream | [Esercizi](module_11) | 22 | | 12 | Database | [Esempi](module_12/src/esempi), [Esercitazione AndiamoATeatro](module_12/src/AndiamoATeatro.pdf) | 23 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /assets/treelogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/assets/treelogo.png -------------------------------------------------------------------------------- /assets/treeschool_header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/assets/treeschool_header.png -------------------------------------------------------------------------------- /module_01/src/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/module_01/src/.gitkeep -------------------------------------------------------------------------------- /module_02/src/cruciverba/Main.java: -------------------------------------------------------------------------------- 1 | package cruciverba; 2 | 3 | import cruciverba.Cruciverba; 4 | 5 | import java.util.Arrays; 6 | 7 | public class Main { 8 | 9 | public static void main(String[] args) { 10 | char[][] matrice = new char[][]{{'h', 'd', 'g', 'u', 'p', 'y', 's', 'p', 'a', 'o'}, {'t', 's', 'a', 'k', 'o', 'y', 'o', 'l', 'p', 's'}, {'r', 'c', 'm', 'c', 'n', 'r', 'i', 'a', 'a', 'b'}, {'i', 'o', 'b', 'a', 'i', 's', 'c', 't', 'l', 'a'}, {'g', 'r', 'e', 'l', 'f', 'a', 'c', 'e', 'o', 'l'}, {'l', 'f', 'r', 'a', 'l', 'l', 'u', 's', 'i', 'e'}, {'i', 'a', 'e', 'm', 'e', 'm', 'l', 's', 'l', 'n'}, {'a', 'n', 't', 'a', 'd', 'o', 'c', 'a', 'g', 'a'}, {'j', 'o', 't', 'r', 'b', 'n', 'd', 'g', 'o', 'd'}, {'l', 'y', 'o', 'o', 'u', 'e', 's', 'm', 's', 'm'}}; 11 | 12 | System.out.println(Cruciverba.cruciverba(matrice, "almto")); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /module_02/src/cruciverba/README.txt: -------------------------------------------------------------------------------- 1 | soluzione esercizio cruciverba 2 | -------------------------------------------------------------------------------- /module_02/src/esempi/Array.java: -------------------------------------------------------------------------------- 1 | package esempi; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Array { 6 | public static void main(String[] args) { 7 | // inizializziamo un array di lunghezza 3 con valori preimpostati 8 | int[] array = new int[]{1,2,3}; 9 | 10 | // inizializziamo un array "vuoto" di lunghezza 3 11 | int[] array2 = new int[3]; 12 | // assegnamo gli elementi 1, 2, 3 13 | array2[0] = 1; 14 | array2[1] = 2; 15 | array2[2] = 3; 16 | 17 | // analogamente, iteriamo e stampiamo gli elementi dell'array dall'indice 0 fino all'ultimo 18 | for (int i = 0; i < array2.length; i++) { 19 | System.out.println(array2[i]); 20 | } 21 | 22 | // se non necessitiamo degli indici, è possibile iterare direttamente elemento per elemento tramite for-each 23 | for (int elemento : array2) { 24 | System.out.println(elemento); 25 | } 26 | 27 | // la stampa di un array può essere effettuata in maniera più "smart" tramite Arrays.toString 28 | System.out.println(Arrays.toString(array2)); 29 | 30 | // sommiamo, tramite la funzione "somma" da noi definita, tutti gli elementi dell'array: 1+2+3=6 31 | System.out.println(somma(array2)); 32 | 33 | // inizializziamo una matrice 3x3 (3 righe e 3 colonne) 34 | // int[][] matrice = new int[3][3]; 35 | int[][] matrice = new int[][]{{1,2,3}, {1,2,3}, {1,2,3}}; 36 | 37 | // stampiamo il contenuto della prima riga 38 | System.out.println(Arrays.toString(matrice[0])); 39 | 40 | // stampiamo il contenuto riga per riga 41 | for (int i = 0; i < matrice.length; i++) { 42 | System.out.println(Arrays.toString(matrice[i])); 43 | } 44 | 45 | // stampiamo il contenuto della prima colonna (il primo valore di ogni riga) 46 | for (int i = 0; i < matrice.length; i++) { 47 | System.out.println(matrice[i][0]); 48 | } 49 | } 50 | 51 | // funzione che somma tutti gli elementi di un array e ritorna il risultato 52 | public static int somma(int[] array) { 53 | int tot = 0; 54 | for (int i = 0; i < array.length; i++) { 55 | tot += array[i]; 56 | } 57 | return tot; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /module_02/src/esempi/EstensioneArray.java: -------------------------------------------------------------------------------- 1 | package esempi; 2 | 3 | import java.util.Arrays; 4 | 5 | public class EstensioneArray { 6 | public static void main(String[] args) { 7 | int[] array = new int[]{1,2,3}; 8 | System.out.println(Arrays.toString(array)); 9 | // assegnando un valore ad un indice valido sovrascriviamo gli elementi già presenti nell'array 10 | array[0] = 5; 11 | System.out.println(Arrays.toString(array)); 12 | // questa operazione invece genererebbe un errore, l'indice 3 non esiste!! 13 | // array[3] = 5; 14 | 15 | // possiamo estendere un array creandone uno nuovo di lunghezza maggiore 16 | // in questo caso di lunghezza uguale al precedente array + 1, così da poter aggiungere un elemento 17 | int[] nuovoArray = new int[array.length + 1]; 18 | // copiamo tutti gli elementi del "vecchio" array nel "nuovo" 19 | for (int i = 0; i < array.length; i++) { 20 | nuovoArray[i] = array[i]; 21 | } 22 | // l'array precedente rimane invariato 23 | System.out.println(Arrays.toString(array)); 24 | // il nuovo array è una "copia" del precedente ma con un nuovo valore aggiunto in coda (inizializzato a 0) 25 | System.out.println(Arrays.toString(nuovoArray)); 26 | // assegnamo il riferimento in memoria del nuovo array a quello precedente 27 | // ATTENZIONE: in questo modo ogni modifica ad "array" si riflette su "nuovoArray" e viceversa 28 | array = nuovoArray; 29 | array[3] = 5; 30 | 31 | // creiamo un array di dimensione 1 ed estendiamolo step by step con la funzione ad hoc da noi definita 32 | int[] array2 = new int[1]; 33 | array2[0] = 1; 34 | array2 = appendToArray(array2, 2); 35 | array2 = appendToArray(array2, 3); 36 | array2 = appendToArray(array2, 4); 37 | System.out.println(array2[0]); 38 | System.out.println(array2[1]); 39 | System.out.println(array2.length); 40 | } 41 | 42 | // funzione per estendere un array di 1 e aggiungervi un elemento 43 | public static int[] appendToArray(int[] array, int newElement) { 44 | int[] nuovoArray = new int[array.length + 1]; 45 | for (int i = 0; i < array.length; i++) { 46 | nuovoArray[i] = array[i]; 47 | } 48 | nuovoArray[array.length] = newElement; 49 | return nuovoArray; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /module_02/src/esempi/Overloading.java: -------------------------------------------------------------------------------- 1 | package esempi; 2 | 3 | public class Overloading { 4 | 5 | public static void main(String[] args) { 6 | // in Java fare overloading significa ridefinire la stessa funzione con diversi parametri o tipi di ritorno 7 | // ad esempio esistono molte "versioni" del println, ognuna con un diverso tipo di parametro (es. int, char, String, ...) 8 | System.out.println(1); 9 | System.out.println(1.0); 10 | System.out.println('1'); 11 | System.out.println("1"); 12 | 13 | System.out.println(somma(1,2)); 14 | System.out.println(somma("1", "2")); 15 | } 16 | 17 | // funzione che somma due interi 18 | public static int somma(int a, int b) { 19 | return a + b; 20 | } 21 | 22 | // funzione che "somma" due stringhe (overloading della funzione di somma dei due interi) 23 | public static String somma(String a, String b) { 24 | return a + " " + b; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /module_02/src/esempi/Ricorsione.java: -------------------------------------------------------------------------------- 1 | package esempi; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Ricorsione { 6 | public static void main(String[] args) { 7 | fattoriale(5); 8 | System.out.println(sommaIterativa(new int[]{1,2,3,4})); 9 | System.out.println(sommaRicorsiva(new int[]{1,2,3,4})); 10 | System.out.println(sommaRicorsiva2(new int[]{1,2,3,4})); 11 | } 12 | 13 | public static int fattoriale(int n) { 14 | if (n < 0) throw new RuntimeException("Valore non supportato"); 15 | if (n == 0 || n == 1) return n; 16 | return n * fattoriale(n - 1); 17 | } 18 | 19 | public static int sommaIterativa(int[] array) { 20 | int tot = 0; 21 | for (int i = 0; i < array.length; i++) tot += array[i]; 22 | return tot; 23 | } 24 | 25 | public static int sommaRicorsiva(int[] array) { 26 | if (array.length == 1) return array[0]; 27 | return array[array.length - 1] + sommaRicorsiva(Arrays.copyOf(array, array.length - 1)); 28 | } 29 | 30 | public static int sommaRicorsiva2(int[] array) { 31 | return sommaRicorsiva2(array, array.length - 1); 32 | } 33 | 34 | public static int sommaRicorsiva2(int[] array, int indice) { 35 | if (indice == 0) return array[0]; 36 | return array[indice] + sommaRicorsiva2(array, indice - 1); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /module_02/src/labirinto/Immagini/laby.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/module_02/src/labirinto/Immagini/laby.gif -------------------------------------------------------------------------------- /module_02/src/labirinto/Immagini/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/module_02/src/labirinto/Immagini/preview.png -------------------------------------------------------------------------------- /module_02/src/labirinto/Immagini/rogue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/module_02/src/labirinto/Immagini/rogue.png -------------------------------------------------------------------------------- /module_02/src/labirinto/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 | 19 | ![test](Immagini/laby.gif) 20 | 21 | 22 | ## :smiling_face_with_three_hearts: Bonus stage: 23 | 24 | Generate il labirinto randomicamente 25 | 26 | # :skull_and_crossbones: Ultra mega bonus stage: 27 | ## Io ve lo dico, è difficile... 28 | Fate in modo che il computer sia in grado di risolvere da solo il labirinto. 29 | -------------------------------------------------------------------------------- /module_04/src/biblioteca/Biblioteca.java: -------------------------------------------------------------------------------- 1 | package biblioteca; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | public class Biblioteca { 7 | 8 | private Libro[] libri; 9 | 10 | public Biblioteca(Libro[] books) { 11 | this.libri = books; 12 | this.ordinaLibri(); 13 | // this.ordinaLibri2(); 14 | } 15 | 16 | public boolean esisteLibro(Libro bookToFind) { return esisteLibro(bookToFind.getIndex()); } 17 | 18 | public boolean esisteLibro(int bookToFind) { 19 | for (Libro libro : libri) 20 | if (libro.getIndex() == bookToFind) 21 | return true; 22 | return false; 23 | } 24 | 25 | public Libro[] getLibriOrdinati() { return libri; } 26 | 27 | public int[] getIndiciLibriOrdinati() { 28 | Libro[] orderedBooks = getLibriOrdinati(); 29 | int[] bookIndexes = new int[orderedBooks.length]; 30 | for (int i = 0; i < orderedBooks.length; i++) 31 | bookIndexes[i] = orderedBooks[i].getIndex(); 32 | return bookIndexes; 33 | } 34 | 35 | /** 36 | * Aggiunge un libro all'array di libri della biblioteca e mantiene l'ordinamento in base agli indici 37 | * @param libro libro da aggiungere nella biblioteca 38 | */ 39 | public void addLibro(Libro libro) { 40 | // 1. estendere l'array 41 | Libro[] newLibri = new Libro[libri.length + 1]; 42 | // 2. copiare tutti gli elementi 43 | for (int i = 0; i < libri.length; i++) 44 | newLibri[i] = libri[i]; 45 | // 3. aggiungere il nuovo libro 46 | newLibri[libri.length] = libro; 47 | // 4. ordinare nuovamente l'array di libri 48 | ordinaLibri(); 49 | } 50 | 51 | /** 52 | * Ordina gli indici dei libri tramite l'algoritmo Selection Sort (https://en.wikipedia.org/wiki/Selection_sort). 53 | * Questo algoritmo è poco efficiente, in quanto per un array di lunghezza n effettua sempre n*n confronti. 54 | */ 55 | private void ordinaLibri() { 56 | for (int i = 0; i < libri.length - 1; i++) 57 | { 58 | int minIndex = i; 59 | 60 | for (int j = i + 1; j < libri.length; j++) 61 | if (libri[j].getIndex() < libri[minIndex].getIndex()) 62 | minIndex = j; 63 | 64 | Libro minIndexBook = libri[minIndex]; 65 | libri[minIndex] = libri[i]; 66 | libri[i] = minIndexBook; 67 | } 68 | } 69 | 70 | /** 71 | * Ordina gli indici dei libri tramite il metodo di sorting di default implementato in Java (ottimizzando i confronti: n*log_n). 72 | * Il criterio di ordinamento è definito tramite il metodo statico `comparing` della classe `Comparator`, 73 | * per ordinare in base al valore di getIndex della classe Libro (Libro::getIndex). 74 | * Vedremo la classe Comparator e come utilizzarla nel dettaglio dal modulo 6 in poi. 75 | */ 76 | private void ordinaLibri2() { Arrays.sort(libri, Comparator.comparing(Libro::getIndex)); } 77 | 78 | public static void main(String[] args) { 79 | Libro lib = new Libro(1, "Libro bello", "Andrea"); 80 | Libro lib2 = new Libro(2, "Libro bello 2", "Andrea"); 81 | 82 | Biblioteca bib = new Biblioteca(new Libro[]{lib, lib2}); 83 | 84 | System.out.println(bib.esisteLibro(1)); 85 | System.out.println(bib.esisteLibro(lib)); 86 | 87 | Libro[] books = new Libro[]{ 88 | new Libro(123, "Luciana Litizzetto", "I dolori del giovane Programmatore"), 89 | new Libro(4, "Super Mario", "Errori da non ripetere"), 90 | new Libro(98, "Luigi Pirandino", "Uno, nessuno e diecimila bug"), 91 | new Libro(33, "Roberto Roberti", "Come programmare in Java da zero"), 92 | new Libro(76, "Piero Java", "Mille splendidi errori"), 93 | new Libro(2, "Lavinia Pitoni", "Non si esce vivi dalle biblioteche"), 94 | new Libro(235, "Luciana Litizzetto Jr.", "I dolori del vecchio Programmatore") 95 | }; 96 | 97 | Biblioteca library = new Biblioteca(books); 98 | System.out.println(library.esisteLibro(76)); 99 | 100 | int[] booksIndexes = library.getIndiciLibriOrdinati(); 101 | System.out.println(booksIndexes[0] == 2); 102 | System.out.println(booksIndexes[1] == 4); 103 | System.out.println(booksIndexes[2] == 33); 104 | System.out.println(booksIndexes[3] == 76); 105 | System.out.println(booksIndexes[4] == 98); 106 | System.out.println(booksIndexes[5] == 123); 107 | System.out.println(booksIndexes[6] == 235); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /module_04/src/biblioteca/BibliotecaSemplificata.java: -------------------------------------------------------------------------------- 1 | package biblioteca; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BibliotecaSemplificata { 6 | 7 | private int[] booksIndexes; 8 | 9 | public BibliotecaSemplificata(int[] booksIndexes) { 10 | Arrays.sort(booksIndexes); 11 | this.booksIndexes = booksIndexes; 12 | } 13 | 14 | public boolean esisteLibro(int bookToFind) { 15 | for (int bookIndex : booksIndexes) 16 | if (bookIndex == bookToFind) 17 | return true; 18 | return false; 19 | } 20 | 21 | public int[] getIndiciLibriOrdinati() { 22 | return booksIndexes; 23 | } 24 | 25 | public static void main(String[] args) { 26 | int[] values = new int[7]; 27 | values[0] = 123; 28 | values[1] = 4; 29 | values[2] = 98; 30 | values[3] = 33; 31 | values[4] = 76; 32 | values[5] = 2; 33 | values[6] = 235; 34 | BibliotecaSemplificata library = new BibliotecaSemplificata(values); 35 | System.out.println(library.esisteLibro(76)); 36 | int[] booksIndexes = library.getIndiciLibriOrdinati(); 37 | System.out.println(booksIndexes[0] == 2); 38 | System.out.println(booksIndexes[1] == 4); 39 | System.out.println(booksIndexes[2] == 33); 40 | System.out.println(booksIndexes[3] == 76); 41 | System.out.println(booksIndexes[4] == 98); 42 | System.out.println(booksIndexes[5] == 123); 43 | System.out.println(booksIndexes[6] == 235); 44 | } 45 | } -------------------------------------------------------------------------------- /module_04/src/biblioteca/Libro.java: -------------------------------------------------------------------------------- 1 | package biblioteca; 2 | 3 | public class Libro { 4 | 5 | private int index; 6 | private String author; 7 | private String name; 8 | 9 | public Libro(int index, String author, String name) { 10 | this.index = index; 11 | this.author = author; 12 | this.name = name; 13 | } 14 | 15 | public int getIndex() { return index; } 16 | } 17 | -------------------------------------------------------------------------------- /module_04/src/biblioteca/README.md: -------------------------------------------------------------------------------- 1 | # 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 biblioteca, in ordine ascendente 9 | 10 | Potete utilizzare il seguente codice come test: 11 | 12 | ```java 13 | public class Main { 14 | public static void main(String[] args) { 15 | int[] values = new int[7]; 16 | values[0] = 123; 17 | values[1] = 4; 18 | values[2] = 98; 19 | values[3] = 33; 20 | values[4] = 76; 21 | values[5] = 2; 22 | values[6] = 235; 23 | Biblioteca biblioteca = new Biblioteca(values); 24 | System.out.println(biblioteca.esisteLibro(76)); 25 | int[] libriOrdinati = biblioteca.getIndiciLibriOrdinati(); 26 | System.out.println(libriOrdinati[0] == 2); 27 | System.out.println(libriOrdinati[1] == 4); 28 | System.out.println(libriOrdinati[2] == 33); 29 | System.out.println(libriOrdinati[3] == 76); 30 | System.out.println(libriOrdinati[4] == 98); 31 | System.out.println(libriOrdinati[5] == 123); 32 | System.out.println(libriOrdinati[6] == 235); 33 | } 34 | } 35 | ``` 36 | 37 | Suggerimento: riutilizzate il codice dei precedenti esercizi 38 | 39 | ## Bonus stage 40 | 41 | Rendere la biblioteca funzionante con dei libri veri e propri invece che con solo i loro indici. 42 | Creare quindi una classe Libro con delle proprie caratteristiche, tra cui l'indice che usavamo prima, 43 | ad esempio nome, autore, categoria, ecc, e modificare di conseguenza la classe Biblioteca ed il main di test. 44 | 45 | NOTA: l'ordinamento dei libri può essere implementato da zero (ad esempio implementando il [selection sort](https://en.wikipedia.org/wiki/Selection_sort) o l'[insertion sort](https://en.wikipedia.org/wiki/Insertion_sort)) o fatto in maniera più smart con un Comparator, che però vedremo dal modulo 6 in poi (una volta sostenuti questi moduli, è possibile riprendere in mano l'esercizio per migliorare il risultato sfruttando le nuove conoscenze). 46 | 47 | ```Java 48 | // dato un array di oggetti di tipo Libro (Libro[] books), i quali contengono un metodo getIndex 49 | // possiamo ordinarlo in base all'index con Arrays.sort, aggiungendo il seguente Comparator come secondo parametro 50 | Arrays.sort(books, Comparator.comparing(Libro::getIndex)); 51 | ``` 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /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 | public class Lampadina { 4 | 5 | private static boolean hasElectricity; 6 | private StatoLampadina stato; 7 | /** 8 | * Numero di click possibili rimasti prima della rottura della lampadina 9 | */ 10 | private int clickCount; 11 | 12 | /** 13 | * Costruisce un oggetto lampadina a partire da un numero massimo di click possibili prima della rottura 14 | * @param maxClickCount numero massimo di click possibili prima della rottura 15 | */ 16 | public Lampadina(int maxClickCount) { 17 | this.clickCount = maxClickCount; 18 | stato = StatoLampadina.SPENTA; 19 | } 20 | 21 | /** 22 | * Cambia lo stato dell'elettricità condivisa da tutte le lampadine all'interno dell'impianto 23 | * @return true se c'è elettricità dopo il cambio, o false altrimenti 24 | */ 25 | public static boolean toggleElectricity() { 26 | hasElectricity = !hasElectricity; 27 | return hasElectricity; 28 | } 29 | 30 | /** 31 | * Ritorna lo stato corrente della lampadina 32 | */ 33 | public StatoLampadina getStato() { 34 | if (stato == StatoLampadina.ROTTA) return stato; 35 | if (!hasElectricity) return StatoLampadina.SPENTA; 36 | return stato; 37 | } 38 | 39 | /** 40 | * Cambia lo stato da accesa a spenta o da spenta ad accesa, in base allo stato attuale. 41 | * Oppure rompe la lampadina dopo un numero di click predefinito. 42 | * @return true se il cambio di stato è andato a buon fine, false altrimenti 43 | */ 44 | public boolean click() { 45 | if (!hasElectricity) return false; 46 | if (stato.equals(StatoLampadina.ROTTA)) return false; 47 | if (clickCount == 0) stato = StatoLampadina.ROTTA; 48 | else { 49 | switch (stato) { 50 | case ACCESA -> stato = StatoLampadina.SPENTA; 51 | case SPENTA -> stato = StatoLampadina.ACCESA; 52 | } 53 | clickCount--; 54 | } 55 | return true; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /module_04/src/lampadina/README.MD: -------------------------------------------------------------------------------- 1 | # Lampadina :bulb: 2 | 3 | ## Lampadina1 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 | ## Lampadina2 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 | ## Lampadina3 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 34 | -------------------------------------------------------------------------------- /module_04/src/lampadina/StatoLampadina.java: -------------------------------------------------------------------------------- 1 | package lampadina; 2 | 3 | public enum StatoLampadina { 4 | ACCESA, SPENTA, ROTTA 5 | } 6 | -------------------------------------------------------------------------------- /module_04/src/negozio/Carrello.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public class Carrello { 4 | 5 | private int indice; 6 | private Cliente cliente; 7 | private Prodotto[] prodotti; 8 | private int[] quantita; 9 | 10 | public Carrello(Cliente cliente) { 11 | this.cliente = cliente; 12 | this.prodotti = new Prodotto[100]; 13 | this.quantita = new int[100]; 14 | this.indice = 0; 15 | } 16 | 17 | // setter e getter 18 | public int getIndice() { 19 | return indice; 20 | } 21 | 22 | public Cliente getCliente() { 23 | return cliente; 24 | } 25 | 26 | public void setCliente(Cliente cliente) { 27 | this.cliente = cliente; 28 | } 29 | 30 | public Prodotto[] getProdotti() { 31 | return prodotti; 32 | } 33 | 34 | public void setProdotti(Prodotto[] prodotti) { 35 | this.prodotti = prodotti; 36 | } 37 | 38 | public int[] getQuantita() { 39 | return quantita; 40 | } 41 | 42 | public void setQuantita(int[] quantita) { 43 | this.quantita = quantita; 44 | } 45 | 46 | public void setIndice(int indice) { 47 | this.indice = indice; 48 | } 49 | 50 | // metodi 51 | public void aggiungiProdotto(Prodotto p, int q) { 52 | prodotti[indice] = p; 53 | quantita[indice] = q; 54 | this.indice++; 55 | } 56 | 57 | public void stampaCarrello() { 58 | for (int i = 0; i < prodotti.length; i++) { 59 | if (prodotti[i] == null) continue; 60 | System.out.println(prodotti[i].getNome() + " : " + quantita[i]); 61 | } 62 | } 63 | 64 | } 65 | 66 | -------------------------------------------------------------------------------- /module_04/src/negozio/Cliente.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public class Cliente { 4 | 5 | // attributi 6 | private int eta; 7 | private Carrello carrello; // il carrello del cliente 8 | private int numeroPunti; // i punti sconto 9 | 10 | // costruttore 11 | public Cliente(int eta) { 12 | this.eta = eta; 13 | this.numeroPunti = 0; 14 | carrello = new Carrello(this); 15 | } 16 | 17 | // getter e setter 18 | public int getEta() { 19 | return eta; 20 | } 21 | 22 | public void setEta(int eta) { 23 | this.eta = eta; 24 | } 25 | 26 | public Carrello getCarrello() { 27 | return carrello; 28 | } 29 | 30 | // metodi 31 | /* questo metodo aggiunge un prodotto p nel carrello del cliente in quantità q 32 | */ 33 | public void addInCarrello(Prodotto p, int q) { 34 | /* 35 | 1) controllare se il prodotto sia disponibile in tale quantità nel negozio 36 | 1.1) se c'è disponibilità aggiungo nella prossima casella libera dei due array che compongono il carrello p e q 37 | 1.2) altrimenti stampo un messaggio di errore 38 | */ 39 | Prodotto[] prodottiNegozio = Supermercato.getProdotti(); 40 | // controllo se il prodotto p è disponibile in quantità q dentro il supermercato 41 | if (Supermercato.isDisponibile(p,q)) { 42 | carrello.aggiungiProdotto(p,q); 43 | } 44 | else System.out.println("Prodotto non disponibile!"); 45 | } 46 | 47 | /* 48 | questo metodo svuota il carrello del cliente 49 | */ 50 | public void svuotaCarrello() { 51 | carrello.setProdotti(new Prodotto[100]); 52 | carrello.setQuantita(new int[100]); 53 | carrello.setIndice(0); 54 | } 55 | 56 | /* 57 | questo metodo ritorna true se il cliente ha diritto allo sconto in questo momento 58 | */ 59 | public boolean isSconto(DayOfWeek day) { 60 | if (eta >= 60 && (day.equals(DayOfWeek.LUNEDI) || day.equals(DayOfWeek.MERCOLEDI))) return true; 61 | return false; 62 | } 63 | 64 | /* 65 | questo metodo permette di effettuare l'acquisto. 66 | 0) inizializzo il conto 67 | 1) controllo se i prodotti nel carrello sono ancora disponibili. Per fare ciò: 68 | faccio un for sui prodotti p e le rispettive quantità q: 69 | 1.1) se quel prodotto p è ancora presente nel negozio in quantità q: 70 | 1.1.1) confermo l'acquisto del prodotto p in quantità q, quindi vado a rimuovere dal 71 | supermercato quella quantità di prodotto. 72 | 1.1.2) aggiungo al conto totale il prezzo di p moltiplicato per q 73 | 1.2) altrimenti: 74 | 1.2.1) permetto l'acquisto solamente della quantità q rimanente qRimanente e aggiorno il supermercato 75 | (che può essere zero e quindi non verrà calcolata in tal caso nel conto finale) 76 | 1.2.2) aggiungo al conto il prezzo di p moltiplicato per qRimanente 77 | 2) svuotare il carrello 78 | 3) ritorno il conto finale 79 | */ 80 | public double checkout(DayOfWeek day, boolean sconto) { 81 | double conto = 0; 82 | for (int i = 0; i < carrello.getIndice(); i++) { // mi scorro il carrello (non tutto ma solo fino all'indice del carrello perchè so che è pieno fino a li 83 | Prodotto p = carrello.getProdotti()[i]; // prendo l'i-esimo prodotto dal carrello 84 | int q = carrello.getQuantita()[i]; // prendo l'i-esima quantità dell'i'-esimo prodotto nel carrello 85 | if (Supermercato.isDisponibile(p,q)) { // controllo se il prodotto in quella quantita sia ancora disponibile 86 | if (isSconto(day) && p.isFood()) { // se posso applicare lo sconto 87 | double prezzo_scontato = (p.getPrezzo() / 100.0) * 80; 88 | conto += q*prezzo_scontato; // lo calcolo aumentando il conto con il prezzo scontato 89 | } 90 | else { 91 | conto += q*p.getPrezzo(); // lo calcolo per intero 92 | } 93 | Supermercato.rimuoviDopoAcquisto(p,q); // se si decremento la quantità del prodotto nel negozio 94 | } 95 | else { // altrimenti 96 | if (isSconto(day) && p.isFood()) { 97 | double prezzo_scontato = (p.getPrezzo() / 100.0) * 80; 98 | conto += p.getQuantity()*prezzo_scontato; 99 | } 100 | else { 101 | conto += p.getQuantity()*p.getPrezzo(); 102 | } 103 | 104 | Supermercato.rimuoviDopoAcquisto(p,p.getQuantity()); // "svuoto" le scorte di quel prodotto 105 | } 106 | } 107 | svuotaCarrello(); // svuoto il carrello 108 | numeroPunti += conto / 10; 109 | if (sconto) { 110 | double euro_scontati = numeroPunti / 10; 111 | return conto - euro_scontati; 112 | } 113 | return conto; 114 | } 115 | 116 | /* 117 | overload del metodo precedente, dove in questo caso il pagamento viene rateizzato 118 | e il metodo ritorna il costo della prima rata 119 | */ 120 | public double checkout(DayOfWeek day, boolean sconto, int nMesi) { 121 | double prezzo_tot = checkout(day, sconto); 122 | return prezzo_tot / nMesi; 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /module_04/src/negozio/DayOfWeek.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public enum DayOfWeek { 4 | 5 | LUNEDI, MARTEDI, MERCOLEDI, GIOVEDI, VENERDI, SABATO, DOMENICA; 6 | 7 | } 8 | -------------------------------------------------------------------------------- /module_04/src/negozio/Prodotto.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public class Prodotto { 4 | 5 | // attributi 6 | private String nome; 7 | private double prezzo; 8 | private int quantity; 9 | private boolean food; 10 | 11 | public Prodotto(String nome, double prezzo, int quantity, boolean food) { 12 | this.nome = nome; 13 | this.prezzo = prezzo; // qui è da mettere una eccezione per controllare se prezzo >= 0 14 | this.quantity = quantity; // qui è da mettere una eccezione per controllare se quantity >= 0 15 | this.food = food; 16 | } 17 | 18 | // getter e setter 19 | public String getNome() { 20 | return nome; 21 | } 22 | 23 | public double getPrezzo() { 24 | return prezzo; 25 | } 26 | 27 | public void setPrezzo(double prezzo) { 28 | this.prezzo = prezzo; 29 | } 30 | 31 | public int getQuantity() { 32 | return quantity; 33 | } 34 | 35 | public void setQuantity(int quantity) { 36 | this.quantity = quantity; 37 | } 38 | 39 | public boolean isFood() { 40 | return food; 41 | } 42 | 43 | // metodi 44 | // questo metodo aggiunge una quantità quantity del prodotto alla quantità precedente 45 | public void addQuantity(int quantity) { 46 | this.quantity += quantity; 47 | } 48 | 49 | /* questo metodo decrementa la quantità di un prodotto */ 50 | public void decreaseQuantity(int quantity) { 51 | this.quantity -= quantity; 52 | } 53 | 54 | // questo metodo aggiorna di 1 la quantità disponibile del prodotto 55 | public void addSingleQuantity() { 56 | this.quantity++; 57 | } 58 | 59 | // ritorna true se i due oggetti hanno lo stesso nome 60 | @Override 61 | public boolean equals(Object obj) { 62 | // controlliamo se il parametro obj sia null oppure sia della classe Prodotto 63 | if (obj == null || obj.getClass() != this.getClass()) return false; 64 | Prodotto new_p = (Prodotto) obj; // questa operazione si chiama casting 65 | if (this.nome.equals(new_p.nome)) return true; 66 | return false; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /module_04/src/negozio/README.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/Supermercato.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public class Supermercato { 4 | 5 | // attributi 6 | private static Prodotto[] prodotti = new Prodotto[100]; // i prodotti del supermercato 7 | 8 | // metodi 9 | public static Prodotto[] getProdotti() { 10 | return prodotti; 11 | } 12 | 13 | /* 14 | Questo metodo aggiunge un prodotto (o ne incrementa la quantità se presente) al negozio 15 | */ 16 | public static void addProdotto(Prodotto p, int q) { 17 | // qui cerco il prodotto 18 | for (int i = 0; i < prodotti.length; i++) { // ciclo i prodotti 19 | if (p.equals(prodotti[i])) { 20 | prodotti[i].addQuantity(q); 21 | return; 22 | } 23 | } 24 | // se non lo trovo cerco un buco 25 | for (int i = 0; i < prodotti.length; i++) { 26 | if (prodotti[i] == null) { 27 | prodotti[i] = p; 28 | prodotti[i].setQuantity(q); 29 | return; 30 | } 31 | } 32 | } 33 | 34 | /* 35 | questo metodo rimuove un prodotto p all'interno dell'array dei prodotti 36 | */ 37 | public static void removeProdotto(Prodotto p) { 38 | // cerco il prodotto 39 | for (int i = 0; i < prodotti.length; i++) { // ciclo i prodotti 40 | if (prodotti[i].equals(p)) { 41 | prodotti[i] = null; 42 | } 43 | } 44 | } 45 | 46 | /* 47 | questo metodo stampa a video tutti i prodotti del negozio con le rispettive quantità 48 | */ 49 | public static void stampaProdotti() { 50 | for (Prodotto p : prodotti) { 51 | if (p == null) continue; 52 | System.out.println(p.getNome() + " : " + p.getQuantity()); 53 | } 54 | } 55 | 56 | /* 57 | Questo metodo ritorna true se il prodotto p è disponibile in quantità q dentro il 58 | negozio. 59 | */ 60 | public static boolean isDisponibile(Prodotto p, int q) { 61 | for (Prodotto prod : prodotti) { // mi scorro l'array di prodotti del negozio 62 | if (p.equals(prod)) { // controllo con equals se trovo il prodotto cercato 63 | if (prod.getQuantity() >= q) return true; // se la quantità è sufficiente ritorno true 64 | else return false; // altrimenti ritorno false 65 | } 66 | } 67 | return false; 68 | } 69 | 70 | /* 71 | Questo metodo prende in input un prodotto p disponibile e una data quantità q 72 | e rimuove q prodotti di quel tipo dal negozio 73 | */ 74 | public static void rimuoviDopoAcquisto(Prodotto p, int q) { 75 | for (Prodotto prod : prodotti) { // mi scorro l'array di prodotti 76 | if (prod.equals(p)) { 77 | prod.decreaseQuantity(q); 78 | break; 79 | } 80 | } 81 | } 82 | } 83 | 84 | -------------------------------------------------------------------------------- /module_04/src/negozio/Test.java: -------------------------------------------------------------------------------- 1 | package negozio; 2 | 3 | public class Test { 4 | 5 | public static void main(String[] args) { 6 | // creo dei prodotti 7 | Prodotto p1 = new Prodotto("Mela", 0.25, 15, true); 8 | Prodotto p2 = new Prodotto("Sapone mani", 1.50, 5, false); 9 | Prodotto p3 = new Prodotto("Riso", 1, 10, true); 10 | Prodotto p4 = new Prodotto("Vino bianco", 4.20, 8, true); 11 | Prodotto p5 = new Prodotto("Deodorante", 3, 4, false); 12 | 13 | // creo due clienti 14 | Cliente c1 = new Cliente(65); 15 | Cliente c2 = new Cliente(29); 16 | Cliente c3 = new Cliente(50); 17 | 18 | // aggiungo i prodotti al negozio 19 | Supermercato.addProdotto(p1, p1.getQuantity()); 20 | Supermercato.addProdotto(p2, p2.getQuantity()); 21 | Supermercato.addProdotto(p3, p3.getQuantity()); 22 | Supermercato.addProdotto(p4, p4.getQuantity()); 23 | Supermercato.addProdotto(p5, p5.getQuantity()); 24 | 25 | // riempiamo i carrelli dei clienti 26 | c1.addInCarrello(p1, 6); 27 | c1.addInCarrello(p2, 1); 28 | c1.addInCarrello(p3, 2); 29 | 30 | c2.addInCarrello(p1, 6); 31 | c2.addInCarrello(p2, 1); 32 | c2.addInCarrello(p3, 2); 33 | 34 | c3.addInCarrello(p1, 10); 35 | 36 | System.out.println("----------------------------------"); 37 | c1.getCarrello().stampaCarrello(); 38 | System.out.println("----------------------------------"); 39 | c2.getCarrello().stampaCarrello(); 40 | System.out.println("----------------------------------"); 41 | c3.getCarrello().stampaCarrello(); 42 | System.out.println("----------------------------------"); 43 | 44 | Supermercato.stampaProdotti(); 45 | System.out.println("----------------------------------"); 46 | 47 | System.out.println(c1.checkout(DayOfWeek.MERCOLEDI, false)); 48 | System.out.println(c2.checkout(DayOfWeek.MERCOLEDI, false)); 49 | 50 | System.out.println("----------------------------------"); 51 | 52 | Supermercato.stampaProdotti(); 53 | 54 | System.out.println("----------------------------------"); 55 | 56 | System.out.println(c3.checkout(DayOfWeek.MERCOLEDI, false)); 57 | System.out.println("----------------------------------"); 58 | Supermercato.stampaProdotti(); 59 | 60 | Comparable[] array_oggetti_comparabili = {p1, p2, c1, c2}; 61 | Comparable oggetto_comparabile = p1; 62 | } 63 | 64 | } 65 | 66 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/DittaRiparazioni.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | 3 | public class DittaRiparazioni { 4 | 5 | private final ListaDiTecnici tecnici; 6 | private final ListaDiRiparazioni riparazioni; 7 | 8 | public DittaRiparazioni(Riparazione[] riparazioni, Tecnico[] tecnici) { 9 | this.tecnici = new ListaDiTecnici(tecnici); 10 | this.riparazioni = new ListaDiRiparazioni(riparazioni); 11 | } 12 | 13 | public ListaDiTecnici getTecnici(){ 14 | return tecnici; 15 | } 16 | 17 | public boolean aggiungiRiparazione(Riparazione riparazione) { 18 | if (esisteRiparazioneDatoIndirizzo(riparazione.getIndirizzo())) 19 | return false; 20 | 21 | riparazioni.add(riparazione); 22 | return true; 23 | } 24 | 25 | public boolean aggiungiTecnico(Tecnico tecnico) { 26 | if (esisteTecnicoDatoNome(tecnico.getNome())) 27 | return false; 28 | 29 | tecnici.add(tecnico); 30 | return true; 31 | } 32 | 33 | private boolean esisteRiparazioneDatoIndirizzo(String indirizzo) { 34 | for (int i = 0; i < riparazioni.length(); i++) 35 | if (riparazioni.get(i).getIndirizzo().equals(indirizzo)) 36 | return true; 37 | 38 | return false; 39 | } 40 | 41 | private boolean esisteTecnicoDatoNome(String nome) { 42 | for (int i = 0; i < tecnici.length(); i++) 43 | if (tecnici.get(i).getNome().equals(nome)) 44 | return true; 45 | 46 | return false; 47 | } 48 | 49 | public Riparazione[] getRiparazioniInAttesa() { 50 | Riparazione[] inAttesa = new Riparazione[riparazioni.length()]; 51 | int countInAttesa = 0; 52 | 53 | for (int i = 0; i < riparazioni.length(); i++) { 54 | if (riparazioni.get(i).getStato().equals(StatoRiparazione.IN_ATTESA)) 55 | { 56 | inAttesa[countInAttesa] = riparazioni.get(i); 57 | countInAttesa++; 58 | } 59 | } 60 | 61 | return inAttesa; 62 | } 63 | 64 | public ListaDiRiparazioni getRiparazioni() { return riparazioni; } 65 | 66 | public Riparazione getRiparazioneMaxPriorita(){ 67 | Riparazione risultato = null; 68 | 69 | for (int i = 0; i < riparazioni.length(); i++) { 70 | 71 | if (riparazioni.get(i).getStato().equals(StatoRiparazione.IN_ATTESA)) 72 | { 73 | if (risultato == null) 74 | risultato = riparazioni.get(i); 75 | else if (riparazioni.get(i).getPriorita() > risultato.getPriorita()) 76 | risultato = riparazioni.get(i); 77 | } 78 | } 79 | 80 | return risultato; 81 | } 82 | 83 | public boolean assegnaProssimaRiparazione(){ 84 | Tecnico tecnicoLibero = null; 85 | for (int i = 0; i < tecnici.length(); i++) { 86 | if (tecnici.get(i).getStato().equals(StatoTecnico.DISPONIBILE)) 87 | { 88 | tecnicoLibero = tecnici.get(i); 89 | break; 90 | } 91 | } 92 | 93 | if (tecnicoLibero == null) 94 | return false; 95 | 96 | Riparazione maxPriorita = getRiparazioneMaxPriorita(); 97 | 98 | maxPriorita.setStato(StatoRiparazione.IN_CORSO); 99 | tecnicoLibero.setRiparazione(maxPriorita); 100 | 101 | return true; 102 | } 103 | 104 | public boolean setRiparazioneTerminata(String nomeTecnico) { 105 | Tecnico tecnico = cercaTecnicoPerNome(nomeTecnico); 106 | 107 | if (tecnico == null) { 108 | System.out.println("nome tecnico non trovato"); 109 | return false; 110 | } 111 | 112 | if (tecnico.getRiparazione() == null) { 113 | System.out.println("il tecnico specificato non ha una riparazione in corso"); 114 | return false; 115 | } 116 | 117 | tecnico.getRiparazione().setStato(StatoRiparazione.TERMINATA); 118 | tecnico.setRiparazione(null); 119 | 120 | return true; 121 | } 122 | 123 | private Tecnico cercaTecnicoPerNome(String nomeTecnico) { 124 | for (int i = 0; i < tecnici.length(); i++) 125 | if (tecnici.get(i).getNome().equals(nomeTecnico)) 126 | return tecnici.get(i); 127 | 128 | return null; 129 | } 130 | 131 | public void mandaTecniciInFerie(ListaDiTecnici tecniciInFerie) { 132 | for (int i = 0; i < tecniciInFerie.length(); i++) { 133 | Tecnico t = cercaTecnicoPerNome(tecniciInFerie.get(i).getNome()); 134 | if(t != null) 135 | t.vaiInFerie(); 136 | } 137 | } 138 | 139 | public static void main(String[] args) { 140 | Tecnico[] tecnici = {new Tecnico("mario"), new Tecnico("giorgio")}; 141 | Riparazione[] riparazioni = new Riparazione[]{ 142 | new Riparazione("via roma", 4), 143 | new Riparazione("via milano", 4), 144 | new Riparazione("via milano2", 4), 145 | new Riparazione("via milano3", 4), 146 | new Riparazione("via milan4", 4), 147 | new Riparazione("via milano5", 4) 148 | }; 149 | DittaRiparazioni d = new DittaRiparazioni(riparazioni, tecnici); 150 | 151 | System.out.println(d.getRiparazioni()); 152 | System.out.println(d.getRiparazioneMaxPriorita()); 153 | System.out.println(d.assegnaProssimaRiparazione()); 154 | System.out.println(d.assegnaProssimaRiparazione()); 155 | System.out.println(d.getRiparazioneMaxPriorita()); 156 | System.out.println(!d.assegnaProssimaRiparazione()); 157 | } 158 | 159 | } 160 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/ListaDiRiparazioni.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Classe per gestire una lista dinamica di Riparazioni, 7 | * basata su un array che ad ogni nuovo inserimento viene esteso di 1 (come visto precedentemente nel modulo 2) 8 | */ 9 | public class ListaDiRiparazioni { 10 | 11 | private Riparazione[] riparazioni = new Riparazione[0]; 12 | 13 | public ListaDiRiparazioni(Riparazione[] riparazioni) { 14 | for (Riparazione riparazione : riparazioni) 15 | add(riparazione); 16 | } 17 | 18 | /** 19 | * @return lunghezza della lista di tecnici 20 | */ 21 | public int length() { return riparazioni.length; } 22 | 23 | /** 24 | * Aggiunge una riparazione nella lista di riparazioni, estendendo la dimensione dell'array di 1 25 | * 26 | * @param riparazione il Tecnico da aggiungere alla lista 27 | */ 28 | public void add(Riparazione riparazione) { 29 | if (riparazione != null) { 30 | // estendiamo l'array di riparazioni creandone uno nuovo temporaneo di lunghezza maggiore di 1 31 | // così da poter aggiungere una nuova riparazione 32 | Riparazione[] nuovoArray = new Riparazione[riparazioni.length + 1]; 33 | // copiamo ogni riparazione nel nuovo array esteso di lunghezza 34 | for (int i = 0; i < riparazioni.length; i++) 35 | nuovoArray[i] = riparazioni[i]; 36 | // aggiungiamo la nuova riparazione in ultima posizione 37 | nuovoArray[riparazioni.length] = riparazione; 38 | // salviamo nel campo riparazioni il riferimento in memoria dell'array esteso con la nuova riparazione 39 | riparazioni = nuovoArray; 40 | } 41 | } 42 | 43 | /** 44 | * Ritorna la riparazione all'indice in input 45 | * 46 | * @param i indice della riparazione nella lista 47 | * @return la Riparazione all'indice in input 48 | */ 49 | public Riparazione get(int i) { 50 | if (i > riparazioni.length) return null; 51 | return riparazioni[i]; 52 | } 53 | 54 | @Override 55 | public String toString() { return Arrays.toString(riparazioni); } 56 | 57 | public static void main(String[] args) { 58 | ListaDiRiparazioni lista = new ListaDiRiparazioni(new Riparazione[]{new Riparazione("Indirizzo test", 1)}); 59 | lista.add(new Riparazione("Indirizzo test 2", 2)); 60 | for (int i = 0; i < lista.length(); i++) 61 | System.out.println(lista.get(i)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/ListaDiTecnici.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Classe per gestire una lista dinamica di Tecnici, 7 | * basata su un array che ad ogni nuovo inserimento viene esteso di 1 (come visto precedentemente nel modulo 2) 8 | */ 9 | public class ListaDiTecnici { 10 | 11 | private Tecnico[] tecnici = new Tecnico[0]; 12 | 13 | public ListaDiTecnici(Tecnico[] tecnici) { 14 | for (Tecnico tecnico : tecnici) 15 | add(tecnico); 16 | } 17 | 18 | /** 19 | * @return lunghezza della lista di tecnici 20 | */ 21 | public int length() { return tecnici.length; } 22 | 23 | /** 24 | * Aggiunge un tecnico nella lista di tecnici, estendendo la dimensione dell'array di 1 25 | * 26 | * @param tecnico il Tecnico da aggiungere alla lista 27 | */ 28 | public void add(Tecnico tecnico) { 29 | if (tecnico != null) { 30 | // estendiamo l'array di tecnici creandone uno nuovo temporaneo di lunghezza maggiore di 1 31 | // così da poter aggiungere un nuovo tecnico 32 | Tecnico[] tmp = new Tecnico[tecnici.length + 1]; 33 | // copiamo ogni tecnico nel nuovo array esteso di lunghezza 34 | for (int i = 0; i < tecnici.length; i++) 35 | tmp[i] = tecnici[i]; 36 | // aggiungiamo il nuovo tecnico in ultima posizione 37 | tmp[tecnici.length] = tecnico; 38 | // salviamo nel campo tecnici il riferimento in memoria dell'array esteso con il nuovo tecnico 39 | tecnici = tmp; 40 | } 41 | } 42 | 43 | /** 44 | * Ritorna il tecnico all'indice in input 45 | * 46 | * @param i indice del tecnico nella lista 47 | * @return il Tecnico all'indice in input 48 | */ 49 | public Tecnico get(int i) { 50 | if (i > tecnici.length) return null; 51 | return tecnici[i]; 52 | } 53 | 54 | @Override 55 | public String toString() { return Arrays.toString(tecnici); } 56 | 57 | public static void main(String[] args) { 58 | ListaDiTecnici lista = new ListaDiTecnici(new Tecnico[]{new Tecnico("Mario")}); 59 | lista.add(new Tecnico("Luigi")); 60 | for (int i = 0; i < lista.length(); i++) 61 | System.out.println(lista.get(i)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/README.MD: -------------------------------------------------------------------------------- 1 | # Ditta di Riparazioni 🛵 2 | 3 | ![Fix-it Felix](https://thumbs.gfycat.com/ArtisticShortEnglishpointer-size_restricted.gif) 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 final 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.IN_ATTESA; 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 | public void setPriorita(int priorita) { 31 | this.priorita = priorita; 32 | } 33 | 34 | @Override 35 | public String toString(){ 36 | return indirizzo+" "+priorita+" "+stato; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /module_04/src/riparazioni/StatoRiparazione.java: -------------------------------------------------------------------------------- 1 | package riparazioni; 2 | 3 | public enum StatoRiparazione { 4 | IN_ATTESA, IN_CORSO, TERMINATA 5 | } 6 | -------------------------------------------------------------------------------- /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 final 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 vaiInFerie() { 35 | this.stato = StatoTecnico.FERIE; 36 | } 37 | 38 | @Override 39 | public String toString(){ 40 | return nome+" "+stato; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /module_05/src/distributoreBevande/distributoreBevande.md: -------------------------------------------------------------------------------- 1 | Distributore di Bevande 🛵 2 | 3 | Scrivere un programma in grado di modellare la gestione di un distributore di bevande. Il distributore gestirà una lista di 2 tipi diversi di prodotti: Caffè e Cappuccino. 4 | Progettare la classe DistributoreDiBevande costruito con un intero n che determina il numero di prodotti nel distributore 5 | Ogni tipo di prodotto può avere un codice univoco e un prezzo uguali nel tempo (ossia per uno stesso tipo di prodotto). 6 | 7 | La classe prevede i seguenti metodi: 8 | 9 | - caricaProdotto: dato un Prodotto p in input, lo carica nel distributore 10 | - inserisciImporto: permette di inserire un importo nella macchinetta 11 | - scegliProdotto: dato in ingresso un codice di prodotto, restituisca il 12 | prodotto associato a quel codice (se l’importo inserito lo consente) e 13 | decrementi il saldo disponibile nel distributore 14 | - saldoAttuale: restituisce il saldo attuale del distributore 15 | - getResto: restituisce il resto dovuto e azzeri il saldo 16 | 17 | 18 | Potete usare questo codice come test 19 | 20 | ``` 21 | Caffe caffe = new Caffe("caffe", 0.5); 22 | Cappuccino cappuccino = new Cappuccino("cappuccino", 1); 23 | DistributoreDiBevande distributoreDiBevande = new DistributoreDiBevande(10); 24 | distributoreDiBevande.caricaProdotto(caffe); 25 | distributoreDiBevande.caricaProdotto(caffe); 26 | distributoreDiBevande.caricaProdotto(cappuccino); 27 | distributoreDiBevande.caricaProdotto(caffe); 28 | distributoreDiBevande.caricaProdotto(caffe); 29 | distributoreDiBevande.caricaProdotto(cappuccino); 30 | distributoreDiBevande.caricaProdotto(caffe); 31 | System.out.println(distributoreDiBevande.saldoAttuale() == 0); 32 | System.out.println(distributoreDiBevande.getResto() == 0); 33 | distributoreDiBevande.inserisciImporto(0.4); 34 | System.out.println(distributoreDiBevande.scegliProdotto("caffe") == null); 35 | distributoreDiBevande.inserisciImporto(0.2); 36 | System.out.println(distributoreDiBevande.scegliProdotto("caffe") != null); 37 | System.out.println(distributoreDiBevande.getResto()-0.10 < 1E-6); 38 | System.out.println(distributoreDiBevande.saldoAttuale() == 0); 39 | System.out.println(distributoreDiBevande.scegliProdotto("caffe") == null); 40 | distributoreDiBevande.inserisciImporto(2.0); 41 | System.out.println(distributoreDiBevande.scegliProdotto("caffe") != null); 42 | System.out.println(distributoreDiBevande.scegliProdotto("cappuccino") != null); 43 | System.out.println(distributoreDiBevande.scegliProdotto("caffe") != null); 44 | System.out.println(distributoreDiBevande.saldoAttuale() == 0); 45 | System.out.println(distributoreDiBevande.getResto()-0.10 < 1E-6); 46 | ``` 47 | 48 | Suggerimento: usate l’ereditarietà 49 | 50 | -------------------------------------------------------------------------------- /module_05/src/formeGeometriche/formeGeometriche.md: -------------------------------------------------------------------------------- 1 | Esercizio 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à -------------------------------------------------------------------------------- /module_05/src/gestoreVeicoli/gestoreVeicoli.md: -------------------------------------------------------------------------------- 1 | # Gestore Veicoli 🛴 2 | 3 | Scrivere un programma in grado di modellare la gestione di diversi tipi di veicoli: automobili e 4 | autocarri. In particolare, create le classi Autocarro e Automobile entrambe con le seguenti 5 | aratteristiche: 6 | Ogni veicolo è caratterizzato da: 7 | - Targa 8 | - Numero di posti 9 | 10 | Gli autocarri hanno una proprietà aggiuntiva: la capacità massima di carico (espressa in quintali). Le automobili, invece, il numero di porte. 11 | Il metodo toString degli oggetti Automobile deve ritornare il numero di targa e il numero di porte, separati dal carattere «:». 12 | Il metodo toString degli oggetti Autocarro, invece, deve ritornare il numero di targa e la massima capacità in quintali, separati dal carattere «:». 13 | 14 | Deve essere possibile eseguire il seguente codice: 15 | 16 | ``` 17 | Automobile automobile = new AutoMobile("cf123rm", 4, 4); 18 | gestione_veicoli.AutoCarro autoCarro = new AutoCarro("ca133sm", 4, 2); 19 | ``` 20 | 21 | Suggerimento: usate l’ereditarietà 22 | -------------------------------------------------------------------------------- /module_05/src/serieA/serieA.md: -------------------------------------------------------------------------------- 1 | # Esercizio Classifica Serie A 🏍 2 | 3 | Progettare una classe Classifica che permetta di gestire la classifica di Serie A costruita a partire da 20 squadre di calcio. Ogni squadra di calcio ha i seguenti attributi: 4 | 5 | * id 6 | * nome 7 | * rosa di giocatori 8 | * punteggio 9 | * gol fatti 10 | * gol subiti 11 | 12 | Ogni giocatore ha un id, un nome e un cognome. In particolare, deve essere possibile gestire le seguenti operazioni: 13 | 14 | * esitoPartita(squadraCasa, golCasa, squadraOspite, golOspite): gestisce il punteggio delle due squadre in base all'esito 15 | * getClassifica(): ritorna la classifica attuale, ordinata per punteggio 16 | * getMigliorAttacco(): ritorna la squadra che ha segnato più gol 17 | * getPeggiorDifesa(): ritorna la squadra che ha concesso più gol -------------------------------------------------------------------------------- /module_06/src/dragonball/README.md: -------------------------------------------------------------------------------- 1 | # DRAGONBALL 2 | 3 | Vogliamo creare un videogioco basato sul famosissimo manga di Akira Toriyama, nel quale i vari 4 | personaggi possono combattere tra di loro in una sorta di Torneo Tenkaichi. 5 | Ogni personaggio ha un nome, dei punti vita, una lista di 4 possibili attacchi personalizzati e una 6 | forza fisica. Inoltre ogni personaggio ha un valore compreso tra 0 ed 1 che rappresenta la sua 7 | capacità di schivare attacchi e un valore compreso tra 0 ed 1 che rappresenta la sua resistenza fisica. 8 | Ogni attacco possibile ha un nome, un valore rappresentante la quantità di danno, e un valore 9 | compreso tra 0 ed 1 che rappresenta la probabilità che l’attacco vada a segno. Notare che per 10 | calcolare la probabilità che un attacco A vada a segno su un personaggio P sarà data dal prodotto 11 | della probabilità che l’attacco vada a segna con la probabilità che l’attacco venga schivato. Quindi 12 | se per esempio il personaggio Goku utilizza il’attacco “Kaikoen” che ha probabilità 0.9 di successo 13 | sul personaggio Freezer che ha probabilità 0.4 di schivare un attacco, la probabilità che l’attacco 14 | vada a segno è: 15 | 16 | - 0.90*0.40 = 0.36 (in pratica il 36% delle volte va a segno). 17 | 18 | __Nota__: un diverso attacco può essere nel kit di più personaggi. Per esempio l’attacco “Kamehameha” 19 | è un attacco sia di Goku che di Gohan che del Maestro delle Tartarughe ecc. 20 | 21 | Torniamo ai personaggi. Essi possono essere di diverso tipo: Umano, Sayan, Namecciano, Cyborg, 22 | Demone (per esempio Majin-bu) e Alieno (per esempio Freezer). Tutti i personaggi, a parte i 4 23 | attacchi personali, hanno un attacco fisico di base, e una probabilità che esso vada a segno che 24 | cambia a seconda del personaggio. Questo attacco fisico di base è a tutti gli effetti un attacco, e il 25 | suo danno è uguale alla forza fisica del personaggio. 26 | Vogliamo inoltre che i personaggi implementino l'interfaccia Comparable, facendo in modo che un personaggio 27 | sia confrontato rispetto agli altri in base ai loro punti vita. 28 | Creare infine una classe Combattimento che rappresenta un combattimento tra due personaggi. 29 | Questa classe avrà tra gli attributi i personaggi stessi e implementerà al proprio interno un metodo 30 | combatti() che simulerà un combattimento. Il metodo eseguirà i seguenti passaggi: 31 | 32 | __1)__ Sceglie a caso il combattente che inizierà per primo. 33 | 34 | __2)__ A turno, i combatteni scaglieranno un attacco preso random dalla lista dei suoi attacchi, calcolerà 35 | randomicamente se l’attacco andrà a segno o meno, e se l’attacco va a segno infligge danno 36 | all’avversario pari al danno che l’attacco infligge moltiplicato per la resistenza fisica dell’avversario 37 | (quindi più questo valore per un personaggio è vicino allo 0 più è resistente, più e vicino ad 1 meno 38 | è resistente). Ad esempio, se Goku riesce ad infliggere un attacco “Kamehameha” a Majin-Bu che 39 | infligge 50 danni, se Majin-Bu ha una resistenza pari a 0.3 il danno inflitto sarà 50*0.3 = 15. 40 | 41 | __3)__ Il combattimento termina quando uno dei due personaggi raggiungerà un numero di punti vita <= 42 | 0. In tal caso il combattimento finisce e i punti vita dei personaggi vengono ripristinati al massimo. 43 | 44 | Creare una classe Main dove vengano creati dei personaggi, degli attacchi, e vengano simulati dei 45 | combattimenti. 46 | 47 | __Nota__: ovviamente se provate a fare più volte lo stesso combattimento potrete accorgervi di avere 48 | risultati diversi: è normale vista la randomicità coinvolta! 49 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/README.md: -------------------------------------------------------------------------------- 1 | Un facoltoso turista americano ci ha chiesto di creare una piattaforma ispirata ad un famoso sito per affittare 2 | case vacanza. Tutti possono registrarsi alla piattaforma e, se approvati come host, caricare una o più abitazioni 3 | e specificare un prezzo, un periodo (data di inizio e data di fine) durante il quale l'abitazione è 4 | prenotabile da altri utenti. Ogni abitazione ha id, nome, indirizzo, numero di locali, numero di posti letto e piano. 5 | Ogni utente ha nome cognome, email, indirizzo e ogni host ha un codice host. In più, un super-host è tale 6 | se ha ricevuto, da quando si è registrato, almeno 100 prenotazioni. 7 | Di ogni prenotazione si deve mantenere un id univoco, le date di inizio e fine, l'abitazione relativa e l'utente che 8 | ha soggiornato. Ogni utente che ha soggiornato presso un abitazione può lasciare un feedback al proprietario 9 | dell'abitazione. Ogni feedback ha un id, un titolo, un testo e un punteggio (da 1 a 5). 10 | Deve essere possibile effettuare le seguenti operazioni nel sistema: 11 | 12 | - ottenere le abitazioni corrispondente ad un certo codice host 13 | - ottenere l'ultima prenotazione dato un id utente 14 | - ottenere l'abitazione più gettonata nell'ultimo mese 15 | - ottenere gli host con più prenotazioni nell'ultimo mese 16 | - ottenere tutti i super-host 17 | - ottenere i 5 utenti con più giorni prenotati nell'ultimo mese 18 | - ottenere il numero medio di posti letto calcolato in base a tutte le abitazioni caricate dagli host 19 | 20 | 21 | Per le date e i periodi potete utilizzare java.time.LocalDateTime e java.time.Duration 22 | esempio: 23 | 24 | ` 25 | Period.between(aDate, sixtyDaysBehind); 26 | ` 27 | Nota: inserire eccezioni dove pensate siano opportune 28 | Nota: gestite tutto con le collection, nessun database (per ora!) 29 | 30 | ## New stage 31 | - scrivere un metodo che presa in input una prenotazione calcoli il suo costo 32 | 33 | Scrivere inoltre le seguenti funzionalità usando degli stream: 34 | 1) ottenere, dati in input una lista di oggetti prenotazione e un double n, il numero di prenotazioni con costo >= n. 35 | 2) ottenere, data in input una lista di oggetti prenotazione, la lista di tutti gli utenti distinti che hanno effettuato 36 | almeno una prenotazione tra quelle in input. 37 | 3) ottenere, dati in input una lista di oggetti prenotazione e un id utente, l'insieme delle prenotazioni effettuate dall'utente. 38 | 4) ottenere, data una lista di abitazioni e un codice host, il numero di abitazioni di quell'host che hanno un numero di posti letto > 2. 39 | 5) ottenere, a partire dalle informazioni del database e dato in input un codice host, il numero di abitazioni possedute da quell'host. (sulle mappe 40 | non posso utilizzare direttamente uno stream, ma posso farlo sull'insieme delle chiavi o sulla collection di valori!) 41 | 42 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/database/Database.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.database; 2 | 3 | import turista_facoltoso.entities.*; 4 | import turista_facoltoso.entities.users.Host; 5 | import turista_facoltoso.entities.users.Utente; 6 | 7 | import java.util.HashMap; 8 | import java.util.HashSet; 9 | 10 | public class Database { 11 | 12 | private static HashMap utenti = new HashMap<>(); 13 | private static HashMap abitazioni = new HashMap<>(); 14 | private static HashMap prenotazioni = new HashMap<>(); 15 | private static HashMap feedbacks = new HashMap<>(); 16 | 17 | private static HashMap> abitazioniHost = new HashMap<>(); 18 | // mappa tra host e insieme delle prenotazioni su abitazioni dell'host 19 | private static HashMap> prenotazioniRicevute = new HashMap<>(); 20 | // mappa tra utenti e prenotazioni effettuate dall'utente 21 | private static HashMap> prenotazioniEffettuate = new HashMap<>(); 22 | // questa mappa è tra i codici delle abitazioni e l'insieme di tutte le prenotazioni effettuate su di essa 23 | private static HashMap> prenotazioniAbitazioni = new HashMap<>(); 24 | 25 | // getter 26 | public static HashMap getAbitazioni() { return abitazioni; } 27 | public static HashMap getFeedbacks() { return feedbacks; } 28 | public static HashMap> getAbitazioniHost() { return abitazioniHost; } 29 | public static HashMap> getPrenotazioniEffettuate() { return prenotazioniEffettuate; } 30 | public static HashMap> getPrenotazioniRicevute() { return prenotazioniRicevute; } 31 | public static HashMap getPrenotazioni() { return prenotazioni; } 32 | public static HashMap getUtenti() { return utenti; } 33 | public static HashMap> getPrenotazioniAbitazioni() { return prenotazioniAbitazioni; } 34 | 35 | public static void addAbitazione(Abitazione ab) { 36 | abitazioni.put(ab.getId(), ab); 37 | prenotazioniAbitazioni.put(ab.getId(), new HashSet<>()); 38 | int idHost = ab.getHost(); 39 | if (abitazioniHost.containsKey(idHost)) { 40 | HashSet abitazioniVecchie = abitazioniHost.get(idHost); 41 | abitazioniVecchie.add(ab.getId()); 42 | abitazioniHost.put(idHost, abitazioniVecchie); 43 | } 44 | else { 45 | HashSet abitazioniVecchie = new HashSet<>(); 46 | abitazioniVecchie.add(ab.getId()); 47 | abitazioniHost.put(idHost, abitazioniVecchie); 48 | } 49 | } 50 | 51 | public static void removeAbitazione(int idAbitazione) { 52 | Abitazione ab = abitazioni.get(idAbitazione); // prendo l'oggetto abitazione dal db 53 | int idHost = ab.getHost(); // prendo il codice host proprietario dell'abitazione 54 | HashSet abitazioniDiQuestoHost = abitazioniHost.get(idHost); // prendo le abitazioni di questo host 55 | abitazioniDiQuestoHost.remove(idAbitazione); // rimuovo l'abitazione desiderata 56 | abitazioniHost.put(idHost, abitazioniDiQuestoHost); // aggiorno la mappa con il nuovo insieme senza l'abitazione eliminata 57 | abitazioni.remove(idAbitazione); // rimuovo l'abitazione anche dall'insieme di tutte le abitazioni 58 | } 59 | 60 | public static void addPrenotazione(Prenotazione pr) { 61 | prenotazioni.put(pr.getId(), pr); // aggiorno la struttura dati prenotazioni 62 | int codiceAbitazionePrenotata = pr.getIdAbitazione(); // prendo l'id dell'abitazione prenotata 63 | Abitazione abitazionePrenotata = abitazioni.get(codiceAbitazionePrenotata); // prendo l'abitazione prenotata 64 | int codiceHost = abitazionePrenotata.getHost(); // ottengo il codice dell'host proprietario 65 | if (prenotazioniRicevute.containsKey(codiceHost)) { // aggiorno la struttura dati prenotazioniRicevute per l'host 66 | HashSet prenotazioniPassate = prenotazioniRicevute.get(codiceHost); 67 | prenotazioniPassate.add(pr.getId()); 68 | prenotazioniRicevute.put(codiceHost, prenotazioniPassate); 69 | } 70 | else { 71 | HashSet prenotazioniPassate = new HashSet<>(); 72 | prenotazioniPassate.add(pr.getId()); 73 | prenotazioniRicevute.put(codiceHost, prenotazioniPassate); 74 | } 75 | int utente = pr.getIdUtente(); // prendo l'utente che ha effettuato la prenotazione 76 | if (prenotazioniEffettuate.containsKey(utente)) { // aggiorno la struttura dati prenotazioniEffettuate 77 | HashSet prenotazioniUtente = prenotazioniEffettuate.get(utente); 78 | prenotazioniUtente.add(pr.getId()); 79 | prenotazioniEffettuate.put(utente, prenotazioniUtente); 80 | } 81 | else { 82 | HashSet prenotazioniUtente = new HashSet<>(); 83 | prenotazioniUtente.add(pr.getId()); 84 | prenotazioniEffettuate.put(utente, prenotazioniUtente); 85 | } 86 | // la aggiungo anche nella mappa abitazioni -> insieme di prenotazioni 87 | HashSet prenotazioniAbitazione = prenotazioniAbitazioni.get(pr.getIdAbitazione()); 88 | prenotazioniAbitazione.add(pr.getId()); 89 | prenotazioniAbitazioni.put(abitazionePrenotata.getId(), prenotazioniAbitazione); 90 | } 91 | 92 | public static void removePrenotazione(Prenotazione pr) { 93 | prenotazioni.remove(pr.getId()); 94 | // rimuovo la prenotazione dalle prenotazioni effettuate dagli utenti 95 | HashSet prenotazioniUtente = prenotazioniEffettuate.get(pr.getIdUtente()); 96 | prenotazioniUtente.remove(pr.getId()); 97 | prenotazioniEffettuate.put(pr.getIdUtente(), prenotazioniUtente); 98 | // rimuovo la prenotazione dalle prenotazioni ricevute dall'host 99 | Abitazione ab = abitazioni.get(pr.getIdAbitazione()); 100 | int codiceHost = ab.getHost(); 101 | HashSet prenotazioniHost = prenotazioniRicevute.get(codiceHost); 102 | prenotazioniHost.remove(ab.getId()); 103 | prenotazioniRicevute.put(codiceHost, prenotazioniHost); 104 | HashSet prenotazioniAbitazione = prenotazioniAbitazioni.get(pr.getIdAbitazione()); 105 | prenotazioniAbitazione.remove(pr.getId()); 106 | prenotazioniAbitazioni.put(pr.getIdAbitazione(), prenotazioniAbitazione); 107 | } 108 | 109 | public static void addFeedback(Feedback fb) { feedbacks.put(fb.getId(), fb); } 110 | public static void removeFeedback(Feedback fb) { feedbacks.remove(fb.getId()); } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/entities/Abitazione.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.entities; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class Abitazione { 6 | 7 | // attributi statici 8 | private static int idTot = 0; 9 | 10 | // attributi 11 | private int id; 12 | private String nome; 13 | private String indirizzo; 14 | private double prezzo; 15 | private int nLocali; 16 | private int nPostiLetto; 17 | private int piano; 18 | private LocalDate inizioDisp; 19 | private LocalDate fineDisp; 20 | private Integer idHost; 21 | 22 | // costruttore 23 | public Abitazione(String nome, String indirizzo, double prezzo, int nLocali, int nPostiLetto, int piano, LocalDate inizioDisp, LocalDate fineDisp, int idHost) { 24 | this.id = idTot++; 25 | this.nome = nome; 26 | this.indirizzo = indirizzo; 27 | this.prezzo = prezzo; 28 | this.nLocali = nLocali; 29 | this.nPostiLetto = nPostiLetto; 30 | this.piano = piano; 31 | this.inizioDisp = inizioDisp; 32 | this.fineDisp = fineDisp; 33 | this.idHost = idHost; 34 | } 35 | 36 | // getter 37 | public int getId() { return id; } 38 | public String getNome() { return nome; } 39 | public String getIndirizzo() { return indirizzo; } 40 | public double getPrezzo() { return prezzo; } 41 | public int getnLocali() { return nLocali; } 42 | public int getnPostiLetto() { return nPostiLetto; } 43 | public int getPiano() { return piano; } 44 | public LocalDate getInizioDisp() { return inizioDisp; } 45 | public LocalDate getFineDisp() { return fineDisp; } 46 | public int getHost() { return idHost; } 47 | 48 | // setter 49 | 50 | public void setNome(String nome) { this.nome = nome; } 51 | public void setIndirizzo(String indirizzo) { this.indirizzo = indirizzo; } 52 | public void setPrezzo(double prezzo) { this.prezzo = prezzo; } 53 | public void setnLocali(int nLocali) { this.nLocali = nLocali; } 54 | public void setnPostiLetto(int nPostiLetto) { this.nPostiLetto = nPostiLetto; } 55 | public void setPiano(int piano) { this.piano = piano; } 56 | public void setInizioDisp(LocalDate inizioDisp) { this.inizioDisp = inizioDisp; } 57 | public void setFineDisp(LocalDate fineDisp) { this.fineDisp = fineDisp; } 58 | } 59 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/entities/Feedback.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.entities; 2 | 3 | import turista_facoltoso.enumerators.Voto; 4 | 5 | public class Feedback { 6 | 7 | // attributi statici 8 | private static int idTot = 0; 9 | 10 | // attributi 11 | private int id; 12 | private String titolo; 13 | private String testo; 14 | private Voto voto; 15 | private int idPrenotazione; 16 | 17 | // costruttore 18 | public Feedback(String titolo, String testo, Voto voto, int idPrenotazione) { 19 | this.id = idTot++; 20 | this.titolo = titolo; 21 | this.testo = testo; 22 | this.voto = voto; 23 | this.idPrenotazione = idPrenotazione; 24 | } 25 | 26 | // getters 27 | public int getId() { return id; } 28 | public String getTitolo() { return titolo; } 29 | public String getTesto() { return testo; } 30 | public Voto getVoto() { return voto; } 31 | public int getIdPrenotazione() { return idPrenotazione; } 32 | 33 | // setters 34 | public void setTitolo(String titolo) { this.titolo = titolo; } 35 | public void setTesto(String testo) { this.testo = testo; } 36 | public void setVoto(Voto voto) { this.voto = voto; } 37 | public void setIdPrenotazione(int idPrenotazione) { this.idPrenotazione = idPrenotazione; } 38 | } 39 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/entities/Prenotazione.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.entities; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | 6 | public class Prenotazione { 7 | 8 | // attributi statici 9 | private static int idTot = 0; 10 | 11 | // attributi 12 | private int id; 13 | private LocalDate inizioPren; 14 | private LocalDate finePren; 15 | private int idUtente; 16 | private int idAbitazione; 17 | private LocalDateTime istantePren; 18 | private int idFeedback; 19 | 20 | // costruttore 21 | public Prenotazione(LocalDate inizioPren, LocalDate finePren, int idUtente, int idAbitazione) { 22 | this.id = idTot; 23 | this.inizioPren = inizioPren; 24 | this.finePren = finePren; 25 | this.idUtente = idUtente; 26 | this.idAbitazione = idAbitazione; 27 | this.istantePren = LocalDateTime.now(); 28 | } 29 | 30 | // getter 31 | public int getId() { return id; } 32 | public LocalDate getInizioPren() { return inizioPren; } 33 | public LocalDate getFinePren() { return finePren; } 34 | public int getIdUtente() { return idUtente; } 35 | public int getIdAbitazione() { return idAbitazione; } 36 | public LocalDateTime getIstantePren() { return istantePren; } 37 | public int getIdFeedback() { return idFeedback; } 38 | 39 | // setter 40 | public void setInizioPren(LocalDate inizioPren) { this.inizioPren = inizioPren; } 41 | public void setFinePren(LocalDate finePren) { this.finePren = finePren; } 42 | public void setIdUtente(int idUtente) { this.idUtente = idUtente; } 43 | public void setIdAbitazione(int idAbitazione) { this.idAbitazione = idAbitazione; } 44 | public void setIdFeedback(int idFeedback) { this.idFeedback = idFeedback; } 45 | } 46 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/entities/users/Host.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.entities.users; 2 | 3 | import turista_facoltoso.database.Database; 4 | import turista_facoltoso.entities.Abitazione; 5 | import turista_facoltoso.entities.Prenotazione; 6 | import turista_facoltoso.entities.users.Utente; 7 | 8 | import java.time.LocalDate; 9 | import java.util.HashSet; 10 | 11 | public class Host extends Utente { 12 | 13 | // attributi statici 14 | private static int codiceTot = 0; 15 | 16 | // attributi 17 | private int codiceHost; 18 | private HashSet abitazioni; // ---> i codici delle abitazioni possedute dall'host 19 | 20 | public Host(String nome, String cognome, String email, String indirizzo) { 21 | super(nome, cognome, email, indirizzo); 22 | codiceHost = codiceTot++; 23 | } 24 | 25 | // getter 26 | public int getCodiceHost() { return codiceHost; } 27 | public HashSet getAbitazioni() { return abitazioni; } 28 | 29 | // setter 30 | public void setCodiceHost(int codiceHost) { this.codiceHost = codiceHost; } 31 | public void setAbitazioni(HashSet abitazioni) { this.abitazioni = abitazioni; } 32 | 33 | // metodi 34 | public void addAbitazione(String nome, String indirizzo, double prezzo, int nLocali, int nPostiLetto, 35 | int piano, LocalDate inizioDisp, LocalDate fineDisp) { 36 | Abitazione ab = new Abitazione(nome, indirizzo, prezzo, nLocali, nPostiLetto, piano, inizioDisp, fineDisp, id); 37 | Database.addAbitazione(ab); 38 | } 39 | 40 | public void removeAbitazione(int idAbitazione) { Database.removeAbitazione(idAbitazione); } 41 | 42 | public void cambiaDisponibilita(int idAbitazione, LocalDate newInizio, LocalDate newFine) { 43 | Abitazione ab = Database.getAbitazioni().get(idAbitazione); 44 | ab.setInizioDisp(newInizio); 45 | ab.setFineDisp(newFine); 46 | } 47 | 48 | // questo metodo permette ad un host di rimuovere una prenotazione a carico di una sua abitazione 49 | public void removePrenotazioneByHost(int idPren) { 50 | Prenotazione pr = Database.getPrenotazioni().get(idPren); 51 | int idAbitazione = pr.getIdAbitazione(); 52 | HashSet abHost = Database.getAbitazioniHost().get(this.id); 53 | if (abHost.contains(idAbitazione)) { Database.removePrenotazione(pr); } 54 | else { System.out.println("Non puoi rimuovere una prenotazione non tua"); } 55 | } 56 | 57 | // questo metodo ritorna tutte le prenotazioni associate all'host 58 | public HashSet prenotazioniHost() { 59 | HashSet idPrenotazioniRicevute = Database.getPrenotazioniRicevute().get(this.id); 60 | HashSet prenotazioniRicevute = new HashSet<>(); 61 | for (Integer idPren : idPrenotazioniRicevute) { 62 | Prenotazione pr = Database.getPrenotazioni().get(idPren); 63 | prenotazioniRicevute.add(pr); 64 | } 65 | return prenotazioniRicevute; 66 | } 67 | 68 | // questo metodo ritorna tutte le prenotazioni di una certa abitazione dell'host 69 | public HashSet prenotazioniHost(int idAbitazione) { 70 | HashSet idPrenotazioniRicevute = Database.getPrenotazioniRicevute().get(this.id); 71 | HashSet prenotazioniRicevute = new HashSet<>(); 72 | for (Integer idPren : idPrenotazioniRicevute) { 73 | Prenotazione pr = Database.getPrenotazioni().get(idPren); 74 | if (pr.getIdAbitazione() == idAbitazione) { 75 | prenotazioniRicevute.add(pr); 76 | } 77 | } 78 | return prenotazioniRicevute; 79 | } 80 | 81 | // questo metodo ritorna la media totale di tutti i voti ricevuti dall'host in una qualsiasi prenotazione 82 | public double mediaHost() { 83 | HashSet prenotazioniHost = Database.getPrenotazioniRicevute().get(this.id); // prendo le prenotazioni ricevute da questo host 84 | double media = 0.0; 85 | int totFeedback = 0; 86 | for (Integer codicePren : prenotazioniHost) { 87 | Prenotazione pr = Database.getPrenotazioni().get(codicePren); 88 | if (pr.getIdFeedback() == 0) continue; 89 | media += Database.getFeedbacks().get(pr.getIdFeedback()).getVoto().getPunteggio(); 90 | totFeedback++; 91 | } 92 | return media / totFeedback; 93 | } 94 | 95 | public double mediaAbitazione(int idAbitazione) { 96 | HashSet prenotazioniHost = Database.getPrenotazioniRicevute().get(this.id); // prendo le prenotazioni ricevute da questo host 97 | double media = 0.0; 98 | int totFeedback = 0; 99 | for (Integer codicePren : prenotazioniHost) { 100 | Prenotazione pr = Database.getPrenotazioni().get(codicePren); 101 | if (pr.getIdFeedback() == 0 || pr.getIdAbitazione() != idAbitazione) continue; 102 | media += Database.getFeedbacks().get(pr.getIdFeedback()).getVoto().getPunteggio(); 103 | totFeedback++; 104 | } 105 | return media / totFeedback; 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/entities/users/Utente.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.entities.users; 2 | 3 | import turista_facoltoso.admin.AirBnB; 4 | import turista_facoltoso.database.Database; 5 | import turista_facoltoso.entities.Abitazione; 6 | import turista_facoltoso.entities.Feedback; 7 | import turista_facoltoso.entities.Prenotazione; 8 | import turista_facoltoso.enumerators.Voto; 9 | 10 | import java.time.LocalDate; 11 | import java.util.HashSet; 12 | 13 | public class Utente { 14 | 15 | // attributi statici 16 | private static int idTotale = 0; 17 | 18 | // attributi 19 | protected int id; 20 | protected String nome; 21 | protected String cognome; 22 | protected String email; 23 | protected String indirizzo; 24 | 25 | public Utente(String nome, String cognome, String email, String indirizzo) { 26 | this.id = idTotale++; 27 | this.nome = nome; 28 | this.cognome = cognome; 29 | this.email = email; 30 | this.indirizzo = indirizzo; 31 | } 32 | 33 | // getter 34 | public int getId() { return id; } 35 | public String getNome() { return nome; } 36 | public String getCognome() { return cognome; } 37 | public String getEmail() { return email; } 38 | public String getIndirizzo() { return indirizzo; } 39 | 40 | // setter 41 | public void setNome(String nome) { this.nome = nome; } 42 | public void setCognome(String cognome) { this.cognome = cognome; } 43 | public void setEmail(String email) { this.email = email; } 44 | public void setIndirizzo(String indirizzo) { this.indirizzo = indirizzo; } 45 | 46 | // metodi 47 | public void addPrenotazione(int idAbitazione, LocalDate inizioPren, LocalDate finePren) { 48 | if (AirBnB.isDisponibile(idAbitazione, inizioPren, finePren)) { 49 | Prenotazione p = new Prenotazione(inizioPren, finePren, this.id, idAbitazione); 50 | Database.addPrenotazione(p); 51 | } 52 | else { System.out.println("Abitazione non disponibile in quel periodo di tempo!"); } 53 | } 54 | 55 | public void removePrenotazione(int idPrenotazione) { 56 | Prenotazione pr = Database.getPrenotazioni().get(idPrenotazione); 57 | if (pr.getIdUtente() == this.id) { Database.removePrenotazione(pr); } // rimuovo solo se la prenotazione è fatta dall'utente 58 | else { System.out.println("Non puoi rimuovere una prenotazione non tua!"); } 59 | } 60 | 61 | public void addFeedback(String titolo, String commento, Voto voto, int idPren) { 62 | Feedback fb = new Feedback(titolo, commento, voto, idPren); 63 | // dobbiamo settare il feedback nell'oggetto prenotazione a cui si riferisce 64 | Prenotazione pr = Database.getPrenotazioni().get(idPren); 65 | pr.setIdFeedback(fb.getId()); 66 | Database.addFeedback(fb); 67 | } 68 | 69 | public void removeFeedback(int idFeedback) { 70 | Feedback fb = Database.getFeedbacks().get(idFeedback); 71 | Prenotazione pr = Database.getPrenotazioni().get(fb.getIdPrenotazione()); 72 | pr.setIdFeedback(0); 73 | Database.removeFeedback(fb); 74 | } 75 | 76 | public void removeFeedbackByPrenotazione(int idPrenotazione) { 77 | Prenotazione pr = Database.getPrenotazioni().get(idPrenotazione); 78 | Feedback fb = Database.getFeedbacks().get(pr.getIdFeedback()); 79 | Database.removeFeedback(fb); 80 | } 81 | 82 | // questo metodo ritorna tutte le prenotazioni effettuate dall'utente 83 | public HashSet prenotazioniEffettuate() { 84 | HashSet prenEffettuate = new HashSet<>(); // creo un nuovo hashset di prenotazioni (nel database gli id) 85 | HashSet codiciPrenEffettuate = Database.getPrenotazioniEffettuate().get(this.id); // prendo i codici delle pren effettuate dall'utente 86 | for (Integer codice : codiciPrenEffettuate) { // mi scorro i codici per prendere le prenotazioni riferite 87 | prenEffettuate.add(Database.getPrenotazioni().get(codice)); // aggiungo ogni prenotazione nell'insieme 88 | } 89 | return prenEffettuate; // e lo ritorno 90 | } 91 | public void visualizzaAbitazioniDisponibili(LocalDate inizio, LocalDate fine) { 92 | for (Abitazione ab : AirBnB.abitazioniDisponibili(inizio, fine)) { 93 | System.out.println(ab); 94 | } 95 | } 96 | 97 | 98 | 99 | } 100 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/enumerators/Voto.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.enumerators; 2 | 3 | public enum Voto { 4 | 5 | ONE(1, "Fa schifo"), TWO(2, "Un mezzo schifo"), 6 | THREE(3, "discreto"), FOUR(4, "buono"), FIVE(5, "da paura"); 7 | 8 | private int punteggio; 9 | private String descrizione; 10 | 11 | Voto(int punteggio, String descrizione) { 12 | this.punteggio = punteggio; 13 | this.descrizione = descrizione; 14 | } 15 | 16 | public int getPunteggio() { 17 | return punteggio; 18 | } 19 | 20 | public String getDescrizione() { 21 | return descrizione; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /module_06/src/turista_facoltoso/main/Main.java: -------------------------------------------------------------------------------- 1 | package turista_facoltoso.main; 2 | 3 | import turista_facoltoso.admin.AirBnB; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | AirBnB admin = AirBnB.getInstance(); 9 | 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /module_07/src/esempi/comparable/Word.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Comparator; 3 | import java.util.List; 4 | 5 | public class Word implements Comparable { 6 | private int i; 7 | private String word; 8 | 9 | Word(int i, String word) { 10 | this.i = i; 11 | this.word = word; 12 | } 13 | 14 | public int getI() { return i; } 15 | public String getWord() { return word; } 16 | 17 | @Override 18 | public int compareTo(Word o) { 19 | // return 0 --> this == word 20 | // return -1 --> this < word 21 | // return +1 --> this > word 22 | int compareStr = this.word.compareTo(o.getWord()); 23 | 24 | // quando le stringhe sono uguali compariamo gli interi 25 | if (compareStr == 0) return Integer.compare(this.i, o.getI()); 26 | 27 | return compareStr; 28 | 29 | /* 30 | // return Integer.compare(this.i, o.getI()); 31 | 32 | if (this.i == word.getI()) return 0; 33 | else if (this.i < word.getI()) return -1; 34 | else return +1; 35 | */ 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "Word{" + 41 | "i=" + i + 42 | ", word='" + word + '\'' + 43 | '}'; 44 | } 45 | 46 | 47 | 48 | public static void main(String[] args) { 49 | 50 | List words = Arrays.asList(new Word(1, "ciao"), new Word(2, "zeta"), new Word(3, "beta")); 51 | 52 | Comparator compareByWord = Comparator.comparing(Word::getWord); 53 | // equivalente alla lambda: Comparator.comparing(w -> w.getWord()); 54 | 55 | Comparator compareBySecondChar = Comparator.comparing(w -> w.getWord().charAt(1)); 56 | 57 | words.sort(compareByWord); 58 | System.out.println(words); 59 | words.sort(compareBySecondChar); 60 | System.out.println(words); 61 | 62 | words.sort(new WordComparator()); 63 | System.out.println(words); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /module_07/src/esempi/comparable/WordComparator.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | 3 | public class WordComparator implements Comparator { 4 | @Override 5 | public int compare(Word o1, Word o2) { 6 | return o1.compareTo(o2); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /module_07/src/esempi/generics/Coppia.java: -------------------------------------------------------------------------------- 1 | package esempiGenerics; 2 | 3 | public class Coppia { 4 | 5 | private T x; 6 | private T y; 7 | 8 | public Coppia() { 9 | 10 | } 11 | 12 | public Coppia(T x, T y) { 13 | this.x = x; 14 | this.y = y; 15 | } 16 | 17 | public T getX() { return x; } 18 | public T getY() { return y; } 19 | 20 | public void setX(T x) { 21 | this.x = x; 22 | } 23 | 24 | public void setY(T y) { 25 | this.y = y; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /module_07/src/esempi/generics/CoppiaDiversa.java: -------------------------------------------------------------------------------- 1 | package esempiGenerics; 2 | 3 | public class CoppiaDiversa { 4 | 5 | private T first; 6 | private S second; 7 | 8 | public CoppiaDiversa(T first, S second) { 9 | this.first = first; 10 | this.second = second; 11 | } 12 | 13 | public T getFirst() { return first; } 14 | public S getSecond() { return second; } 15 | } 16 | -------------------------------------------------------------------------------- /module_07/src/esempi/generics/Main.java: -------------------------------------------------------------------------------- 1 | package esempiGenerics; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | Coppia coppia = new Coppia<>("ciao", "buondi"); 9 | System.out.println(coppia.getX().getClass()); 10 | 11 | // se non dichiaro un tipo tra le parentesi angolari, il tipo generico T viene trattato come il tipo Object 12 | Coppia coppiaGenerica = new Coppia<>(); 13 | coppiaGenerica.setX(10); 14 | coppiaGenerica.setY("ciao"); 15 | 16 | // avendo due segnaposto nella dichiarazione della classe CoppiaDiversa 17 | CoppiaDiversa coppiaParole = new CoppiaDiversa<>("prima_parola", "seconda_parola"); 18 | CoppiaDiversa coppiaDiversa = new CoppiaDiversa<>("parolina", 10); 19 | 20 | } 21 | 22 | public static void returnQualcosa(T oggetto) { 23 | Studente studente = (Studente) oggetto; 24 | System.out.println(studente.getMatricola()); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /module_07/src/esempi/generics/davide/App.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class App { 5 | public static void main(String[] args) throws Exception { 6 | System.out.println("**** SYSTEM STARTUP ****"); 7 | 8 | Scatola scatolaDiInteri = new Scatola<>(42); 9 | System.out.println(scatolaDiInteri.getDescrizioneOggetto()); 10 | 11 | Scatola scatolaDiDouble = new Scatola<>(42.0); 12 | System.out.println(scatolaDiDouble.getDescrizioneOggetto()); 13 | 14 | Scatola scatolaDiString = new Scatola<>("42"); 15 | System.out.println(scatolaDiString.getDescrizioneOggetto()); 16 | 17 | // posso avere ArrayList con String dentro l'operatore diamond, non è un errore 18 | // ma è comunque una ripetizione 19 | List strings = new ArrayList<>(); 20 | strings.add(""); 21 | 22 | // Lista non parametrizzata 23 | List listObj = new ArrayList(); 24 | listObj.get(0); //.get(0) mi torna un tipo Object che devo castare esplicitamente 25 | 26 | System.out.println("**** SYSTEM SHUTDOWN ****"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /module_07/src/esempi/generics/davide/Scatola.java: -------------------------------------------------------------------------------- 1 | public class Scatola { 2 | 3 | private T oggetto; 4 | 5 | private String miaStringa; 6 | 7 | public Scatola(T oggetto) { 8 | this.oggetto = oggetto; 9 | } 10 | 11 | public Scatola(T oggetto, String miaStringa) { 12 | this.oggetto = oggetto; 13 | this.miaStringa = miaStringa; 14 | } 15 | 16 | public T getOggetto() { 17 | return oggetto; 18 | } 19 | 20 | public void setOggetto(T oggetto) { 21 | this.oggetto = oggetto; 22 | } 23 | 24 | public String getMiaStringa() { 25 | return miaStringa; 26 | } 27 | 28 | public void setMiaStringa(String miaStringa) { 29 | this.miaStringa = miaStringa; 30 | } 31 | 32 | public String getDescrizioneOggetto() { 33 | return "L'oggetto è di tipo: " + this.oggetto.getClass().getName(); 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return "Scatola [oggetto=" + oggetto + ", miaStringa=" + miaStringa + "]"; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /module_07/src/supermercato/Cliente.java: -------------------------------------------------------------------------------- 1 | package supermercato; 2 | 3 | import java.util.Comparator; 4 | 5 | public class Cliente implements Comparable , Comparator { 6 | 7 | private static int idTotale = 0; 8 | private int id; 9 | private String nome; 10 | private String cognome; 11 | private int eta; 12 | 13 | public Cliente(String nome, String cognome, int eta) { 14 | this.id = idTotale++; 15 | this.nome = nome; 16 | this.cognome = cognome; 17 | this.eta = eta; 18 | } 19 | 20 | public int getId() { 21 | return id; 22 | } 23 | 24 | public String getNome() { 25 | return nome; 26 | } 27 | 28 | public void setNome(String nome) { 29 | this.nome = nome; 30 | } 31 | 32 | public String getCognome() { 33 | return cognome; 34 | } 35 | 36 | public void setCognome(String cognome) { 37 | this.cognome = cognome; 38 | } 39 | 40 | public int getEta() { 41 | return eta; 42 | } 43 | 44 | public void setEta(int eta) { 45 | this.eta = eta; 46 | } 47 | 48 | @Override 49 | public int compareTo(Cliente o) { 50 | if (this.eta > o.eta) return -1; 51 | else if (this.eta < o.eta) return 1; 52 | else return 0; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return this.nome + " " + this.cognome; 58 | } 59 | 60 | 61 | @Override 62 | public int compare(Object o1, Object o2) { 63 | Cliente c1 = (Cliente) o1; 64 | Cliente c2 = (Cliente) o2; 65 | return c1.getEta() - c2.getEta(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /module_07/src/supermercato/Main.java: -------------------------------------------------------------------------------- 1 | package supermercato; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Cliente c1 = new Cliente("Marco", "Adriani", 29); 7 | Cliente c2 = new Cliente("Anna", "Rossi", 80); 8 | Cliente c3 = new Cliente("Pippo", "Franco", 85); 9 | Cliente c4 = new Cliente("Giulia", "Verdi", 24); 10 | Cliente c5 = new Cliente("Gianni", "Fragola", 70); 11 | 12 | Supermercato supermercato = new Supermercato(); 13 | supermercato.addCliente(c1); 14 | System.out.println(supermercato.getClienti()); 15 | supermercato.addCliente(c2); 16 | System.out.println(supermercato.getClienti()); 17 | supermercato.addCliente(c3); 18 | System.out.println(supermercato.getClienti()); 19 | supermercato.addCliente(c4); 20 | System.out.println(supermercato.getClienti()); 21 | supermercato.addCliente(c5); 22 | 23 | System.out.println(supermercato.getClienti()); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /module_07/src/supermercato/Supermercato.java: -------------------------------------------------------------------------------- 1 | package supermercato; 2 | 3 | import java.util.Comparator; 4 | import java.util.PriorityQueue; 5 | import java.util.Queue; 6 | 7 | public class Supermercato { 8 | 9 | Queue clienti = new PriorityQueue<>(10, Cliente::compareTo); 10 | 11 | 12 | public Queue getClienti() { return clienti; } 13 | 14 | public void addCliente(Cliente c) { 15 | if (!clienti.contains(c)) { // se il cliente non è già presente in coda 16 | boolean b = clienti.offer(c); 17 | if (!b) { 18 | System.out.println("C'è stato un problema nell'inserimento del cliente " + c.getNome() + " " + c.getCognome()); 19 | } 20 | else { 21 | System.out.println("Inserimento del cliente andato a buon fine"); 22 | } 23 | } 24 | } 25 | 26 | public void removeCliente() { clienti.poll(); } 27 | 28 | public void nextCliente() { clienti.peek(); } 29 | 30 | public void inCoda() { clienti.size(); } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /module_07/src/supermercato/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/tinderlike/Interest.java: -------------------------------------------------------------------------------- 1 | package tinderlike; 2 | 3 | import java.util.Comparator; 4 | import java.util.Objects; 5 | 6 | public class Interest implements Comparable{ 7 | private String id, text; 8 | 9 | public Interest(String id, String text) { 10 | this.id = id; 11 | this.text = text; 12 | } 13 | 14 | public String getId() { 15 | return id; 16 | } 17 | 18 | public String getText() { 19 | return text; 20 | } 21 | 22 | @Override 23 | public boolean equals(Object o) { 24 | if (this == o) return true; 25 | if (o == null || getClass() != o.getClass()) return false; 26 | Interest interest = (Interest) o; 27 | return Objects.equals(id, interest.id); 28 | } 29 | 30 | @Override 31 | public int hashCode() { 32 | return Objects.hash(id); 33 | } 34 | 35 | @Override 36 | public int compareTo(Interest o) { 37 | return Comparator.comparing(Interest::getId).compare(this, o); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /module_07/src/tinderlike/README.md: -------------------------------------------------------------------------------- 1 | # Esercizio TinderLike 🛵 2 | 3 | Scrivere un programma per gestire gli interessi in comune tra le persone. 4 | In particolare, deve essere possibile gestire una quantità potenzialmente 5 | infinita di utenti, ognuno con i propri interessi (a ciascun utente può essere 6 | associato uno o più interessi). 7 | Ogni interesse ha un codice e un testo. 8 | 9 | Devono essere possibili le seguenti operazioni: 10 | - inserire un utente e i suoi interessi 11 | - cancellare un utente (e i suoi interessi associati) 12 | - dato un utente u1, ottenere l'utente u2 con più interessi in comune con u1 13 | 14 | ## PLUS 🏍 15 | Ottenere gli utenti più simili (ossia con più interessi in comune) 16 | -------------------------------------------------------------------------------- /module_07/src/tinderlike/TinderLike.java: -------------------------------------------------------------------------------- 1 | package tinderlike; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Scrivere un programma per gestire gli interessi in comune tra le persone. 7 | * In particolare, deve essere possibile gestire una quantità potenzialmente infinita di utenti, 8 | * ognuno con i propri interessi (a ciascun utente può essere associato uno o più interessi). 9 | */ 10 | public class TinderLike { 11 | Map> interestsByUser = new HashMap<>(); 12 | Map userById = new HashMap<>(); 13 | 14 | /** 15 | * Inserisce un utente e un insieme di interessi a lui associati 16 | * 17 | * @param user utente da inserire 18 | * @param interests interessi da associare all'utente inserito 19 | */ 20 | public void insertUserWithInterests(User user, Set interests) { 21 | userById.put(user.getId(), user); 22 | // add interests if user already exists 23 | if (interestsByUser.containsKey(user)) 24 | interestsByUser.get(user).addAll(interests); 25 | else 26 | interestsByUser.put(user, new HashSet<>(interests)); 27 | } 28 | 29 | /** 30 | * Cancella un utente e gli interessi a lui associati 31 | * 32 | * @param user utente da cancellare 33 | */ 34 | public void removeUser(User user) { 35 | interestsByUser.remove(user); 36 | userById.remove(user.getId()); 37 | } 38 | 39 | /** 40 | * Rimuove l'associazione tra gli interessi specificati e l'utente 41 | * 42 | * @param user utente a cui rimuovere gli interessi associati 43 | * @param interests interessi da rimuovere dall'utente 44 | */ 45 | public void removeInterestsForUser(User user, Set interests) { 46 | if(interestsByUser.containsKey(user)) 47 | interestsByUser.get(user).removeAll(interests); 48 | } 49 | 50 | /** 51 | * Trova l'utente con più interessi in comune rispetto all'utente specificato 52 | * 53 | * @param user utente per cui cercare l'utente con più interessi in comune 54 | * @return utente con più interessi in comune rispetto all'utente specificato 55 | */ 56 | public User getMostSimilarUser(User user) { 57 | if(user == null || !interestsByUser.containsKey(user)) 58 | return null; 59 | 60 | Set userInterests = this.interestsByUser.get(user); 61 | User mostSimilarUser = null; 62 | int interestsInCommonCount = 0; 63 | 64 | for(User user2 : this.interestsByUser.keySet()) { 65 | // skip user 66 | if(user2.equals(user)) 67 | continue; 68 | Set interestsInCommon = new HashSet<>(this.interestsByUser.get(user2)); 69 | interestsInCommon.retainAll(userInterests); 70 | if(mostSimilarUser == null || interestsInCommon.size() > interestsInCommonCount) { 71 | mostSimilarUser = user2; 72 | interestsInCommonCount = interestsInCommon.size(); 73 | } 74 | } 75 | return mostSimilarUser; 76 | } 77 | 78 | /** 79 | * Trova gli utenti più simili tra loro, ovvero con più interessi in comune 80 | * 81 | * @return un array di due elementi, contenente la coppia di utenti con più interessi in comune 82 | */ 83 | public User[] getMostSimilarUsers() { 84 | User mostSimilarUser1 = null; 85 | User mostSimilarUser2 = null; 86 | int interestsInCommonCount = 0; 87 | 88 | for(User user : interestsByUser.keySet()){ 89 | 90 | User mostSimilarUser = getMostSimilarUser(user); 91 | Set interestsInCommon = new HashSet<>(interestsByUser.get(user)); 92 | interestsInCommon.retainAll(interestsByUser.get(mostSimilarUser)); 93 | 94 | if(interestsInCommon.size() > interestsInCommonCount) { 95 | mostSimilarUser1 = user; 96 | mostSimilarUser2 = mostSimilarUser; 97 | interestsInCommonCount = interestsInCommon.size(); 98 | } 99 | } 100 | 101 | return new User[]{mostSimilarUser1, mostSimilarUser2}; 102 | } 103 | 104 | public static void main(String[] args) { 105 | TinderLike tinderLike = new TinderLike(); 106 | Interest i1 = new Interest("1", "football"); 107 | Interest i2 = new Interest("2", "tennis"); 108 | Interest i3 = new Interest("3", "cricket"); 109 | Interest i4 = new Interest("4", "jumping"); 110 | Interest i5 = new Interest("5", "gym"); 111 | Interest i6 = new Interest("6", "jogging"); 112 | Interest i7 = new Interest("7", "cards"); 113 | User u1 = new User("1", "mario"); 114 | User u2 = new User("2", "giovanni"); 115 | User u3 = new User("3", "andrea"); 116 | User u4 = new User("4", "jonathan"); 117 | Set s1 = new HashSet<>(); 118 | s1.add(i1); 119 | s1.add(i2); 120 | s1.add(i3); 121 | tinderLike.insertUserWithInterests(u1, s1); 122 | Set s2 = new HashSet<>(); 123 | s2.add(i1); 124 | s2.add(i5); 125 | Set s3 = new HashSet<>(); 126 | s3.add(i2); 127 | s3.add(i3); 128 | Set s4 = new HashSet<>(); 129 | s4.add(i1); 130 | s4.add(i2); 131 | s4.add(i3); 132 | s4.add(i7); 133 | tinderLike.insertUserWithInterests(u2, s2); 134 | tinderLike.insertUserWithInterests(u3, s3); 135 | User u = tinderLike.getMostSimilarUser(u1); 136 | System.out.println(u.getName().equals("andrea")); 137 | tinderLike.insertUserWithInterests(u4, s4); 138 | User[] mostSimilarUsers = tinderLike.getMostSimilarUsers(); 139 | System.out.println(mostSimilarUsers[0].getName().equals("mario")); 140 | System.out.println(mostSimilarUsers[1].getName().equals("jonathan")); 141 | 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /module_07/src/tinderlike/User.java: -------------------------------------------------------------------------------- 1 | package tinderlike; 2 | 3 | import java.util.Objects; 4 | 5 | public class User { 6 | private String id, name; 7 | 8 | public User(String id, String name) { 9 | this.id = id; 10 | this.name = name; 11 | } 12 | 13 | public String getId() { 14 | return id; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | @Override 22 | public boolean equals(Object o) { 23 | if (this == o) return true; 24 | if (o == null || getClass() != o.getClass()) return false; 25 | User user = (User) o; 26 | return Objects.equals(id, user.id); 27 | } 28 | 29 | @Override 30 | public int hashCode() { 31 | return Objects.hash(id); 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "User{" + 37 | "name='" + name + '\'' + 38 | '}'; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /module_08/src/dictionary/CharacterNotPresentException.java: -------------------------------------------------------------------------------- 1 | package dictionary; 2 | 3 | public class CharacterNotPresentException extends ElementNotPresentException { 4 | 5 | CharacterNotPresentException(char character) { 6 | super("Character \"" + character + "\" is not present in the dictionary"); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /module_08/src/dictionary/Dictionary.java: -------------------------------------------------------------------------------- 1 | package dictionary; 2 | 3 | import java.util.*; 4 | 5 | public class Dictionary { 6 | 7 | Map>> dictionary; 8 | 9 | public Dictionary() { 10 | this.dictionary = new TreeMap<>(); 11 | } 12 | 13 | public void insertWord(String word, String meaning) { 14 | if(word == null || meaning == null) 15 | return; 16 | word = word.toLowerCase(); 17 | Character firstLetter = word.charAt(0); 18 | // letter already present 19 | if(dictionary.containsKey(firstLetter)) { 20 | // word already present 21 | if (dictionary.get(firstLetter).containsKey(word)) 22 | dictionary.get(firstLetter).get(word).add(meaning); 23 | // word not present 24 | else { 25 | Set meanings = new TreeSet<>(); 26 | meanings.add(meaning); 27 | dictionary.get(firstLetter).put(word, meanings); 28 | } 29 | } 30 | // letter not present 31 | else { 32 | Map> words = new TreeMap<>(); 33 | Set meanings = new TreeSet<>(); 34 | meanings.add(meaning); 35 | words.put(word, meanings); 36 | dictionary.put(firstLetter, words); 37 | } 38 | } 39 | 40 | public void addMeanings(String word, Set meanings) throws CharacterNotPresentException, WordNotPresentException { 41 | if (word == null || meanings == null || meanings.isEmpty()) 42 | return; 43 | word = word.toLowerCase(); 44 | Character firstLetter = word.charAt(0); 45 | if(!dictionary.containsKey(firstLetter)) 46 | throw new CharacterNotPresentException(firstLetter); 47 | if(!dictionary.get(firstLetter).containsKey(word)) 48 | throw new WordNotPresentException(word); 49 | dictionary.get(firstLetter).get(word).addAll(meanings); 50 | } 51 | 52 | public String printDictionary() { 53 | StringBuilder text = new StringBuilder(); 54 | for (Character letter : dictionary.keySet()) { 55 | Set words = new HashSet<>(); 56 | for (String word : dictionary.get(letter).keySet()) { 57 | String meanings = String.join(";", dictionary.get(letter).get(word)); 58 | words.add(word + ": (" + meanings + ")"); 59 | } 60 | text.append(letter).append(":[").append(String.join(", ", words)).append("]\n"); 61 | } 62 | return text.toString(); 63 | } 64 | 65 | public static void main(String[] args) { 66 | Dictionary dictionary = new Dictionary(); 67 | dictionary.insertWord("retina", "Rete, spesso elastica, indossata sopra i capelli lunghi per tenerli in posizione"); 68 | dictionary.insertWord("retina", "La rètina è la membrana più interna del bulbo oculare"); 69 | dictionary.insertWord("calcio", "sport di squadra"); 70 | dictionary.insertWord("calcio", "elemento chimico"); 71 | dictionary.insertWord("calcio", "colpo dato col piede"); 72 | dictionary.insertWord("calcio", "comune di 5353 abitanti"); 73 | dictionary.insertWord("calcio", "impugnatura del fucile"); 74 | dictionary.insertWord("circuito", "circuito elettrico"); 75 | dictionary.insertWord("circuito", "circuito chiuso dove si svolgono corse"); 76 | Set meanings = new HashSet<>(); 77 | meanings.add("circuito commerciale"); 78 | try { 79 | dictionary.addMeanings("circuito", meanings); 80 | } catch (CharacterNotPresentException e) { 81 | System.out.println("letter c not found"); 82 | } catch (WordNotPresentException e) { 83 | System.out.println("word circuito not found"); 84 | } 85 | System.out.println(dictionary.printDictionary()); 86 | } 87 | 88 | } -------------------------------------------------------------------------------- /module_08/src/dictionary/ElementNotPresentException.java: -------------------------------------------------------------------------------- 1 | package dictionary; 2 | 3 | public class ElementNotPresentException extends Exception { 4 | 5 | ElementNotPresentException(String message) { super(message); } 6 | 7 | } 8 | -------------------------------------------------------------------------------- /module_08/src/dictionary/README.md: -------------------------------------------------------------------------------- 1 | # Esercizio Dictionary 🛵 2 | 3 | Scrivere un programma che per gestire un dizionario. In particolare, ad ogni lettera 4 | dell'alfabeto è associata una lista di parole che iniziano con quella lettera e ad 5 | ogni parola è, a sua volta, associata una lista di significati diversi della parola. 6 | 7 | Esempio: 8 | - c -> caldo -> alta temperatura 9 | - c -> caldo -> pieno di passione 10 | - c -> calcio -> impugnatura della pistola 11 | - c -> calcio -> sport 12 | - c -> calcio -> elemento chimico 13 | 14 | Devono essere possibili almeno le seguenti operazioni: 15 | - `inserisciParola`: inserisce una parola, con almeno un significato associato 16 | - `aggiungiSignificato`: aggiunge il significato per una certa parola 17 | - `toString`: ritorna una stringa contenente ogni parola e significato presente nel dizionario 18 | (in ordine lessicografico ascendente in base alla lettera) nella forma: 19 | 20 | ``` 21 | lettera1: [parola1: (significato1;significato2;...;), parola2: (significato1;...;...;)] 22 | lettera2: [parola1: (significato1;significato2;...;), parola2: (significato1;...;...;)] 23 | ... 24 | letteraN: [parola1: (significato1;significato2;...;), parola2: (significato1;...;...;)] 25 | ``` 26 | 27 | Suggerimenti sulle eccezioni da prevedere: 28 | - `WordNotPresentException`: lanciata nel caso in cui la parola da cercare o rimuovere non sia contenuta 29 | - `MeaningAlreadyExistingException:` lanciata nel caso in cui il significato che vogliamo aggiungere già esista 30 | -------------------------------------------------------------------------------- /module_08/src/dictionary/WordNotPresentException.java: -------------------------------------------------------------------------------- 1 | package dictionary; 2 | 3 | public class WordNotPresentException extends ElementNotPresentException { 4 | WordNotPresentException(String word) { 5 | super("Word \"" + word + "\" is not present in the dictionary"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /module_08/src/floppydisk/README.md: -------------------------------------------------------------------------------- 1 | # Floppy disk 2,5" 🛵 2 | 3 | ![](floppy.jpg) 4 | 5 | Il floppy disk è un supporto magnetico che contiene dati e 6 | può essere acceduto in lettura e scrittura. 7 | Implementare un floppy disk da 2.5 pollici, ovvero con una 8 | capacità pari a 1.474.560 bytes (ovvero 1.44 MB). 9 | Il floppy disk possiede anche un blocco scrittura che è 10 | possibile attivare o disattivare; questo meccanismo, se 11 | attivato, impedisce la scrittura di dati. 12 | 13 | Implementare inoltre i seguenti metodi: 14 | - `posizionaTestina()`: posiziona la testina in posizione k-esima 15 | - `leggi()`: legge i prossimi x byte 16 | - `scrivi()`: scrive i byte passati in input 17 | - `formatta()`: cancella tutti i dati presenti sul floppy disk 18 | - `attivaBloccoScrittura()`: attiva il blocco scrittura 19 | - `disattivaBloccoScrittura()`: disattiva il blocco scrittura 20 | 21 | Prevedere inoltre tutte le situazioni di errore, ad esempio: 22 | - se si cerca di scrivere o formattare mentre è presente il blocco 23 | scrittura 24 | - se si cerca di scrivere ma il disco è pieno 25 | - si cerca di leggere ma non sono presenti sufficienti dati sul disco -------------------------------------------------------------------------------- /module_08/src/floppydisk/floppy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/module_08/src/floppydisk/floppy.jpg -------------------------------------------------------------------------------- /module_09/src/esempi/ReaderWriter.java: -------------------------------------------------------------------------------- 1 | package esempi; 2 | 3 | import java.io.*; 4 | import java.nio.file.*; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | 8 | public class ReaderWriter { 9 | 10 | /** 11 | * Metodo inefficiente per leggere da file tramite la classe Scanner. 12 | * In precedenza utilizzata analogamente per leggere input da tastiera. 13 | * 14 | * La risorsa aperta (in questo caso l'oggetto scanner) 15 | * DEVE essere sempre chiuso in un blocco finally per assicurarsi 16 | * che non rimanga aperta in caso di eccezioni non/mal gestite! 17 | */ 18 | public static void readByScanner(String filePath) { 19 | Scanner sc = null; 20 | try { 21 | sc = new Scanner(new File(filePath)); 22 | while (sc.hasNextLine()) 23 | System.out.println(sc.nextLine()); 24 | } catch (FileNotFoundException e) { 25 | // TODO gestire eccezione !!! 26 | } 27 | finally { if (sc != null) sc.close(); } 28 | } 29 | 30 | /** 31 | * Metodo per leggere da file tramite la classe Scanner, 32 | * utilizzando try-with-resources per chiudere in automatico l'oggetto scanner nel blocco finally. 33 | */ 34 | public static void readByScannerTryWithResources(String filePath) { 35 | try (Scanner sc = new Scanner(new File(filePath))) { 36 | while (sc.hasNextLine()) 37 | System.out.println(sc.nextLine()); 38 | } catch (FileNotFoundException e) { 39 | // TODO gestire eccezione !!! 40 | } 41 | } 42 | 43 | /** 44 | * Lettura standard da file tramite BufferedReader, 45 | * con chiusura automatica tramite try-with-resources. 46 | */ 47 | public static void readByBufferedReader(String filePath) { 48 | // try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { // pre Java 7 49 | try (BufferedReader br = Files.newBufferedReader(Paths.get(filePath))) { // post Java 7 50 | String line; 51 | // "salta" la prima riga del file 52 | br.readLine(); 53 | // legge una riga del file e passa alla successiva finché ce ne sono da leggere nel file buffer 54 | while ((line = br.readLine()) != null) 55 | System.out.println(line); 56 | } 57 | catch (IOException e) { 58 | // TODO gestire eccezione !!! 59 | } 60 | } 61 | 62 | /** 63 | * Lettura di tutto il contenuto di un file senza BufferedReader e necessità di chiudere risorse. 64 | * Leggere una riga per volta è comunque l'utilizzo più consigliato 65 | * per non leggere interamente file di grandi dimensioni e caricare troppe informazioni in memoria. 66 | */ 67 | public static void readAllLines(String filePath) { 68 | try { 69 | List lines = Files.readAllLines(Paths.get(filePath)); 70 | System.out.println(lines); 71 | } catch (IOException e) { 72 | // TODO gestire eccezione !!! 73 | } 74 | } 75 | 76 | /** 77 | * Scrittura su file tramite BufferedWriter, 78 | * con chiusura automatica tramite try-with-resources. 79 | * 80 | * Il comportamento di default è quello di sovrascrivere il file se già esistente, o di crearlo altrimenti. 81 | */ 82 | public static void writeLine(String filePath, String lineToWrite) { 83 | // try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) { // pre Java 7 84 | try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(filePath))) { // post Java 7 85 | bw.write(lineToWrite); 86 | bw.newLine(); 87 | } 88 | catch (IOException e) { 89 | e.printStackTrace(); 90 | } 91 | } 92 | 93 | /** 94 | * Scrittura su file tramite BufferedWriter in modalità append, 95 | * ovvero senza sovrascrivere il file ma aggiungendo in coda. 96 | * 97 | * Altre opzioni di apertura file sono disponibili nell'enum java.nio.file.StandardOpenOption. 98 | */ 99 | public static void appendLine(String filePath, String lineToWrite) { 100 | // try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true))) { // pre Java 7 101 | try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(filePath), StandardOpenOption.APPEND)) { // post Java 7 102 | bw.write(lineToWrite); 103 | bw.newLine(); 104 | } 105 | catch (IOException e) { 106 | e.printStackTrace(); 107 | } 108 | } 109 | 110 | public static void main(String[] args) { 111 | String filePath = "module_09/src/esempi/test.txt"; 112 | Path path = Paths.get("module_09/src/esempi/test.txt"); // sconsigliabile utilizzare "/" per risalire al percorso 113 | Path path2 = Paths.get("module_09", "src", "esempi", "test.txt"); // metodo più robusto per generare un percorso ad un file 114 | 115 | writeLine(filePath, "ciao"); 116 | appendLine(filePath, "ciaociao"); 117 | 118 | readByScanner(filePath); 119 | readByBufferedReader(filePath); 120 | readAllLines(filePath); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /module_09/src/fileandparole/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). 4 | Questo tipo di lavoro è molto utilizzato in vari ambiti, dalla crittografia, alla linguistica, al Natural Language Processing. 5 | Vogliamo realizzare la classe `FileAndParole`, che effettua alcune di queste operazioni ed è composta dai seguenti metodi: 6 | 7 | - `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. 8 | - `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. 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. 10 | SUGGERIMENTO: per eliminare la punteggiatura da una riga di testo utilizzare il metodo `riga.split("\W+")`. 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: 12 | - Terminano con una sequenza vocale-consonante-vocale identica. 13 | - Terminano con una sequenza vocale-consonante-consonante-vocale identica. 14 | 15 | 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). 16 | 17 | Ad esempio se il testo è il seguente: 18 | 19 | "Il soldato è tornato passando per un ponte vicino a una fonte" 20 | 21 | Il metodo deve tornare: 22 | 23 | { 24 | "ato": ["soldato", "tornato"], 25 | "ando": ["passando"], 26 | "onte": ["ponte", "fonte"], 27 | "ino": ["vicino"] 28 | } 29 | 30 | NB: possiamo ignorare completamente le parole con lunghezza minore di 4 lettere. 31 | -------------------------------------------------------------------------------- /module_09/src/mappadirighe/README.md: -------------------------------------------------------------------------------- 1 | # Mappa di righe 🛴 2 | 3 | Leggere il file righe.txt usando le classi del package java.nio, ogni riga segue la formattazione k:v,v,v,v,v 4 | 5 | Creare una `Map` in cui, per ogni riga del file, aggiungiamo la chiave col valore della stringa "k" associata ai valori "v,v,v,v,v" della riga 6 | 7 | Es. 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 211 | -------------------------------------------------------------------------------- /module_10/src/esempi/builder/Main.java: -------------------------------------------------------------------------------- 1 | package esempi.builder; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | UserBuilder ub = new UserBuilder() 7 | .name("Marco") 8 | .age(29); 9 | 10 | System.out.println(ub.getName() + " " + ub.getSurname()); 11 | ub.surname("Adriani"); 12 | System.out.println(ub.getName() + " " + ub.getSurname()); 13 | 14 | User user = ub.build(); 15 | System.out.println(user.getName() + " " + user.getSurname()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /module_10/src/esempi/builder/User.java: -------------------------------------------------------------------------------- 1 | package esempi.builder; 2 | 3 | public class User { 4 | 5 | private String name; 6 | private String surname; 7 | private int age; 8 | 9 | protected User(UserBuilder ub) { 10 | this.name = ub.getName(); 11 | this.surname = ub.getSurname(); 12 | this.age = ub.getAge(); 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public String getSurname() { 20 | return surname; 21 | } 22 | 23 | public int getAge() { 24 | return age; 25 | } 26 | 27 | public void setName(String name) { 28 | this.name = name; 29 | } 30 | 31 | public void setSurname(String surname) { 32 | this.surname = surname; 33 | } 34 | 35 | public void setAge(int age) { 36 | this.age = age; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /module_10/src/esempi/builder/UserBuilder.java: -------------------------------------------------------------------------------- 1 | package esempi.builder; 2 | 3 | public class UserBuilder { 4 | 5 | private String name; 6 | private String surname; 7 | private int age; 8 | 9 | public UserBuilder() {} 10 | 11 | public UserBuilder name(String name) { 12 | this.name = name; 13 | return this; 14 | } 15 | 16 | public UserBuilder surname(String surname) { 17 | this.surname = surname; 18 | return this; 19 | } 20 | 21 | public UserBuilder age(int age) { 22 | this.age = age; 23 | return this; 24 | } 25 | 26 | public User build() { 27 | return new User(this); 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public String getSurname() { 35 | return surname; 36 | } 37 | 38 | public int getAge() { 39 | return age; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /module_10/src/esempi/dao/User.java: -------------------------------------------------------------------------------- 1 | package esempi.dao; 2 | 3 | import java.time.LocalDate; 4 | import java.util.Objects; 5 | 6 | public class User implements Comparable { 7 | 8 | private Integer id; 9 | private String name; 10 | private String lastName; 11 | private LocalDate birthday; 12 | 13 | public User(Integer id, String name, String lastName, LocalDate birthday) { 14 | this.id = id; 15 | this.name = name; 16 | this.lastName = lastName; 17 | this.birthday = birthday; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return "User{" + 23 | "id=" + id + 24 | ", name='" + name + '\'' + 25 | ", lastName='" + lastName + '\'' + 26 | ", birthday=" + birthday + 27 | '}'; 28 | } 29 | 30 | protected void setId(Integer id) { this.id = id; } 31 | 32 | public Integer getId() { return id; } 33 | public String getName() { return name; } 34 | public String getLastName() { return lastName; } 35 | public LocalDate getBirthday() { return birthday; } 36 | 37 | @Override 38 | public boolean equals(Object o) { 39 | if (this == o) return true; 40 | if (o == null || getClass() != o.getClass()) return false; 41 | User user = (User) o; 42 | return id.equals(user.id) && name.equals(user.name) && lastName.equals(user.lastName) && birthday.equals(user.birthday); 43 | } 44 | 45 | @Override 46 | public int hashCode() { return Objects.hash(id, name, lastName, birthday); } 47 | 48 | @Override 49 | public int compareTo(User user) { return this.id.compareTo(user.id); } 50 | } 51 | -------------------------------------------------------------------------------- /module_10/src/esempi/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package esempi.dao; 2 | 3 | import java.util.List; 4 | 5 | public interface UserDao { 6 | boolean insert(User user); 7 | 8 | boolean update(User user); 9 | 10 | boolean delete(int id); 11 | 12 | User get(int id); 13 | 14 | List getAll(); 15 | } 16 | -------------------------------------------------------------------------------- /module_10/src/esempi/dao/UserDaoCsv.java: -------------------------------------------------------------------------------- 1 | package esempi.dao; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.IOException; 6 | import java.nio.file.Files; 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.time.LocalDate; 10 | import java.util.*; 11 | 12 | public class UserDaoCsv implements UserDao { 13 | 14 | private Path usersCsv; 15 | private TreeMap idsToUsers; 16 | 17 | public UserDaoCsv(Path usersCsv) { 18 | this.usersCsv = usersCsv; 19 | this.idsToUsers = new TreeMap<>(); 20 | 21 | try { 22 | if (!Files.exists(usersCsv)) 23 | Files.createFile(usersCsv); 24 | } catch (IOException e) { e.printStackTrace(); } 25 | 26 | try (BufferedReader br = Files.newBufferedReader(usersCsv)) { 27 | String line; 28 | while ((line = br.readLine()) != null) { 29 | String[] values = line.split(","); 30 | Integer id = Integer.parseInt(values[0]); 31 | this.idsToUsers.put(id, new User(id, values[1], values[2], LocalDate.parse(values[3]))); 32 | } 33 | } 34 | catch (IOException e) { e.printStackTrace(); } 35 | } 36 | 37 | @Override 38 | public boolean insert(User user) { 39 | int lastId = 0; 40 | 41 | if (idsToUsers.size() > 0) 42 | lastId = idsToUsers.lastKey(); 43 | 44 | user.setId(lastId + 1); 45 | this.idsToUsers.put(user.getId(), user); 46 | 47 | return save(); 48 | } 49 | 50 | @Override 51 | public boolean update(User user) { 52 | this.idsToUsers.put(user.getId(), user); 53 | return save(); 54 | } 55 | 56 | @Override 57 | public boolean delete(int id) { 58 | User removedUser = idsToUsers.remove(id); 59 | 60 | if (removedUser != null) 61 | return save(); 62 | else 63 | return false; 64 | } 65 | 66 | @Override 67 | public User get(int id) { 68 | return idsToUsers.get(id); 69 | } 70 | 71 | @Override 72 | public List getAll() { 73 | return new ArrayList<>(idsToUsers.values()); 74 | } 75 | 76 | private boolean save() { 77 | try (BufferedWriter bw = Files.newBufferedWriter(this.usersCsv)) { 78 | for (User user : idsToUsers.values()) { 79 | List values = Arrays.asList( 80 | user.getId().toString(), 81 | user.getName(), 82 | user.getLastName(), 83 | user.getBirthday().toString()); 84 | 85 | bw.write(String.join(",", values)); 86 | bw.newLine(); 87 | } 88 | } 89 | catch (IOException e) { 90 | e.printStackTrace(); 91 | return false; 92 | } 93 | 94 | return true; 95 | } 96 | 97 | public static void main(String[] args) { 98 | UserDao userDao = new UserDaoCsv(Paths.get("module_10", "src", "esempi", "dao", "users.csv")); 99 | 100 | userDao.insert(new User(1,"Andrea", "Rossi", LocalDate.of(2023, 2, 28))); 101 | userDao.insert(new User(2,"Luca", "Verdi", LocalDate.of(2023, 2, 27))); 102 | 103 | System.out.println(userDao.getAll()); 104 | 105 | System.out.println(userDao.get(1)); 106 | userDao.update(new User(1,"Giovanni", "Rossi", LocalDate.of(2023, 2, 28))); 107 | System.out.println(userDao.get(1)); 108 | 109 | System.out.println(userDao.get(1)); 110 | userDao.delete(1); 111 | System.out.println(userDao.get(1)); 112 | 113 | System.out.println(userDao.getAll()); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /module_10/src/esempi/dao/UserDaoSql.java: -------------------------------------------------------------------------------- 1 | package esempi.dao; 2 | 3 | import java.util.List; 4 | 5 | // Questa classe idealmente implementerà le stesse funzionalità di UserDaoCsv ma tramite un database SQL vero e proprio 6 | // semplificando la flessibilità di poter passare ad utilizzare il formato SQL piuttosto che l'attuale CSV 7 | public class UserDaoSql implements UserDao { 8 | @Override 9 | public boolean insert(User user) { 10 | return false; 11 | } 12 | 13 | @Override 14 | public boolean update(User user) { 15 | return false; 16 | } 17 | 18 | @Override 19 | public boolean delete(int id) { 20 | return false; 21 | } 22 | 23 | @Override 24 | public User get(int id) { 25 | return null; 26 | } 27 | 28 | @Override 29 | public List getAll() { 30 | return null; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /module_10/src/esempi/dao/users.csv: -------------------------------------------------------------------------------- 1 | 2,Andrea,Rossi,2023-02-28 2 | 3,Luca,Verdi,2023-02-27 3 | 4,Andrea,Rossi,2023-02-28 4 | 5,Luca,Verdi,2023-02-27 5 | 6,Andrea,Rossi,2023-02-28 6 | 7,Luca,Verdi,2023-02-27 7 | -------------------------------------------------------------------------------- /module_10/src/esempi/observer/ConnectionNotifier.java: -------------------------------------------------------------------------------- 1 | package esempi.observer; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class ConnectionNotifier implements Observable { 6 | 7 | private ArrayList observers = new ArrayList<>(); 8 | 9 | public ArrayList getObservers() { 10 | return observers; 11 | } 12 | 13 | @Override 14 | public void addObserver(Observer o) { 15 | observers.add(o); 16 | } 17 | 18 | @Override 19 | public void deleteObserver(Observer o) { 20 | observers.remove(o); 21 | } 22 | 23 | public void notifyObservers() { 24 | for (Observer o : observers) { 25 | o.notifyMe(this, "OK"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /module_10/src/esempi/observer/Main.java: -------------------------------------------------------------------------------- 1 | package esempi.observer; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | ConnectionNotifier connectionNotifier = new ConnectionNotifier(); 7 | User user = new User("Marco", "Adriani", connectionNotifier); 8 | System.out.println(connectionNotifier.getObservers()); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /module_10/src/esempi/observer/Observable.java: -------------------------------------------------------------------------------- 1 | package esempi.observer; 2 | 3 | public interface Observable { 4 | 5 | public void addObserver(Observer o); 6 | public void deleteObserver(Observer o); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /module_10/src/esempi/observer/Observer.java: -------------------------------------------------------------------------------- 1 | package esempi.observer; 2 | 3 | public interface Observer { 4 | 5 | public void notifyMe(Observable o, String message); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /module_10/src/esempi/observer/User.java: -------------------------------------------------------------------------------- 1 | package esempi.observer; 2 | 3 | public class User implements Observer { 4 | 5 | private String name; 6 | private String surname; 7 | 8 | public User(String name, String surname, ConnectionNotifier connectionNotifier) { 9 | this.name = name; 10 | this.surname = surname; 11 | connectionNotifier.addObserver(this); 12 | } 13 | 14 | @Override 15 | public void notifyMe(Observable o, String message) { 16 | if (message.contains("OK") && message.contains(this.name + " " + this.surname)) { 17 | System.out.println("connessione stabilita"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /module_10/src/sharedmobility/Database.java: -------------------------------------------------------------------------------- 1 | package sharedmobility; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.IOException; 6 | import java.nio.file.Files; 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.time.LocalDate; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | public class Database { 14 | 15 | private static Database instance = null; 16 | 17 | private Path usersCsv; 18 | private List users; 19 | 20 | private Database(Path usersCsv) { 21 | this.usersCsv = usersCsv; 22 | this.users = new ArrayList<>(); 23 | 24 | try { 25 | if (!Files.exists(usersCsv)) 26 | Files.createFile(usersCsv); 27 | } catch (IOException e) { e.printStackTrace(); } 28 | 29 | try (BufferedReader br = Files.newBufferedReader(usersCsv)) { 30 | String line; 31 | while ((line = br.readLine()) != null) { 32 | // "1,Mario,Mario,1981-07-09" 33 | // "2,Luigi,Mario,1983-03-04" 34 | // "3,Francesco,Totti,1976-09-27" 35 | this.users.add(User.parseCsv(line)); 36 | } 37 | } 38 | catch (IOException e) { e.printStackTrace(); } 39 | } 40 | 41 | public static Database getInstance() { 42 | if (instance != null) 43 | return instance; 44 | 45 | throw new DatabaseInstanceNotDefined(); 46 | // throw new RuntimeException("Database instance does not exist"); 47 | } 48 | 49 | public static Database getInstance(Path usersCsv) { 50 | if (instance != null && usersCsv.equals(instance.usersCsv)) 51 | return instance; 52 | 53 | instance = new Database(usersCsv); 54 | return instance; 55 | } 56 | 57 | public boolean insertUser(User user) { 58 | int lastId = 0; 59 | 60 | if (users.size() > 0) 61 | lastId = users.get(users.size()-1).getId(); 62 | 63 | user.setId(lastId+1); 64 | // insert user in this.users 65 | users.add(user); 66 | 67 | // insert user in csv 68 | return updateUsersCsv(); 69 | } 70 | 71 | public void removeUser(int userId) { 72 | // remove user from this.users 73 | // remove user from csv 74 | } 75 | 76 | private boolean updateUsersCsv() { 77 | try (BufferedWriter bw = Files.newBufferedWriter(this.usersCsv)) { 78 | for (User user : users) { 79 | bw.write(user.getCsv()); 80 | bw.newLine(); 81 | } 82 | } 83 | catch (IOException e) { 84 | e.printStackTrace(); 85 | return false; 86 | } 87 | 88 | return true; 89 | } 90 | 91 | public static void main(String[] args) { 92 | Database db = Database.getInstance(Paths.get("module_10", "src", "sharedmobility", "users.csv")); 93 | // Database db = new Database(Paths.get("module_10", "src", "sharedmobility", "users.csv")); 94 | Database db2 = Database.getInstance(Paths.get("module_10", "src", "sharedmobility", "users.csv")); 95 | // Database db2 = new Database(Paths.get("module_10", "src", "sharedmobility", "users.csv")); 96 | 97 | db.insertUser(new User(1,"Nuovo", "Utente", LocalDate.of(2023, 2, 28))); 98 | System.out.println(db.users); 99 | System.out.println(db2.users); 100 | db2.updateUsersCsv(); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /module_10/src/sharedmobility/DatabaseInstanceNotDefined.java: -------------------------------------------------------------------------------- 1 | package sharedmobility; 2 | 3 | public class DatabaseInstanceNotDefined extends RuntimeException { 4 | public DatabaseInstanceNotDefined() { super("Database instance not defined"); } 5 | } 6 | -------------------------------------------------------------------------------- /module_10/src/sharedmobility/README.md: -------------------------------------------------------------------------------- 1 | # Compagnia Shared Mobility 🛵 2 | 3 |

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 | 48 | ## Bonus stage: design patterns 49 | 50 | - Implementare, tramite il design pattern Observer/Observable, un sistema che notifichi all'utente quando sia terminato un noleggio, stampando su console un messaggio che lo avvisi e indicando il prezzo del noleggio terminato. 51 | - Per tutte le entità del database (utente, veicolo, ecc) implementare il design pattern Builder, e farne uso in tutti i metodi che aggiungono entità nel database (inserire un utente, inserire un veicolo, ecc.). 52 | 53 | ## Bonus stage 2: lettura/scrittura file 54 | 55 | Aggiornare la classe Database per poter gestire un "database" in formato CSV, ovvero una serie di file di testo, 56 | uno per ogni entità del sistema (es. utenti, veicoli, ecc), in cui in ogni riga contiene le informazioni relative ad una 57 | specifica istanza di quell'entità separate da virgole (es. nel file degli utenti, ogni riga conterrà le informazioni di un diverso utente). 58 | Esempio: 59 | ``` 60 | ID,Nome,Cognome,Data di nascita 61 | 1,Mario,Rossi,15/11/1968 62 | 2,Luigi,Mario,26/03/1989 63 | 3,Francesco,Totti,27/09/1976 64 | ``` 65 | La classe dovrà quindi prevedere le seguenti funzionalità: 66 | - Creazione a partire da dei percorsi a dei file CSV 67 | - nel caso siano già esistenti, caricando in memoria le informazioni che contengono 68 | - altrimenti, creando dei nuovi file su cui scrivere successivamente 69 | - Aggiornamento del contenuto dei file ad ogni operazione di modifica (es. inserisci utente, rimuovi utente, modifica utente, ecc) 70 | 71 | Inoltre, è necessario implementare, tramite il design pattern Singleton, l'univocità delle istanze della classe Database, così da evitare conflitti di lettura/scrittura sul nostro "database" in formato CSV. -------------------------------------------------------------------------------- /module_10/src/sharedmobility/User.java: -------------------------------------------------------------------------------- 1 | package sharedmobility; 2 | 3 | import java.time.LocalDate; 4 | import java.util.Arrays; 5 | 6 | public class User { 7 | private Integer id; 8 | private String name; 9 | private String lastName; 10 | private LocalDate birthday; 11 | 12 | public User(Integer id, String name, String lastName, LocalDate birthday) { 13 | this.id = id; 14 | this.name = name; 15 | this.lastName = lastName; 16 | this.birthday = birthday; 17 | } 18 | 19 | public void setId(Integer id) { this.id = id; } 20 | 21 | public Integer getId() { return id; } 22 | 23 | public String getCsv() { 24 | return String.join(",", Arrays.asList(id.toString(), name, lastName, birthday.toString())); 25 | } 26 | 27 | @Override 28 | public String toString() { 29 | return "User{" + 30 | "id=" + id + 31 | ", name='" + name + '\'' + 32 | ", lastName='" + lastName + '\'' + 33 | ", birthday=" + birthday + 34 | '}'; 35 | } 36 | 37 | public static User parseCsv(String userCsv) { 38 | String[] values = userCsv.split(","); 39 | return new User(Integer.parseInt(values[0]), values[1], values[2], LocalDate.parse(values[3])); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /module_10/src/sharedmobility/users.csv: -------------------------------------------------------------------------------- 1 | 1,Mario,Mario,1981-07-09 2 | 2,Luigi,Mario,1983-03-04 3 | 3,Francesco,Totti,1976-09-27 4 | 4,Nuovo,Utente,2023-02-28 5 | -------------------------------------------------------------------------------- /module_11/resources/testuccio.txt: -------------------------------------------------------------------------------- 1 | ciao a tutti 2 | questo è un testo di prova 3 | inventato da Marco per farvi vedere 4 | come si crei uno stream di righe a partire dal file. 5 | è una cosa molto utile 6 | se ci pensate -------------------------------------------------------------------------------- /module_11/src/MonstersAndTreasures/README.md: -------------------------------------------------------------------------------- 1 | ## MONSTERS AND TREASURES 2 | 3 | Vogliamo progettare un videogame con una struttura simile al famoso gioco da tavolo Dungeons&Dragons. 4 | Il gioco sarà composto da una serie di avventure o campagne che un team di giocatori deve affrontare. Il gioco terminerà quando tutte le avventure 5 | saranno completate. 6 | Ogni avventura, da affrontare in sequenza una dopo l'altra, è composta da una mappa (una matrice nxn, la dimensione può variare da avventura ad avventura). 7 | Ogni mappa avrà una coordinata di entrata e una di uscita (poste su un bordo della matrice) e contiene, in ogni coordinata, una delle seguenti: 8 | - Uno spazio vuoto. 9 | - Un muro (dove ovviamente i giocatori non potranno passare). 10 | - Uno o più giocatori. 11 | - Un mostro. 12 | - Un tesoro. 13 | 14 | Per terminare un'avventura i giocatori dovranno raccogliere tutti quanti i tesori, sconfiggendo ogni mostro che gli si pari davanti la strada. Fin quando 15 | i tesori non saranno tutti raccolti, i giocatori non potranno uscire neanche se raggiungessero l'uscita. 16 | Ogni giocatore/personaggio avrà un nome, un livello di esperienza, una razza, una classe, i punti vita totali, i punti vita che ha in quel momento del gioco, 17 | degli equipaggiamenti, un insieme di oggetti (che chiameremo item) e delle abilità. Ogni giocatore inoltre avrà un punteggio per le seguenti specialità: 18 | intelligenza, carisma, forza, costituzione, destrezza, stregoneria e saggezza. Per quanto riguarda i valori iniziali alla creazione del giocatore, si deve tirare un dado 19 | a 6 facce e sommare il risultato ai valori di base dati dalla propria razza (umano, elfo, nano, ecc.) e dalla propria classe (un ladro avrà inizialmente 20 | più destrezza di un mago, ma il mago ha sicuramente più punti iniziali di stregoneria rispetto a un guerriero). Successivamente, in base alle informazioni 21 | sulla classe a cui appartiene, ad ogni livello che avanza questi attributi verranno modificati. 22 | 23 | Una abilità è invece composta dai tipi di specialità coinvolti (per esempio un'abilità può sia essere una prova di destrezza sia di carisma), un danno e una 24 | probabilità che vada a segno, che è un numero compreso tra 1 e 20 (quando usiamo un'abilità dovremo tirare un dado a 20 facce, quindi 1 vuol dire che va a 25 | segno una volta su 20, 20 che va a segno sempre). 26 | 27 | Un equipaggiamento invece è un oggetto che si lega ai giocatori in maniera permanente e gli assicura un power-up sulle specialità. Per esempio uno scettro magico 28 | può aumentare il punteggio di intelligenza e stregoneria, o una nuova spada può aggiungere punti di forza). Alcuni equipaggiamenti per bilanciare il proprio 29 | potere su una specifica specialità possono abbassare il punteggio su altre. Ad esempio una spada molto potente ma estremamente pesante può aumentare di molto 30 | i punti di forza sacrificando della destrezza. I tipi di equipaggiamento sono armatura, spada, pugnale, mazza, arco, copricapo, scettro, calzatura, copricapo. 31 | Un personaggio può avere contemporaneamente solo: 32 | - 1 armatura 33 | - 1 calzatura 34 | - 1 copricapo 35 | - al massimo 3 di tutti gli altri equipaggiamenti. 36 | 37 | Gli oggetti invece permettono di avere dei power-up consumabili (quindi dalla durata di al massimo qualche turno o fino alla fine del combattimento). Possono 38 | anche svolgere funzioni di utilità, come curare o resuscitare un compagno morto durante il combattimento. 39 | 40 | Un tesoro è un oggetto che può contenere più equipaggiamenti e oggetti. Una volta preso un tesoro il giocatore che lo prende per primo potrà scegliere 41 | se distribuire il tesoro e come agli altri giocatori. Gli equipaggiamenti eventualmente in più saranno scartati a meno che il giocatore che ha trovato 42 | il tesoro non decida di sostituirlo con un suo già presente o lo doni a un suo compagno. Sulla quantità di oggetti invece non c'è limite. 43 | 44 | Ogni turno si svolge facendo giocare un giocatore alla volta (l'ordine è in base alla destrezza). Un giocatore ad ogni turno può cambiare di una posizione, 45 | e se si trova muovendosi sulla casella di un mostro, deve necessariamente combatterci. Il combattimento termina quando nessun giocatore rimane in vita 46 | oppure quando il mostro viene sconfitto. Mentre se ci si trova in una casella tesoro, questo viene trattato come scritto sopra. 47 | 48 | In un combattimento il mostro attacca sempre per primo. Un mostro avrà un livello, dei punti vita, un quantitativo di esperienza che distribuirà ai giocatori 49 | che hanno partecipato al combattimento se sconfitto. Inoltre anche lui avrà una serie di abilità e ha anche un set di specialità da usare per sconfiggere 50 | il mostro. Ad esempio un mago oscuro è un mostro che per essere sconfitto ha bisogno di subire delle abilità con specialità stregoneria, saggezza o 51 | intelligenza (se sei un guerriero ti mena prima che arrivi!). Un mostro può anche possedere dei tesori. 52 | 53 | Un combattimento si svolge nelle seguenti fasi: 54 | - Attaccano a turno mostro e giocatori coinvolti. 55 | - Ad ogni turno il mostro può solo attaccare con le sue abilità, mentre i giocatori possono: attaccare, usare un oggetto o tentare la fuga. Purchè ogni 56 | attacco vada a segno bisogna tirare un dado a 20 facce. Un oggetto si può usare sia su se stessi che su un altro compagno. Per la fuga bisogna tirare un dado 57 | da 1 a 6 e la fuga riesce se esce 6. Gli attacchi o abilità che i giocatori possono fare al mostro come detto sono solo quelli che contengono almeno una delle 58 | specialità che il mostro ha come caratteristica. 59 | - Se uno dei giocatori termina i punti vita è morto, e può tornare in vita solo grazie all'uso di speciali oggetti da parte di un compagno. Se tutti i giocatori 60 | muoiono è game over. 61 | - Se il mostro muore vengono distribuiti ai giocatori la sua exp e i tesori. In questo caso il possessore dei tesori del mostro sarà quello che gli ha dato il 62 | colpo di grazia. 63 | 64 | Un giocatore può guadagnare esperienza nei seguenti modi: 65 | - Sconfiggendo un mostro (in tal caso l'exp è distribuita equamente tra i giocatori). 66 | - Tramite oggetti specifici. 67 | - Terminando le singole avventure. 68 | 69 | Come detto il gioco termina dopo aver terminato tutte le avventure! 70 | -------------------------------------------------------------------------------- /module_12/src/AndiamoATeatro.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/module_12/src/AndiamoATeatro.pdf -------------------------------------------------------------------------------- /module_12/src/esempi/DatabaseConnection.java: -------------------------------------------------------------------------------- 1 | import java.sql.*; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | public class DatabaseConnection { 6 | 7 | public static void main(String[] args) throws SQLException { 8 | /* scriviamo un programma che legge da database e crea oggetti */ 9 | List utenti = new ArrayList<>(); 10 | 11 | // 1) aprire una connessione 12 | Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/aibnb", "postgres", "password"); 13 | 14 | // 2) creo uno statement 15 | Statement statement = connection.createStatement(); 16 | 17 | // 3) posso lanciare delle query e salvare il risultato in un resultSet 18 | ResultSet resultSet = statement.executeQuery("select nome, cognome from utente"); 19 | 20 | // 4) leggo i dati 21 | while (resultSet.next()) { // per ogni record (riga) della tabella risultato 22 | String nome = resultSet.getString("nome"); 23 | String cognome = resultSet.getString("cognome"); 24 | Utente u = new Utente(nome, cognome); 25 | utenti.add(u); 26 | } 27 | 28 | // chiudo lo statement 29 | statement.close(); 30 | 31 | System.out.println(utenti); 32 | 33 | // provo ad aggiungere un utente 34 | Utente u = new Utente("Francesco", "Totti", "ciccio@gmail.com", "36985254"); 35 | addUtente(u, connection); 36 | } 37 | 38 | public static void addUtente(Utente u, Connection connection) throws SQLException { 39 | PreparedStatement preparedStatement = connection 40 | .prepareStatement("INSERT INTO utente (nome,cognome,email, indirizzo) VALUES (?, ?, ?, ?)"); 41 | preparedStatement.setString(1, u.getNome()); 42 | preparedStatement.setString(2, u.getCognome()); 43 | preparedStatement.setString(3, u.getEmail()); 44 | preparedStatement.setString(4, u.getIndirizzo()); 45 | preparedStatement.executeUpdate(); 46 | preparedStatement.close(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /module_12/src/esempi/connectionhandler/ConnectionHandler.java: -------------------------------------------------------------------------------- 1 | package esempi.connectionhandler; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.nio.file.Files; 6 | import java.nio.file.Path; 7 | import java.nio.file.Paths; 8 | import java.sql.*; 9 | import java.util.Properties; 10 | 11 | public class ConnectionHandler implements AutoCloseable { 12 | 13 | public static final String DB_URL_PREFIX = "jdbc:postgresql://"; 14 | 15 | public static final Path propertiesPath = Paths.get("module_12", "src", "esempi", "connectionhandler", "config.properties"); 16 | 17 | private static ConnectionHandler instance; 18 | 19 | private Connection connection; 20 | 21 | private Properties dbProps; 22 | 23 | private ConnectionHandler() { 24 | try (BufferedReader br = Files.newBufferedReader(propertiesPath)) 25 | { 26 | // carichiamo le properties del database direttamente da file 27 | this.dbProps = new Properties(); 28 | this.dbProps.load(br); 29 | 30 | // sostituendo la precedente inizializzazione manuale 31 | // this.dbProps.setProperty("user", DB_USER); 32 | // this.dbProps.setProperty("password", DB_PASSWORD); 33 | 34 | System.out.println("Host name: " + dbProps.getProperty("host") + ":" + dbProps.getProperty("port")); 35 | System.out.println("Database name: " + dbProps.getProperty("name")); 36 | System.out.println("DB username: " + dbProps.getProperty("user")); 37 | System.out.println("DB password: " + dbProps.getProperty("password")); 38 | } 39 | catch (IOException e) { e.printStackTrace(); } 40 | 41 | // Explicitly loading the driver is no longer required since Java 1.6 42 | // https://jdbc.postgresql.org/documentation/use/#loading-the-driver 43 | // Class.forName("org.postgresql.Driver"); 44 | } 45 | 46 | public static ConnectionHandler getInstance() { 47 | if (instance == null) 48 | instance = new ConnectionHandler(); 49 | 50 | return instance; 51 | } 52 | 53 | public String getDatabaseUrl() { 54 | return DB_URL_PREFIX + 55 | dbProps.getProperty("host") + 56 | ":" + dbProps.getProperty("port") + 57 | "/" + dbProps.getProperty("name"); 58 | } 59 | 60 | public Connection getConnection() throws SQLException { 61 | if (this.connection == null || this.connection.isClosed()) 62 | // se la connessione non esiste o è chiusa, ne viene creata una nuova 63 | this.connection = DriverManager.getConnection(getDatabaseUrl(), dbProps); 64 | 65 | return this.connection; 66 | } 67 | 68 | public void closeConnection() throws SQLException { 69 | if (this.connection != null && !this.connection.isClosed()) { 70 | this.connection.close(); 71 | this.connection = null; 72 | } 73 | } 74 | 75 | @Override 76 | public void close() throws SQLException { this.closeConnection(); } 77 | 78 | public PreparedStatement getPreparedStatement(String query) throws SQLException { 79 | // utilizziamo il metodo getConnection invece di accedere direttamente al campo connection 80 | // per garantire che la connection esista e sia attiva 81 | Connection conn = getConnection(); 82 | 83 | return conn.prepareStatement(query); 84 | } 85 | 86 | public static void main(String[] args) throws SQLException { 87 | // esistono vari modi per ottenere una connection con un DB postgresql 88 | String username = "postgres"; 89 | String password = "postgres"; 90 | Connection conn; 91 | 92 | // 1. specificando tutti i parametri nell'url 93 | conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/AndiamoATeatro?user=" + username + "&password=" + password); 94 | 95 | // 2. specificando user e password come parametri del metodo getConnection 96 | // (eventuali altri parametri andranno comunque specificati nell'url) 97 | conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/AndiamoATeatro", username, password); 98 | 99 | // 3. utilizzando un oggetto Properties 100 | Properties props = new Properties(); 101 | props.setProperty("user", username); 102 | props.setProperty("password", password); 103 | conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/AndiamoATeatro", props); 104 | 105 | PreparedStatement ps = conn.prepareStatement("SELECT id, nome, cognome FROM utente;"); 106 | ResultSet rs = ps.executeQuery(); 107 | // while (rs.next()) System.out.println(rs.getString("nome")); 108 | 109 | conn.close(); 110 | ps.close(); 111 | rs.close(); 112 | 113 | // <-------------------------------------------- ConnectionHandler --------------------------------------------> 114 | 115 | // gestiamo in maniera strutturata apertura/chiusura della connessione con il DB, garantendone l'univocità 116 | ConnectionHandler ch = ConnectionHandler.getInstance(); 117 | ps = ch.getPreparedStatement("SELECT * FROM utente;"); 118 | rs = ps.executeQuery(); 119 | // while (rs.next()) System.out.println(rs.getString("nome")); 120 | 121 | ch.closeConnection(); 122 | ps.close(); 123 | rs.close(); 124 | 125 | // implementando l'interfaccia AutoClosable, 126 | // possiamo chiudere il tutto (PreparedStatement, ResultSet e Connection) anche tramite try-with-resources 127 | try (ConnectionHandler ch2 = ConnectionHandler.getInstance(); 128 | PreparedStatement ps2 = ch2.getPreparedStatement("SELECT * FROM utente;"); 129 | ResultSet rs2 = ps2.executeQuery()) 130 | { 131 | while (rs2.next()) System.out.println(rs2.getString("nome")); 132 | } 133 | /* 134 | // la chiusura manuale di ogni risorsa aperta non è più necessaria (che andrebbe fatta in un finally) 135 | finally { 136 | ch2.closeConnection(); 137 | ps2.close(); 138 | rs2.close(); 139 | } 140 | */ 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /module_12/src/esempi/connectionhandler/Dao.java: -------------------------------------------------------------------------------- 1 | package esempi.connectionhandler; 2 | 3 | import java.sql.SQLException; 4 | import java.util.List; 5 | import java.util.Optional; 6 | 7 | public interface Dao { 8 | boolean insert(T entity) throws SQLException; 9 | 10 | boolean update(T entity) throws SQLException; 11 | 12 | boolean delete(int id) throws SQLException; 13 | 14 | Optional get(int id) throws SQLException; 15 | 16 | List getAll() throws SQLException; 17 | } 18 | -------------------------------------------------------------------------------- /module_12/src/esempi/connectionhandler/User.java: -------------------------------------------------------------------------------- 1 | package esempi.connectionhandler; 2 | 3 | import java.sql.ResultSet; 4 | import java.sql.SQLException; 5 | import java.util.Objects; 6 | 7 | public class User implements Comparable { 8 | 9 | private Integer id; 10 | private String name; 11 | private String lastName; 12 | 13 | public User(String name, String lastName) { 14 | this(null, name, lastName); 15 | } 16 | 17 | public User(Integer id, String name, String lastName) { 18 | this.id = id; 19 | this.name = name; 20 | this.lastName = lastName; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | return "User{" + 26 | "id=" + id + 27 | ", name='" + name + '\'' + 28 | ", lastName='" + lastName + '\'' + 29 | '}'; 30 | } 31 | 32 | public Integer getId() { return id; } 33 | public String getName() { return name; } 34 | public String getLastName() { return lastName; } 35 | 36 | public static User fromResultSet(ResultSet rs) throws SQLException { 37 | return new User(rs.getInt("id"), rs.getString("nome"), rs.getString("cognome")); 38 | } 39 | 40 | @Override 41 | public boolean equals(Object o) { 42 | if (this == o) return true; 43 | if (o == null || getClass() != o.getClass()) return false; 44 | User user = (User) o; 45 | return id.equals(user.id) && name.equals(user.name) && lastName.equals(user.lastName); 46 | } 47 | 48 | @Override 49 | public int hashCode() { return Objects.hash(id, name, lastName); } 50 | 51 | @Override 52 | public int compareTo(User user) { return this.id.compareTo(user.id); } 53 | } 54 | -------------------------------------------------------------------------------- /module_12/src/esempi/connectionhandler/UserDao.java: -------------------------------------------------------------------------------- 1 | package esempi.connectionhandler; 2 | 3 | import java.sql.SQLException; 4 | import java.util.List; 5 | 6 | public interface UserDao extends Dao { 7 | List getByLastName(String lastName) throws SQLException; 8 | } 9 | 10 | /* 11 | public interface UserDao { 12 | boolean insert(User user) throws SQLException; 13 | 14 | boolean update(User user) throws SQLException; 15 | 16 | boolean delete(int id) throws SQLException; 17 | 18 | User get(int id) throws SQLException; 19 | List getByLastName(String lastName) throws SQLException; 20 | List getAll() throws SQLException; 21 | } 22 | */ 23 | -------------------------------------------------------------------------------- /module_12/src/esempi/connectionhandler/UserDaoSql.java: -------------------------------------------------------------------------------- 1 | package esempi.connectionhandler; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.ResultSet; 5 | import java.sql.SQLException; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Optional; 9 | 10 | public class UserDaoSql implements UserDao { 11 | 12 | @Override 13 | public boolean insert(User user) throws SQLException { 14 | String query = "INSERT INTO utente (nome, cognome) VALUES (?, ?);"; 15 | 16 | try (ConnectionHandler ch = ConnectionHandler.getInstance(); 17 | PreparedStatement ps = ch.getPreparedStatement(query)) 18 | { 19 | ps.setString(1, user.getName()); 20 | ps.setString(2, user.getLastName()); 21 | int insertedCount = ps.executeUpdate(); 22 | 23 | return insertedCount > 0; 24 | } 25 | } 26 | 27 | @Override 28 | public boolean update(User user) throws SQLException { 29 | String query = "UPDATE utente SET nome = ?, cognome = ? WHERE id = ?;"; 30 | 31 | try (ConnectionHandler ch = ConnectionHandler.getInstance(); 32 | PreparedStatement ps = ch.getPreparedStatement(query)) 33 | { 34 | ps.setString(1, user.getName()); 35 | ps.setString(2, user.getLastName()); 36 | ps.setInt(3, user.getId()); 37 | int updatedCount = ps.executeUpdate(); 38 | return updatedCount > 0; 39 | } 40 | } 41 | 42 | @Override 43 | public boolean delete(int id) throws SQLException { 44 | String query = "DELETE FROM utente WHERE id = ?;"; 45 | 46 | try (ConnectionHandler ch = ConnectionHandler.getInstance(); 47 | PreparedStatement ps = ch.getPreparedStatement(query)) 48 | { 49 | ps.setInt(1, id); 50 | int deletedCount = ps.executeUpdate(); 51 | return deletedCount > 0; 52 | } 53 | } 54 | 55 | @Override 56 | public Optional get(int id) throws SQLException { 57 | Optional user = Optional.empty(); 58 | 59 | String query = "SELECT * FROM utente WHERE id = ?;"; 60 | 61 | try (ConnectionHandler ch = ConnectionHandler.getInstance(); 62 | PreparedStatement ps = ch.getPreparedStatement(query)) 63 | { 64 | ps.setInt(1, id); 65 | ResultSet rs = ps.executeQuery(); 66 | if (rs.next()) user = Optional.of(User.fromResultSet(rs)); 67 | } 68 | 69 | return user; 70 | } 71 | 72 | @Override 73 | public List getByLastName(String lastName) throws SQLException { 74 | List users = new ArrayList<>(); 75 | 76 | String query = "SELECT * FROM utente WHERE cognome = ?;"; 77 | 78 | try (ConnectionHandler ch = ConnectionHandler.getInstance(); 79 | PreparedStatement ps = ch.getPreparedStatement(query)) 80 | { 81 | ps.setString(1, lastName); 82 | ResultSet rs = ps.executeQuery(); 83 | while (rs.next()) users.add(User.fromResultSet(rs)); 84 | } 85 | 86 | return users; 87 | } 88 | 89 | @Override 90 | public List getAll() throws SQLException { 91 | List users = new ArrayList<>(); 92 | 93 | String query = "SELECT * FROM utente;"; 94 | 95 | try (ConnectionHandler ch = ConnectionHandler.getInstance(); 96 | PreparedStatement ps = ch.getPreparedStatement(query); 97 | ResultSet rs = ps.executeQuery()) 98 | { 99 | while (rs.next()) users.add(User.fromResultSet(rs)); 100 | } 101 | 102 | return users; 103 | } 104 | 105 | public static void main(String[] args) throws SQLException { 106 | UserDao userDao = new UserDaoSql(); 107 | 108 | System.out.println(userDao.get(1)); 109 | 110 | System.out.println(userDao.getAll()); 111 | 112 | userDao.insert(new User("Luigi", "Mario")); 113 | 114 | System.out.println(userDao.getAll()); 115 | 116 | userDao.update(new User(4, "Mario", "Mario")); 117 | 118 | System.out.println(userDao.get(4)); 119 | 120 | userDao.delete(4); 121 | 122 | System.out.println(userDao.get(4)); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /module_12/src/esempi/connectionhandler/config.properties: -------------------------------------------------------------------------------- 1 | host=localhost 2 | port=5432 3 | name=AndiamoATeatro 4 | user=postgres 5 | password=postgres -------------------------------------------------------------------------------- /module_12/src/esempi/connectionhandler/config.properties.example: -------------------------------------------------------------------------------- 1 | host=localhost 2 | port=5432 3 | name=AndiamoATeatro 4 | user=postgres 5 | password=postgres -------------------------------------------------------------------------------- /module_13/Live Coding/demo_rest_api/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backend-Developer-School-Tree/Corso-Java-Developer-2023-01/e5a6bac830c295ceb9e79e9e3641064ffc3dbb38/module_13/Live Coding/demo_rest_api/.DS_Store -------------------------------------------------------------------------------- /module_13/Live Coding/demo_rest_api/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | org.example 5 | demo_rest_api 6 | jar 7 | 1.0-SNAPSHOT 8 | 9 | 1.8 10 | 1.8 11 | 12 | demo_rest_api 13 | http://maven.apache.org 14 | 15 | 16 | 17 | com.google.code.gson 18 | gson 19 | 2.10 20 | 21 | 22 | 23 | com.sparkjava 24 | spark-core 25 | 2.9.3 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /module_13/Live Coding/demo_rest_api/src/main/java/org/example/App.java: -------------------------------------------------------------------------------- 1 | package org.example; 2 | 3 | import com.google.gson.Gson; 4 | import org.example.model.ErrorResponse; 5 | import org.example.model.User; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | import static spark.Spark.*; 11 | 12 | public class App { 13 | 14 | private static Map users = new HashMap<>(); //Simulo un DB con una mappa 15 | 16 | public static void main( String[] args ) { 17 | 18 | //Mi creo dei dati di test all'avvio del programma 19 | User u1 = new User( 1, "username1", "myEmail1@gmail.com"); 20 | User u2 = new User( 2, "username2", "myEmail2@gmail.com"); 21 | User u3 = new User( 3, "username3", "myEmail3@gmail.com"); 22 | users.put(1, u1); 23 | users.put(2, u2); 24 | users.put(3, u3); 25 | 26 | // Porta su cui deve girare il processo, è opzionale nel caso prende la default 27 | port(8080); 28 | 29 | /* 30 | * Metodo get esposto verso l'esterno che si invoca 31 | * su endpoint /helloworld 32 | * 33 | * path --> è un prefisso per gli endpoint, tutto quello che viene dopo 34 | * inizia con quel percorso 35 | * 36 | * es: http://localhost:8080/api/test/helloworld 37 | * */ 38 | path( "/api/v1/test", () ->{ 39 | get("/helloworld", (req, res)->{ 40 | return "Hello World nidificato!"; 41 | }); 42 | }); 43 | // Senza nidificazione 44 | get("/helloworld", (req, res)->{ 45 | return "Hello World!"; 46 | }); 47 | 48 | 49 | /* 50 | * Servizio web che torna un utente dummy 51 | * */ 52 | get("/user", (req, res)->{ 53 | //mi aspetto nel sevizio una proprietà "id" dopo il ? 54 | int userId = Integer.valueOf(req.queryParams("id")); 55 | 56 | //Il secondo avrà & 57 | String username = req.queryParams("username"); 58 | 59 | // Cerco nel Database utente con id e/o username che prendo da params 60 | User userResponse = users.get(userId); 61 | 62 | //Simulo che non ho trovato nessun utente nel database con un parametro 0 63 | if(userResponse==null){ 64 | res.status(404); 65 | return new Gson().toJson(new ErrorResponse("User not found", "404")); 66 | } 67 | 68 | //TODO: implementare ricerca per username 69 | 70 | res.type("application/json"); //il tipo di ritorno è json 71 | return new Gson().toJson(userResponse); 72 | }); 73 | 74 | //Get all users 75 | get("/users", (req, res)->{ 76 | res.type("application/json"); 77 | return new Gson().toJsonTree(users.values()); 78 | }); 79 | 80 | //Delete di un record 81 | delete("/user", (req, res)->{ 82 | //mi aspetto nel sevizio una proprietà "id" dopo il ? 83 | int userId = Integer.valueOf(req.queryParams("id")); 84 | 85 | users.remove(userId); //rimuovo dalla mappa 86 | 87 | res.type("application/json"); 88 | return new Gson().toJson("Utente cancellato"); 89 | }); 90 | 91 | post("/user", (req, res)->{ 92 | 93 | /** 94 | * req.body --> prendo i dati dal body della richiesta http 95 | * User.class --> classe per il mapping 96 | */ 97 | User newUser = new Gson().fromJson(req.body(), User.class); 98 | newUser.setId(100); //TODO: rendere randomico 99 | 100 | users.put(newUser.getId(), newUser); 101 | 102 | res.type("application/json"); 103 | return new Gson().toJson(newUser); 104 | }); 105 | 106 | put("/user", (req, res)->{ 107 | 108 | User user2update = new Gson().fromJson(req.body(), User.class); 109 | 110 | users.put(user2update.getId(), user2update); 111 | 112 | res.type("application/json"); 113 | return new Gson().toJson(user2update); 114 | }); 115 | 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /module_13/Live Coding/demo_rest_api/src/main/java/org/example/model/ErrorResponse.java: -------------------------------------------------------------------------------- 1 | package org.example.model; 2 | 3 | public class ErrorResponse { 4 | private String message; 5 | private String code; 6 | 7 | public ErrorResponse(String message, String code) { 8 | this.message = message; 9 | this.code = code; 10 | } 11 | 12 | public String getMessage() { 13 | return message; 14 | } 15 | 16 | public void setMessage(String message) { 17 | this.message = message; 18 | } 19 | 20 | public String getCode() { 21 | return code; 22 | } 23 | 24 | public void setCode(String code) { 25 | this.code = code; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /module_13/Live Coding/demo_rest_api/src/main/java/org/example/model/User.java: -------------------------------------------------------------------------------- 1 | package org.example.model; 2 | 3 | public class User { 4 | 5 | private int id; 6 | private String username; 7 | private String email; 8 | 9 | public User(){} 10 | 11 | public User(int id, String username, String email) { 12 | this.id = id; 13 | this.username = username; 14 | this.email = email; 15 | } 16 | 17 | public int getId() { 18 | return id; 19 | } 20 | 21 | public void setId(int id) { 22 | this.id = id; 23 | } 24 | 25 | public String getUsername() { 26 | return username; 27 | } 28 | 29 | public void setUsername(String username) { 30 | this.username = username; 31 | } 32 | 33 | public String getEmail() { 34 | return email; 35 | } 36 | 37 | public void setEmail(String email) { 38 | this.email = email; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /module_13/Live Coding/demo_rest_api/src/test/java/org/example/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.example; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /module_13/simple-ecommerce/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.myecommerce 5 | simple-ecommerce 6 | jar 7 | 1.0 8 | 9 | 1.8 10 | 1.8 11 | 12 | 13 | 14 | 15 | org.apache.maven.plugins 16 | maven-compiler-plugin 17 | 18 | 11 19 | 11 20 | 21 | 22 | 23 | 24 | simple-ecommerce 25 | http://maven.apache.org 26 | 27 | 28 | junit 29 | junit 30 | 3.8.1 31 | test 32 | 33 | 34 | 35 | com.google.code.gson 36 | gson 37 | 2.10 38 | 39 | 40 | 41 | com.sparkjava 42 | spark-core 43 | 2.9.3 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /module_13/simple-ecommerce/src/main/java/com/myecommerce/App.java: -------------------------------------------------------------------------------- 1 | package com.myecommerce; 2 | 3 | import com.google.gson.Gson; 4 | import com.myecommerce.model.Product; 5 | 6 | import java.util.HashSet; 7 | import java.util.Optional; 8 | import java.util.Set; 9 | 10 | import static spark.Spark.*; 11 | 12 | /* 13 | * TODO: 14 | * 1. Implementare ricerca prodotto per ID e per name 15 | * 2. Aggiungere persistenza (DB) 16 | * 3. Bonus: modificare il codice per aggiungere JUnit (es creare classe DummyDB dove 17 | * gestire i prodotti e testare quella classe) 18 | * */ 19 | public class App { 20 | 21 | private static Set products = new HashSet<>(); 22 | 23 | private static Gson gson = new Gson(); 24 | 25 | public static void main(String[] args) { 26 | 27 | /*DATI DI TEST PRE-CARICATI*/ 28 | Product p1 = new Product(1L, 100, 9.99, "P1", "Product P1"); 29 | products.add(p1); 30 | 31 | port(8080); //opzionale, indica su quale porta è in ascolto il mio processo 32 | 33 | path("/ecommerce", () -> { 34 | path("/product", () -> { 35 | post("/add", (req, res) -> { 36 | Product newProduct = gson.fromJson(req.body(), Product.class); 37 | 38 | /* Dall'esterno mi arriva un prodotto già presente -> Errore */ 39 | if (products.contains(newProduct)) { 40 | res.status(400); 41 | return "product already present"; 42 | } 43 | 44 | products.add(newProduct); 45 | res.status(201); 46 | return "ok"; 47 | }); 48 | 49 | post("/buy", (req, res) -> { 50 | String productID = req.queryParams("id"); 51 | String quantity =req.queryParams("quantity"); //String perché se null mi potrebbe dare problemi 52 | 53 | if(productID == null || quantity == null || productID.equals("") || quantity.equals("")){ 54 | res.status(400); 55 | return "Malformed request"; 56 | } 57 | 58 | // Ho convertito la stringa che arriva dall'esterno nel mio tipo numerico 59 | long productIDConverted = Long.valueOf(productID); 60 | int quantityConverted = Integer.valueOf(quantity); 61 | 62 | Optional productOptional = products.stream() 63 | .filter(prod -> prod.getId() == productIDConverted) 64 | .findFirst(); 65 | 66 | // ID valido ma non esistente 67 | if(productOptional.isEmpty()){ 68 | res.status(404); 69 | return "Product not found"; 70 | } 71 | 72 | // Controllo se quantità sufficiente 73 | Product product = productOptional.get(); 74 | if(product.getStockAvailability() { 87 | long productID = Long.valueOf(req.queryParams("id")); 88 | 89 | // Controllo di esistenza del prodotto non necessario (se non esiste è già come lo volevamo) 90 | products.removeIf( p -> p.getId() == productID ); 91 | 92 | res.status(200); 93 | return "ok"; 94 | }); 95 | } 96 | 97 | ); 98 | 99 | path("/products", () -> { 100 | get("/available", (req, res) -> { 101 | res.type("application/json"); 102 | res.status(200); 103 | 104 | return gson.toJson(products); 105 | }); 106 | }); 107 | }); 108 | } 109 | } -------------------------------------------------------------------------------- /module_13/simple-ecommerce/src/main/java/com/myecommerce/model/Product.java: -------------------------------------------------------------------------------- 1 | package com.myecommerce.model; 2 | 3 | import java.util.Objects; 4 | 5 | public class Product { 6 | 7 | private long id; 8 | private int stockAvailability; 9 | private double price; 10 | private String name; 11 | private String description; 12 | 13 | public Product(){} 14 | 15 | public Product(long id, int stockAvailability, double price, String name, String description) { 16 | this.id = id; 17 | this.stockAvailability = stockAvailability; 18 | this.price = price; 19 | this.name = name; 20 | this.description = description; 21 | } 22 | 23 | public long getId() { 24 | return id; 25 | } 26 | 27 | public void setId(long id) { 28 | this.id = id; 29 | } 30 | 31 | public int getStockAvailability() { 32 | return stockAvailability; 33 | } 34 | 35 | public void setStockAvailability(int stockAvailability) { 36 | this.stockAvailability = stockAvailability; 37 | } 38 | 39 | public double getPrice() { 40 | return price; 41 | } 42 | 43 | public void setPrice(double price) { 44 | this.price = price; 45 | } 46 | 47 | public String getName() { 48 | return name; 49 | } 50 | 51 | public void setName(String name) { 52 | this.name = name; 53 | } 54 | 55 | public String getDescription() { 56 | return description; 57 | } 58 | 59 | public void setDescription(String description) { 60 | this.description = description; 61 | } 62 | 63 | @Override 64 | public boolean equals(Object o){ 65 | if(this == o) //se oggetto è se stesso allora è true 66 | return true; 67 | if(o == null || getClass() != o.getClass()) // getClass() equivale a this.getClass() 68 | return false; 69 | 70 | Product product = (Product) o; // Cast da Object a Product per poter usare il getId() 71 | return (id == product.getId()); 72 | } 73 | 74 | @Override 75 | public String toString(){ 76 | return "Product: " + name + " - " + description; 77 | } 78 | 79 | @Override 80 | public int hashCode(){ 81 | return Objects.hash(id); 82 | } 83 | 84 | public void decreaseStock(int quantity){ 85 | stockAvailability -= quantity; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /module_13/simple-ecommerce/src/test/java/com/myecommerce/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.myecommerce; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /module_13/tree_express/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | org.treeexpress 5 | tree_express 6 | jar 7 | 1.0 8 | 9 | 10 | 11 | org.apache.maven.plugins 12 | maven-compiler-plugin 13 | 14 | 8 15 | 8 16 | 17 | 18 | 19 | 20 | tree_express 21 | http://maven.apache.org 22 | 23 | 24 | org.junit.jupiter 25 | junit-jupiter-api 26 | 5.9.1 27 | test 28 | 29 | 30 | 31 | com.google.code.gson 32 | gson 33 | 2.10 34 | 35 | 36 | 37 | com.sparkjava 38 | spark-core 39 | 2.9.3 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /module_13/tree_express/src/main/java/org/treeexpress/App.java: -------------------------------------------------------------------------------- 1 | package org.treeexpress; 2 | 3 | import com.google.gson.Gson; 4 | import org.treeexpress.model.Delivery; 5 | import org.treeexpress.model.DeliveryType; 6 | import org.treeexpress.model.TreeExpressUser; 7 | 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | import java.util.List; 12 | 13 | 14 | import static spark.Spark.*; 15 | 16 | public class App { 17 | 18 | private static Gson gson = new Gson(); 19 | 20 | static Map treeExpressUsers = new HashMap<>(); 21 | static List deliveries = new ArrayList<>(); 22 | 23 | public static void main( String[] args ) { 24 | port(8081); //8081 perché 8080 era già occupata :) 25 | 26 | path("/express", () -> { 27 | path("/treeexpressuser", () ->{ 28 | post("/add", (req, res) -> { 29 | 30 | //TODO: implementare controllo su ID 31 | TreeExpressUser newExpressUser = gson.fromJson(req.body(),TreeExpressUser.class); 32 | 33 | treeExpressUsers.put(newExpressUser.getId(), newExpressUser); 34 | 35 | res.status(201); //201 --> creato 36 | return "ok"; 37 | }); 38 | 39 | get("/all", (req, res) -> { 40 | 41 | res.status(200); 42 | return gson.toJson(treeExpressUsers); 43 | }); 44 | }); 45 | 46 | 47 | path("/delivery", () ->{ 48 | post("/create", (req, res) -> { 49 | 50 | String senderId = req.queryParams("senderID"); 51 | String receiverId = req.queryParams("receiverID"); 52 | 53 | if(senderId == null || receiverId == null || senderId.equals("") || receiverId.equals("")){ 54 | res.status(400); 55 | return "Sender or Receiver id not valid"; 56 | } 57 | 58 | // Sto recuperando gli utenti dalla hashmap che ha Long come chiave, devo convertire 59 | TreeExpressUser userSender = treeExpressUsers.get( Long.valueOf(senderId) ); 60 | TreeExpressUser userReceiver = treeExpressUsers.get( Long.valueOf(receiverId) ); 61 | 62 | String weightString = req.queryParams("weight"); 63 | if(weightString == null || weightString.equals("")){ 64 | res.status(400); 65 | return "weightString not present"; 66 | } 67 | double weight = Double.parseDouble(weightString); 68 | 69 | //TODO: generare ID intero randomico 70 | Delivery newDelivery = new Delivery(1L,weight, DeliveryType.SHIPPING,userSender, userReceiver ); 71 | deliveries.add(newDelivery); 72 | 73 | res.status(201); //201 --> Created 74 | return "ok"; 75 | }); 76 | 77 | get("/all", (req, res) -> { 78 | 79 | res.status(200); 80 | return gson.toJson(deliveries); 81 | }); 82 | }); 83 | }); 84 | 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /module_13/tree_express/src/main/java/org/treeexpress/model/Delivery.java: -------------------------------------------------------------------------------- 1 | package org.treeexpress.model; 2 | 3 | import java.util.Objects; 4 | 5 | public class Delivery { 6 | 7 | private long id; 8 | private double weight; 9 | private DeliveryType deliveryType; 10 | private TreeExpressUser sender, receiver; 11 | 12 | public Delivery(){} 13 | 14 | public Delivery(long id, double weight, DeliveryType deliveryType, TreeExpressUser sender, TreeExpressUser receiver) { 15 | this.id = id; 16 | this.weight = weight; 17 | this.deliveryType = deliveryType; 18 | this.sender = sender; 19 | this.receiver = receiver; 20 | } 21 | 22 | public long getId() { 23 | return id; 24 | } 25 | 26 | public void setId(long id) { 27 | this.id = id; 28 | } 29 | 30 | public double getWeight() { 31 | return weight; 32 | } 33 | 34 | public void setWeight(double weight) { 35 | this.weight = weight; 36 | } 37 | 38 | public DeliveryType getDeliveryType() { 39 | return deliveryType; 40 | } 41 | 42 | public void setDeliveryType(DeliveryType deliveryType) { 43 | this.deliveryType = deliveryType; 44 | } 45 | 46 | public TreeExpressUser getSender() { 47 | return sender; 48 | } 49 | 50 | public void setSender(TreeExpressUser sender) { 51 | this.sender = sender; 52 | } 53 | 54 | public TreeExpressUser getReceiver() { 55 | return receiver; 56 | } 57 | 58 | public void setReceiver(TreeExpressUser receiver) { 59 | this.receiver = receiver; 60 | } 61 | 62 | @Override 63 | public boolean equals(Object o) { 64 | if (this == o) 65 | return true; 66 | 67 | if (o == null || getClass() != o.getClass()) 68 | return false; 69 | 70 | Delivery delivery = (Delivery) o; 71 | return id == delivery.id; 72 | } 73 | 74 | @Override 75 | public int hashCode() { 76 | return Objects.hash(id); 77 | } 78 | 79 | @Override 80 | public String toString() { 81 | return "Delivery{" + 82 | "id=" + id + 83 | ", weight=" + weight + 84 | ", deliveryType=" + deliveryType + 85 | ", sender=" + sender + 86 | ", receiver=" + receiver + 87 | '}'; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /module_13/tree_express/src/main/java/org/treeexpress/model/DeliveryType.java: -------------------------------------------------------------------------------- 1 | package org.treeexpress.model; 2 | 3 | public enum DeliveryType { 4 | SHIPPING, SHIPPED 5 | } 6 | -------------------------------------------------------------------------------- /module_13/tree_express/src/main/java/org/treeexpress/model/TreeExpressUser.java: -------------------------------------------------------------------------------- 1 | package org.treeexpress.model; 2 | 3 | import java.util.Objects; 4 | 5 | public class TreeExpressUser { 6 | 7 | private long id; 8 | private String name, lastName, address; 9 | 10 | public TreeExpressUser(){} 11 | 12 | public TreeExpressUser(long id, String name, String lastName, String address) { 13 | this.id = id; 14 | this.name = name; 15 | this.lastName = lastName; 16 | this.address = address; 17 | } 18 | 19 | public long getId() { 20 | return id; 21 | } 22 | 23 | public void setId(long id) { 24 | this.id = id; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public String getLastName() { 36 | return lastName; 37 | } 38 | 39 | public void setLastName(String lastName) { 40 | this.lastName = lastName; 41 | } 42 | 43 | public String getAddress() { 44 | return address; 45 | } 46 | 47 | public void setAddress(String address) { 48 | this.address = address; 49 | } 50 | 51 | @Override 52 | public boolean equals(Object o) { 53 | if (this == o) 54 | return true; 55 | 56 | if (o == null || getClass() != o.getClass()) 57 | return false; 58 | 59 | TreeExpressUser treeExpressUser = (TreeExpressUser) o; 60 | return id == treeExpressUser.id; 61 | } 62 | 63 | @Override 64 | public int hashCode() { 65 | return Objects.hash(id); 66 | } 67 | 68 | @Override 69 | public String toString() { 70 | return "TreeExpressUser{" + 71 | "id=" + id + 72 | ", name='" + name + '\'' + 73 | ", lastName='" + lastName + '\'' + 74 | ", address='" + address + '\'' + 75 | '}'; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /module_13/tree_express/src/test/java/org/treeexpress/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.treeexpress; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /module_14/demo-junit/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.demo.junit 8 | demo-junit 9 | 1.0 10 | 11 | demo-junit 12 | 13 | http://www.example.com 14 | 15 | 16 | UTF-8 17 | 1.8 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.junit.jupiter 24 | junit-jupiter-api 25 | 5.9.1 26 | test 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | maven-clean-plugin 36 | 3.1.0 37 | 38 | 39 | 40 | maven-resources-plugin 41 | 3.0.2 42 | 43 | 44 | maven-compiler-plugin 45 | 3.8.0 46 | 47 | 48 | maven-surefire-plugin 49 | 2.22.1 50 | 51 | 52 | maven-jar-plugin 53 | 3.0.2 54 | 55 | 56 | maven-install-plugin 57 | 2.5.2 58 | 59 | 60 | maven-deploy-plugin 61 | 2.8.2 62 | 63 | 64 | 65 | maven-site-plugin 66 | 3.7.1 67 | 68 | 69 | maven-project-info-reports-plugin 70 | 3.0.0 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /module_14/demo-junit/src/main/java/com/demo/junit/App.java: -------------------------------------------------------------------------------- 1 | package com.demo.junit; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /module_14/demo-junit/src/test/java/com/demo/junit/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.demo.junit; 2 | 3 | import org.junit.jupiter.api.BeforeAll; 4 | import org.junit.jupiter.api.BeforeEach; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertNotNull; 11 | import static org.junit.jupiter.api.Assertions.assertEquals; 12 | import static org.junit.jupiter.api.Assertions.assertTrue; 13 | 14 | public class AppTest { 15 | List myStringList; 16 | 17 | @BeforeAll 18 | static void beforeAllMethods(){ 19 | 20 | System.out.println("Before all methods"); 21 | } 22 | 23 | @BeforeEach 24 | void setUpBeforeEach(){ 25 | System.out.println("Hello World"); 26 | 27 | String s = "new"; 28 | s.length(); 29 | myStringList = new ArrayList<>(); 30 | 31 | myStringList.add("My value 1"); 32 | myStringList.add("My value 2"); 33 | myStringList.add("My value 3"); 34 | 35 | } 36 | 37 | @Test 38 | void notNullListTest(){ 39 | assertNotNull(myStringList); 40 | } 41 | 42 | @Test 43 | void sizeListTest(){ 44 | assertEquals(myStringList.size(), 3); 45 | } 46 | 47 | @Test 48 | void addElement2ListTest(){ 49 | myStringList.add("Value 4"); 50 | 51 | assertTrue(myStringList.size() == 4); 52 | } 53 | } 54 | --------------------------------------------------------------------------------