├── README.md
├── cap01
├── Ejemplo01_01.java
├── Ejemplo01_01a.java
├── Ejemplo01_01b.java
├── Ejemplo01_01c.java
├── Ejercicio01_01.java
└── Ejercicio01_02.java
├── cap02
├── Ejemplo02_01.java
├── Ejemplo02_02.java
├── Ejemplo02_03.java
├── Ejemplo02_03Mal.java
├── Ejemplo02_04.java
├── Ejemplo02_05.java
├── Ejemplo02_06.java
├── Ejemplo02_07.java
├── Ejercicio02_01.java
├── Ejercicio02_02.java
├── Ejercicio02_03.java
├── Ejercicio02_04.java
├── Ejercicio02_05.java
├── Ejercicio02_06.java
├── Ejercicio02_07.java
├── Test02_04.java
└── Test02_05.java
├── cap03
├── Ejemplo03_01.java
├── Ejemplo03_02.java
├── Ejemplo03_02Mal.java
├── Ejemplo03_03.java
├── Ejercicio03_01.java
├── Ejercicio03_02.java
├── Ejercicio03_03.java
├── Ejercicio03_04.java
├── Ejercicio03_05.java
├── Ejercicio03_05Sol.java
└── Ejercicio03_06.java
├── cap04
├── Ejemplo04_01.java
├── Ejemplo04_02.java
├── Ejemplo04_03.java
├── Ejemplo04_04.java
├── Ejemplo04_05a.java
├── Ejemplo04_05b.java
├── Ejemplo04_06.java
├── Ejemplo04_07.java
├── Ejemplo04_08.java
├── Ejercicio04_01.java
├── Ejercicio04_02.java
├── Ejercicio04_02ForEach.java
├── Ejercicio04_03.java
├── Ejercicio04_04.java
├── Ejercicio04_04Sol.java
├── Ejercicio04_05.java
├── Ejercicio04_06.java
└── Ejercicio04_07.java
├── cap05
└── PiedraPapelTijeras.java
├── cap06
└── SinEjemplos.txt
├── cap07
├── .classpath
├── .gitignore
├── .project
└── src
│ └── sooper
│ ├── IContenedor.java
│ ├── IPedido.java
│ ├── IProducto.java
│ ├── Pedido.java
│ ├── Supermercado.java
│ ├── contenedores
│ ├── Bolsa.java
│ ├── Caja.java
│ └── Contenedor.java
│ └── enums
│ ├── Categoria.java
│ └── TipoContenedor.java
├── cap08
├── .classpath
├── .gitignore
├── .project
├── Estatica.java
└── src
│ └── sooper
│ ├── IContenedor.java
│ ├── IPedido.java
│ ├── IProducto.java
│ ├── Pedido.java
│ ├── Supermercado.java
│ ├── contenedores
│ ├── Bolsa.java
│ ├── Caja.java
│ └── Contenedor.java
│ ├── enums
│ ├── Categoria.java
│ └── TipoContenedor.java
│ └── productos
│ ├── Alimentacion.java
│ ├── Congelado.java
│ ├── Drogueria.java
│ ├── Fresco.java
│ ├── Higiene.java
│ ├── Mascotas.java
│ ├── NoPerecedero.java
│ └── Producto.java
├── cap09
└── huerto
│ ├── Huerto.java
│ ├── IHuerto.java
│ ├── IMaceta.java
│ ├── IPlanta.java
│ ├── Sistema.java
│ ├── enums
│ ├── Especie.java
│ ├── Familia.java
│ └── FormaMaceta.java
│ ├── macetas
│ ├── Maceta.java
│ ├── MacetaRectangular.java
│ └── MacetaTubular.java
│ └── plantas
│ ├── Hinojo.java
│ ├── Lechuga.java
│ ├── Perejil.java
│ ├── Planta.java
│ ├── PlantaAromatica.java
│ ├── PlantaFruto.java
│ ├── PlantaHoja.java
│ ├── PlantaRaiz.java
│ ├── Tomate.java
│ ├── TomateCherry.java
│ └── Zanahoria.java
├── cap10
├── ejemplos
│ ├── BusinessException.java
│ ├── NoQuiero.java
│ ├── TechnicalException.java
│ └── TestExcepcional.java
└── ejercicios
│ ├── LanzadorMultiple.java
│ ├── LanzadorMultipleTest.java
│ ├── LanzadorNullPointer.java
│ ├── LanzadorNullPointerTest.java
│ ├── OrdenEjecucion.java
│ ├── OrdenEjecucionTest.java
│ ├── TodoControlado.java
│ └── TodoControladoTest.java
├── cap11
└── Tests11.java
├── cap12
├── Mockeando
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ │ ├── org.eclipse.core.resources.prefs
│ │ ├── org.eclipse.jdt.core.prefs
│ │ └── org.eclipse.m2e.core.prefs
│ ├── pom.xml
│ └── src
│ │ ├── main
│ │ └── java
│ │ │ └── cap12
│ │ │ └── mockeando
│ │ │ ├── SuperCalculadora.java
│ │ │ └── SuperCalculadoraImpl.java
│ │ └── test
│ │ └── java
│ │ └── cap12
│ │ └── mockeando
│ │ └── SuperCalculadoraTest.java
└── TestUnitarios
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ └── org.eclipse.jdt.core.prefs
│ ├── src
│ └── cap12
│ │ ├── Calculadora.java
│ │ └── ExcepcionPropia.java
│ └── test
│ └── cap12
│ └── CalculadoraTest.java
├── cap13
└── trazas
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ ├── org.eclipse.core.resources.prefs
│ ├── org.eclipse.jdt.core.prefs
│ └── org.eclipse.m2e.core.prefs
│ ├── pom.xml
│ └── src
│ └── main
│ ├── java
│ └── cap13
│ │ └── trazas
│ │ └── App.java
│ └── resources
│ └── log4j2.properties
├── cap14
└── recordsManager
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ ├── org.eclipse.core.resources.prefs
│ ├── org.eclipse.jdt.core.prefs
│ └── org.eclipse.m2e.core.prefs
│ ├── pom.xml
│ ├── puntuaciones.txt
│ └── src
│ ├── main
│ ├── java
│ │ └── cap14
│ │ │ └── recordsManager
│ │ │ ├── PlayerNameTooShortException.java
│ │ │ ├── RecordsManager.java
│ │ │ └── ScoreTooLowException.java
│ └── resources
│ │ └── log4j2.properties
│ └── test
│ └── java
│ └── cap14
│ └── recordsManager
│ └── RecordsManagerTest.java
├── cap15
└── Estructuras
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ └── org.eclipse.jdt.core.prefs
│ ├── resources
│ ├── ejercicio15_05.properties
│ ├── ejercicio15_05_zh_CN.properties
│ ├── ejercicio15_05_zh_TW.properties
│ ├── estructuras_en.properties
│ └── estructuras_es.properties
│ └── src
│ ├── Ejercicio15_01.java
│ ├── Ejercicio15_02.java
│ ├── Ejercicio15_03.java
│ ├── Ejercicio15_04.java
│ ├── Ejercicio15_05.java
│ ├── FechasNuevas.java
│ ├── FechasViejas.java
│ ├── Mensajes.java
│ ├── Monedas.java
│ └── Numeros.java
├── cap16
└── gestor
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ ├── org.eclipse.core.resources.prefs
│ ├── org.eclipse.jdt.core.prefs
│ ├── org.eclipse.m2e.core.prefs
│ └── org.sonarlint.eclipse.core.prefs
│ ├── pom.xml
│ └── src
│ ├── main
│ └── java
│ │ ├── META-INF
│ │ └── persistence.xml
│ │ └── cap16
│ │ └── orm
│ │ └── gestor
│ │ ├── Albaran.java
│ │ ├── App.java
│ │ ├── Factura.java
│ │ ├── GestorPedidos.java
│ │ ├── Pedido.java
│ │ ├── Producto.java
│ │ ├── SinQueries.java
│ │ ├── dao
│ │ ├── AbstractDao.java
│ │ ├── AlbaranDao.java
│ │ ├── Dao.java
│ │ ├── FacturaDao.java
│ │ ├── PedidoDao.java
│ │ └── ProductoDao.java
│ │ └── utiles
│ │ └── EntityManagerUtil.java
│ └── test
│ └── java
│ └── cap16
│ └── orm
│ └── gestor
│ └── AppTest.java
├── cap17
└── lambdas
│ ├── Calculadora.java
│ ├── CuentasVarias.java
│ ├── FiltrandoTextos.java
│ └── FiltrandoTextosStreams.java
└── cap18
└── otrareunionmas
├── .classpath
├── .project
├── .settings
├── org.eclipse.core.resources.prefs
├── org.eclipse.jdt.core.prefs
└── org.eclipse.m2e.core.prefs
├── pom.xml
└── src
├── main
└── java
│ ├── META-INF
│ └── persistence.xml
│ └── cap18
│ └── otrareunionmas
│ ├── CartelSala.java
│ ├── GeneracionDatos.java
│ ├── InformeReunion.java
│ ├── InformeReuniones.java
│ ├── dao
│ ├── AbstractDao.java
│ ├── ActaDao.java
│ ├── Dao.java
│ ├── PersonaDao.java
│ ├── ReunionDao.java
│ └── SalaDao.java
│ ├── dominio
│ ├── Acta.java
│ ├── Persona.java
│ ├── Reunion.java
│ └── Sala.java
│ └── utiles
│ └── EntityManagerUtil.java
└── test
└── java
└── cap18
└── otrareunionmas
└── AppTest.java
/README.md:
--------------------------------------------------------------------------------
1 | Curso de programación Java
2 | ==========================
3 |
4 | Repositorio de ejemplos y ejercicios
5 | ------------------------------------
6 |
7 | Este repositorio acompaña al libro [Manual Imprescindible Curso de programación Java](https://school.dsrroma.es/libro/) de [Anaya Multimedia](https://www.anayamultimedia.es/libro.php?id=6085791) escrito por [Mariona Nadal](https://www.linkedin.com/in/marionanadal/).
8 |
9 |
10 |
11 | * ISBN (Papel): 978-84-415-4324-9
12 | * ISBN (Digital): 978-84-415-4425-3
13 |
14 | El libro contiene múltiples ejemplos y ejercicios, que te puedes descargar para practicar con ellos. Están disponibles en este repositorio público.
15 |
16 | Puedes descargarte todo en un fichero zip, pero te recomiendo aprender las [operaciones básicas](https://docs.github.com/es/github/getting-started-with-github/fork-a-repo) de git para poder sacarle el máximo provecho, pues algunos de los ficheros pueden tener varias versiones, en función de cómo vamos trabajando sobre ellos.
17 | En la historia de un fichero, coge la primera versión (normalmente la de más abajo) y trabaja sobre ella para lograr llegar a la de más arriba, que ya contiene la solución.
18 | Algunas nociones para empezar a utilizar el repositorio:
19 | * La interfaz de gitHub puede cambiar sin previo aviso, pero además de ver el código en la propia web, mediante el botón Code es posible clonarlo parar tener tu propia versión del repositorio o descargártelo como zip.
20 | * Viendo un fichero en la web, el botón History te permitirá conocer todos los commits hechos sobre ese fichero. Cuando cojas una versión en concreto, verás con el fondo neutro las líneas de código sin cambios respecto a las anteriores, con fondo rojo y un signo menos, las líneas que estaban antes y ya no están, y con fondo verde y un signo más, las nuevas. Si una línea ha sido modificada, aparecerá la versión antigua en rojo y la nueva en verde.
21 | * El título de cada commit te dará una pista de en qué sección del libro se modifica ese fragmento de código.
22 |
23 | Capítulos
24 | ---------
25 |
26 | 1. [Mi primer programa](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap01)
27 | 2. [Argumentos, variables, métodos y operadores](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap02)
28 | 3. [Estructuras condicionales](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap03)
29 | 4. [Estructuras iterativas](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap04)
30 | 5. [Proyecto «piedra, papel, tijeras»](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap05)
31 | 6. [Diseño orientado a objetos](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap06)
32 | 7. [Clases y objetos](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap07)
33 | 8. [Relaciones orientadas a objetos](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap08)
34 | 9. [Proyecto «macetohuerto»](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap09)
35 | 10. [Manejo de excepciones](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap10)
36 | 11. [Depuración](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap11)
37 | 12. [Test unitarios](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap12)
38 | 13. [Trazas de ejecución](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap13)
39 | 14. [Proyecto «Gestión de récords»](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap14)
40 | 15. [Estructuras de datos](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap15)
41 | 16. [Bases de datos: Mapeo Objeto-Relacional](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap16)
42 | 17. [Expresiones lambda y Streams](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap17)
43 | 18. [Proyecto «otra reunión más»](https://github.com/DSRschool/Anaya-MI-Java/tree/main/cap18)
44 |
45 | Garantía
46 | --------
47 |
48 | Los programas y aplicaciones presentados en este repositorio se han incluido por su valor educativo y no están garantizados para ningún propósito específico. Ni el editor ni el autor ofrecen garantías o prerrogativas ni aceptan responsabilidad alguna con respecto a los programas o aplicaciones.
49 |
50 | Licencia
51 | --------
52 |
53 | Copyright (c) 2021 [Mariona Nadal](https://school.dsrroma.es).
54 |
55 |
56 |
57 | Puedes utilizar libremente el material de este repositorio bajo la licencia
58 | Creative Commons
59 | Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).
60 |
--------------------------------------------------------------------------------
/cap01/Ejemplo01_01.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo01_01 {
2 | public static void main(String[] args) {
3 | System.out.println("Bienvenido al curso de programación Java");
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/cap01/Ejemplo01_01a.java:
--------------------------------------------------------------------------------
1 | // Ejemplo01_01a.java
2 | public class Ejemplo01_01a {
3 | public static void main(String[] args) {
4 |
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/cap01/Ejemplo01_01b.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo01_01b {
2 | public static void main(String[] args) {
3 |
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/cap01/Ejemplo01_01c.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo01_01c {
2 | public static void main(String[] args) {
3 |
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/cap01/Ejercicio01_01.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 1.1 - Escribe un programa que imprima por pantalla la frase
2 | * “Estoy aprendiendo a programar bien en Java”.
3 | */
4 |
5 | // La clase debe llamarse igual que el fichero
6 | public class Ejercicio01_01 {
7 |
8 | // el método main es el que se ejecuta al ejecutar una clase
9 | public static void main(String[] args) {
10 | // System.out.print o System.out.println escriben por la salida estándar
11 | // que es la consola
12 | System.out.println("Estoy aprendiendo a programar bien en Java");
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/cap01/Ejercicio01_02.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 1.2 - Escribe un programa que imprima por pantalla
2 | * estas dos frases: “La vida es tan buena maestra,” y
3 | * “que si no aprendes la lección te la repite.”.
4 | */
5 |
6 | public class Ejercicio01_02 {
7 |
8 | public static void main(String[] args) {
9 | System.out.println("La vida es tan buena maestra,");
10 | System.out.println("que si no aprendes la lección te la repite.");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/cap02/Ejemplo02_01.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_01 {
2 | public static void main(String[] args) {
3 | System.out.println("El último elemento que me has pasado es "
4 | + args[args.length-1]);
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/cap02/Ejemplo02_02.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_02 {
2 | public static void main(String[] args) {
3 | // Los argumentos que recibimos son Strings.
4 | // Tenemos que convertirlos a números para poder operar con ellos
5 | // Los guardamos en variables y les damos un nombre representativo
6 | int numManzanas = Integer.valueOf(args[0]);
7 | int numPeras = Integer.valueOf(args[1]);
8 | // TODO deberíamos comprobar que al menos tenemos dos argumentos
9 | // TODO deberíamos asegurarnos de que los argumentos son números enteros
10 |
11 | // Guardamos el resultado del cálculo en una variable
12 | int numFrutas = numManzanas + numPeras;
13 |
14 | // Tras hacer todos los cálculos necesarios, mostramos el resultado
15 | // Cuidado con los espacios al concatenar Strings, para que no se
16 | // peguen las palabras
17 | System.out.println("El frutero tiene " + numFrutas +
18 | " piezas de fruta.");
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/cap02/Ejemplo02_03.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_03 {
2 | public static void main(String[] args) {
3 | int numManzanas = Integer.valueOf(args[0]);
4 | int numPeras = Integer.valueOf(args[1]);
5 | int numCucharas = Integer.valueOf(args[2]);
6 | int numTenedores = Integer.valueOf(args[3]);
7 | int numNinos = Integer.valueOf(args[4]);
8 | int numAdultos = Integer.valueOf(args[5]);
9 |
10 | // Guardamos el resultado del cálculo en una variable
11 | int numFrutas = suma(numManzanas, numPeras);
12 | int numCubiertos = suma(numCucharas, numTenedores);
13 | int numPersonas = suma(numNinos, numAdultos);
14 |
15 | System.out.println("Tenemos " + numFrutas +
16 | " piezas de fruta, " + numCubiertos +
17 | " cubiertos y " + numPersonas + " personas.");
18 | }
19 |
20 | private static int suma(int a, int b) {
21 | return a + b;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/cap02/Ejemplo02_03Mal.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_03Mal {
2 | public static void main(String[] args) {
3 | int numManzanas = Integer.valueOf(args[0]);
4 | int numPeras = Integer.valueOf(args[1]);
5 | int numCucharas = Integer.valueOf(args[2]);
6 | int numTenedores = Integer.valueOf(args[3]);
7 | int numNinos = Integer.valueOf(args[4]);
8 | int numAdultos = Integer.valueOf(args[5]);
9 |
10 | // Guardamos el resultado del cálculo en una variable
11 | int numFrutas = numManzanas + numPeras;
12 | int numCubiertos = numCucharas + numTenedores;
13 | int numPersonas = numNinos + numAdultos;
14 |
15 | System.out.println("Tenemos " + numFrutas +
16 | " piezas de fruta, " + numCubiertos +
17 | " cubiertos y " + numPersonas + " personas.");
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/cap02/Ejemplo02_04.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_04 {
2 | public static void main(String[] args) {
3 | int divisionEntera = 7 / 2;
4 | int modulo = 7 % 2;
5 | double divisionReal = 7.0 / 2.0;
6 | System.out.println("División Entera 7/2: " + divisionEntera);
7 | System.out.println("Módulo 7%2: " + modulo);
8 | System.out.println("División Real 7.0/2.0: " + divisionReal);
9 | }
10 | }
--------------------------------------------------------------------------------
/cap02/Ejemplo02_05.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_05 {
2 | public static void main(String[] args) {
3 | int n = 7;
4 | System.out.println("1) n: " + n);
5 | System.out.println("2) ++n: " + ++n);
6 | System.out.println("3) n: " + n);
7 | System.out.println("4) n++: " + n++);
8 | System.out.println("5) n: " + n);
9 | }
10 | }
--------------------------------------------------------------------------------
/cap02/Ejemplo02_06.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_06 {
2 | public static void main(String[] args) {
3 | int x = 3;
4 | int y = 3;
5 | System.out.println("x: " + x);
6 | System.out.println("y: " + y);
7 | System.out.println("x == y? " + (x == y) );
8 | System.out.println("x != y? " + (x != y) );
9 | String a = new String("hola");
10 | String b = new String("hola");
11 | System.out.println("a: " + a);
12 | System.out.println("b: " + b);
13 | System.out.println("a == b? " + (a == b) );
14 | System.out.println("a != b? " + (a != b) );
15 | }
16 | }
--------------------------------------------------------------------------------
/cap02/Ejemplo02_07.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo02_07 {
2 | public static void main(String[] args) {
3 | System.out.println("1) AND: " + (siempreCierto() && siempreFalso()));
4 | System.out.println("2) AND: " + (siempreFalso() && siempreCierto()));
5 | System.out.println("3) OR: " + (siempreCierto() || siempreFalso()));
6 | System.out.println("4) OR: " + (siempreFalso() || siempreCierto()));
7 | }
8 |
9 | private static boolean siempreCierto() {
10 | System.out.println("siempreCierto");
11 | return true;
12 | }
13 |
14 | private static boolean siempreFalso() {
15 | System.out.println("siempreFalso");
16 | return false;
17 | }
18 | }
--------------------------------------------------------------------------------
/cap02/Ejercicio02_01.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 2.1 - Escribe un programa que imprima por pantalla el argumento
2 | * que ha recibido: “He recibido este argumento: …”.
3 | */
4 |
5 | public class Ejercicio02_01 {
6 | public static void main(String[] args) {
7 | // el operador + sirve para concatenar Strings
8 | System.out.println("He recibido este argumento: " + args[0]);
9 | // TODO deberíamos comprobar que al menos tenemos un argumento
10 | }
11 | }
--------------------------------------------------------------------------------
/cap02/Ejercicio02_02.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 2.2 - Escribe un programa que imprima por pantalla cuántos argumentos
2 | * ha recibido: "He recibido … argumentos."
3 | */
4 |
5 | public class Ejercicio02_02 {
6 | public static void main(String[] args) {
7 | // length es un atributo de los arrays que nos indica cuántos elementos tiene
8 | System.out.println("He recibido " + args.length + " argumentos.");
9 | }
10 | }
--------------------------------------------------------------------------------
/cap02/Ejercicio02_03.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 2.3 - Escribe un programa que calcule el área de un rectángulo
2 | * e imprima por pantalla el texto “El rectángulo de … por … tiene un área de …”.
3 | * Recibirá el tamaño de los dos lados como argumentos.
4 | */
5 |
6 | public class Ejercicio02_03 {
7 | public static void main(String[] args) {
8 | // Los argumentos que recibimos son Strings.
9 | // Tenemos que convertirlos a números para poder operar con ellos
10 | // Los guardamos en variables y les damos un nombre representativo
11 | int ladoX = Integer.valueOf(args[0]);
12 | int ladoY = Integer.valueOf(args[1]);
13 | // TODO deberíamos comprobar que al menos tenemos dos argumentos
14 | // TODO deberíamos asegurarnos de que los argumentos son números enteros
15 |
16 | // Guardamos el resultado del cálculo en una variable
17 | int area = ladoX * ladoY;
18 |
19 | // Tras hacer todos los cálculos necesarios, mostarmos el resultado
20 | // Cuidado con los espacios al concatenar Strings, para que no se
21 | // peguen las palabras
22 | System.out.println("El rectángulo de " + ladoX + " por " + ladoY +
23 | " tiene un área de " + area);
24 | }
25 | }
--------------------------------------------------------------------------------
/cap02/Ejercicio02_04.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 2.4 - Escribe un programa que calcule el área de un rectángulo
2 | * e imprima por pantalla el texto “El rectángulo de … por … tiene un área de …”.
3 | * Recibirá el tamaño de los dos lados como argumentos.
4 | */
5 |
6 | public class Ejercicio02_04 {
7 | public static void main(String[] args) {
8 | String apellido1 = args[0];
9 | String apellido2 = args[1];
10 | String hijo1 = args[2];
11 | String hijo2 = args[3];
12 | String hijo3 = args[4];
13 | String padre = args[5];
14 | String madre = args[6];
15 |
16 | String apellidosHijos = apellido1 + " " + apellido2;
17 |
18 | System.out.println("Padre: " + padre + " " + apellido1);
19 | System.out.println("Madre: " + madre + " " + apellido2);
20 | System.out.println("Hijos:");
21 | System.out.println(hijo1 + " " + apellidosHijos);
22 | System.out.println(hijo2 + " " + apellidosHijos);
23 | System.out.println(hijo3 + " " + apellidosHijos);
24 | }
25 | }
--------------------------------------------------------------------------------
/cap02/Ejercicio02_05.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 2.5 - Realiza el mismo ejercicio que en el 03a,
2 | * pero sacando el cálculo del área a un método:
3 | * Escribe un programa que calcule el área de un rectángulo
4 | * e imprima por pantalla el texto “El rectángulo de … por … tiene un área de …”.
5 | * Recibirá el tamaño de los dos lados como argumentos.
6 | */
7 |
8 | public class Ejercicio02_05 {
9 | public static void main(String[] args)
10 | {
11 | int ladoX = Integer.valueOf(args[0]);
12 | int ladoY = Integer.valueOf(args[1]);
13 |
14 | // Llamamos a un método para que calcule el área
15 | int area = areaRectangulo(ladoX, ladoY);
16 |
17 | System.out.println("El rectángulo de " + ladoX + " por " + ladoY +
18 | " tiene un área de " + area);
19 | }
20 |
21 | // Este método recibe dos parámetros, ambos enteros
22 | // Y devuelve un entero
23 | private static int areaRectangulo(int base, int altura) {
24 | return base * altura;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/cap02/Ejercicio02_06.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 2.6 - Escribe un programa que reciba estos 7 argumentos:
2 | * 0. Primer apellido
3 | * 1. Segundo apellido
4 | * 2. Nombre primer hijo
5 | * 3. Nombre segundo hijo
6 | * 4. Nombre tercer hijo
7 | * 5. Nombre del padre
8 | * 6. Nombre de la madre
9 | * Y saque los datos de toda la familia: una línea por cada miembro.
10 | * Crea un método pintarPersona que reciba como argumento 3 strings (el nombre y los dos apellidos)
11 | * y saque como salida: “Nombre: Apellidos: ”.
12 | * Usa la cadena vacía (“”) para los segundos apellidos desconocidos.
13 | * Usa el método para sacar los datos de todos los miembros de la familia, en el mismo orden de antes:
14 | */
15 |
16 | public class Ejercicio02_06 {
17 | public static void main(String[] args) {
18 | String apellido1 = args[0];
19 | String apellido2 = args[1];
20 | String hijo1 = args[2];
21 | String hijo2 = args[3];
22 | String hijo3 = args[4];
23 | String padre = args[5];
24 | String madre = args[6];
25 |
26 | String apellidosHijos = apellido1 + " " + apellido2;
27 |
28 | pintaPersona(padre, apellido1, "");
29 | pintaPersona(madre, apellido2, "");
30 | pintaPersona(hijo1, apellido1, apellido2);
31 | pintaPersona(hijo2, apellido1, apellido2);
32 | pintaPersona(hijo3, apellido1, apellido2);
33 | }
34 |
35 | protected static void pintaPersona(String nombre, String apellido1, String apellido2) {
36 | System.out.println("Nombre: " + nombre + " Apellidos: " + apellido1 + " " + apellido2);
37 | }
38 | }
--------------------------------------------------------------------------------
/cap02/Ejercicio02_07.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 2.7 - Escribe un programa que reciba estos 7 argumentos:
2 | * 0. Primer apellido
3 | * 1. Segundo apellido
4 | * 2. Nombre primer hijo
5 | * 3. Nombre segundo hijo
6 | * 4. Nombre tercer hijo
7 | * 5. Nombre del padre
8 | * 6. Nombre de la madre
9 | * Y saque los datos de toda la familia: una línea por cada miembro.
10 | *
11 | * Vamos a meter un tercer ejercicio en este tema, para mejorar lo que hemos hecho en el ejercicio 04b.
12 | *
13 | * Esta vez vamos a crear dos métodos: uno que construya el nombre de cada persona:
14 | * protected static String construyeNombreCompleto(String nombre, String apellido1, String apellido2)
15 | * que se encargue de la parte de concatenar los distintos elementos del nombre.
16 | *
17 | * Y otro que reciba el nombre completo y lo pinte por pantalla:
18 | * protected static void pintarNombreCompleto(String nombreCompleto)
19 | *
20 | * Usa los métodos para sacar los datos de todos los miembros de la familia, en el mismo orden de antes
21 | */
22 |
23 | public class Ejercicio02_07 {
24 | public static void main(String[] args) {
25 | String apellido1 = args[0];
26 | String apellido2 = args[1];
27 | String hijo1 = args[2];
28 | String hijo2 = args[3];
29 | String hijo3 = args[4];
30 | String padre = args[5];
31 | String madre = args[6];
32 |
33 | String apellidosHijos = apellido1 + " " + apellido2;
34 |
35 | pintarNombreCompleto(construyeNombreCompleto(padre, apellido1, ""));
36 | pintarNombreCompleto(construyeNombreCompleto(madre, apellido2, ""));
37 | pintarNombreCompleto(construyeNombreCompleto(hijo1, apellido1, apellido2));
38 | pintarNombreCompleto(construyeNombreCompleto(hijo2, apellido1, apellido2));
39 | pintarNombreCompleto(construyeNombreCompleto(hijo3, apellido1, apellido2));
40 | }
41 |
42 | protected static String construyeNombreCompleto(String nombre, String apellido1, String apellido2) {
43 | return "Nombre: " + nombre + " Apellidos: " + apellido1 + " " + apellido2;
44 | }
45 |
46 | protected static void pintarNombreCompleto(String nombreCompleto) {
47 | System.out.println(nombreCompleto);
48 | }
49 | }
--------------------------------------------------------------------------------
/cap02/Test02_04.java:
--------------------------------------------------------------------------------
1 | public class Test02_04 {
2 | public static void main(String[] args) {
3 | int a = 3;
4 | int b = 8;
5 | System.out.print("1)");
6 | test(b, a);
7 | System.out.print("2)");
8 | test(a, a);
9 | }
10 |
11 | private static void test(int a, int b) {
12 | System.out.println("A=" + a + " B=" + b);
13 | }
14 | }
--------------------------------------------------------------------------------
/cap02/Test02_05.java:
--------------------------------------------------------------------------------
1 | public class Test02_05 {
2 | public static void main(String[] args) {
3 | int uno = 1;
4 | int res = suma(uno, suma(uno + uno, suma(-uno, uno * uno)));
5 | System.out.println(res);
6 | }
7 |
8 | private static int suma(int a, int b) {
9 | return a + b;
10 | }
11 | }
--------------------------------------------------------------------------------
/cap03/Ejemplo03_01.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo03_01 {
2 | public static void main(String[] args) {
3 | int temp = Integer.valueOf(args[0]);
4 | System.out.print("La temperatura es de ");
5 | if (temp > 0) {
6 | System.out.println(temp + "ºC positivos.");
7 | } else {
8 | System.out.println(temp + "ºC bajo cero.");
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/cap03/Ejemplo03_02.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo03_02 {
2 | public static void main(String[] args) {
3 | int temp = Integer.valueOf(args[0]);
4 | if (haceFrio(temp)) {
5 | ponerCalefaccion();
6 | abrigarse();
7 | }
8 | }
9 |
10 | private static boolean haceFrio(int temp) {
11 | return temp <= 15;
12 | }
13 |
14 | private static void ponerCalefaccion() {
15 | System.out.println("Calefacción a tope!!");
16 | }
17 |
18 | private static void abrigarse() {
19 | System.out.println("¿Dónde está mi batamanta?");
20 | }
21 | }
--------------------------------------------------------------------------------
/cap03/Ejemplo03_02Mal.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo03_02Mal {
2 | public static void main(String[] args) {
3 | int temp = Integer.valueOf(args[0]);
4 | if (haceFrio(temp))
5 | ponerCalefaccion();
6 | abrigarse();
7 | }
8 |
9 | private static boolean haceFrio(int temp) {
10 | return temp <= 15;
11 | }
12 |
13 | private static void ponerCalefaccion() {
14 | System.out.println("Calefacción a tope!!");
15 | }
16 |
17 | private static void abrigarse() {
18 | System.out.println("¿Dónde está mi batamanta?");
19 | }
20 | }
--------------------------------------------------------------------------------
/cap03/Ejemplo03_03.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo03_03 {
2 | private static final int TEMP_FRIO = 15;
3 |
4 | public static void main(String[] args) {
5 | int temp = Integer.valueOf(args[0]);
6 | if (haceFrio(temp)) {
7 | ponerCalefaccion();
8 | abrigarse();
9 | }
10 | }
11 |
12 | private static boolean haceFrio(int temp) {
13 | return temp <= TEMP_FRIO;
14 | }
15 |
16 | private static void ponerCalefaccion() {
17 | System.out.println("Calefacción a tope!!");
18 | }
19 |
20 | private static void abrigarse() {
21 | System.out.println("¿Dónde está mi batamanta?");
22 | }
23 | }
--------------------------------------------------------------------------------
/cap03/Ejercicio03_01.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 3.1 – Comprueba el número de argumentos que recibe tu programa.
2 | * Si no recibe argumentos, avisa al usuario. En caso contrario, indícale cuántos
3 | * has recibido.
4 | */
5 |
6 | public class Ejercicio03_01 {
7 | public static void main(String[] args) {
8 | int numArgs = args.length;
9 | // en la rama if, pondremos una condición
10 | if (numArgs == 0) {
11 | // System.err.println sacará el mensaje por la salida de error
12 | // En este caso, por la consola, pero en rojo
13 | System.err.println("No se han recibido argumentos");
14 | } else { // la rama else se ejecutará en el resto de casos
15 | System.out.println("Se han recibido " + numArgs + " argumentos");
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/cap03/Ejercicio03_02.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 3.2 - Comprueba el número de argumentos que recibe tu programa.
2 | * Si no recibe argumentos, avisa al usuario. Si recibe hasta 4, indícale
3 | * cuántos has recibido. Si recibe más, avisa al usuario.
4 | */
5 |
6 | public class Ejercicio03_02 {
7 | public static void main(String[] args) {
8 | int numArgs = args.length;
9 | if (numArgs == 0) {
10 | // System.err.println sacará el mensaje por la salida de error
11 | // En este caso, por la consola, pero en rojo
12 | System.err.println("No se han recibido argumentos");
13 | } else if (numArgs <= 4) { // Si tenemos más de dos casos, podemos añadir
14 | // tantas ramas else if como necesitemos
15 | System.out.println("Se han recibido " + numArgs + " argumentos");
16 | } else {
17 | System.err.println("Se han recibido demasiados argumentos");
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/cap03/Ejercicio03_03.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 3.3 – Realiza el mismo ejercicio que en el punto anterior,
2 | * pero pon el número máximo de argumentos aceptables en una constante.
3 | */
4 |
5 | public class Ejercicio03_03 {
6 | // Número máximo de argumentos.
7 | // Es una constante, el nombre debe decirnos qué significa, no que valor tiene
8 | // y debemos escribirlo en MAYÚSCULAS
9 | private static final int MAX_ARGS = 4;
10 |
11 | public static void main(String[] args) {
12 | int numArgs = args.length;
13 | if (numArgs == 0) {
14 | // System.err.println sacará el mensaje por la salida de error
15 | // En este caso, por la consola, pero en rojo
16 | System.err.println("No se han recibido argumentos");
17 | } else if (numArgs <= MAX_ARGS) {
18 | System.out.println("Se han recibido " + numArgs + " argumentos");
19 | } else {
20 | System.err.println("Se han recibido demasiados argumentos");
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/cap03/Ejercicio03_04.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 3.4 – Escribe un programa que reciba el número de mes y devuelva
2 | * el número de días que tiene. Ignora los años bisiestos.
3 | * Sólo debes hacer algo si recibes 1 sólo parámetro.
4 | */
5 |
6 | public class Ejercicio03_04 {
7 | public static void main(String[] args) {
8 | if (args.length == 1) {
9 | int mes = Integer.valueOf(args[0]);
10 | // || es el OR, será cierto si al menos uno de los operandos es cierto
11 | if (mes < 1 || mes > 12) {
12 | System.err.println(mes + " no es un mes válido");
13 | } else {
14 | int dias = calculaDias(mes);
15 | System.out.println("El mes " + mes + " tiene " + dias + " días.");
16 | } // if mes
17 | } // if args
18 | } // main
19 |
20 | private static int calculaDias(int mes) {
21 | int dias;
22 | // miraremos los valores de mes
23 | // se puede hacer siempre con enteros y caracteres
24 | switch (mes) {
25 | case 2:
26 | System.out.println("Febrero");
27 | dias = 28;
28 | break;
29 | case 4:
30 | System.out.println("Abril");
31 | case 6:
32 | System.out.println("Junio");
33 | case 9:
34 | System.out.println("Setiembre");
35 | case 11:
36 | System.out.println("Noviembre");
37 | dias = 30;
38 | break; // hasta que no ponemos el break, sigue ejecutando
39 | // prueba con un 4 de parámetro ;)
40 | default:
41 | System.out.println("Mes de los largos");
42 | dias = 31;
43 | break;
44 | } // switch
45 | return dias;
46 | }
47 | } // clase
48 |
--------------------------------------------------------------------------------
/cap03/Ejercicio03_05.java:
--------------------------------------------------------------------------------
1 | public class Ejercicio03_05 {
2 | private static final String CANTA = "CANTA";
3 | private static final String LADRA = "LADRA";
4 |
5 | public static void main(String[] args) {
6 | if (args != null) { // [1]
7 | boolean hayArgumentos;
8 | if (args.length > 0) { // [2]
9 | hayArgumentos = true;
10 | } else {
11 | hayArgumentos = false;
12 | }
13 | if (!hayArgumentos) { // [3]
14 | System.err.println("No tengo argumentos");
15 | return;
16 | }
17 | if (hayArgumentos) { // [4]
18 | int numArgumentos = args.length;
19 |
20 | String primerArgumento = args[0];
21 | if (primerArgumento.equals(CANTA)) { // [5]
22 | System.out.println(
23 | "Un, dos, tres, un pasito palante María!");
24 | } else if (LADRA.equals(primerArgumento)) { // [6]
25 | boolean faltaNombre;
26 | String nombrePerro = "";
27 | if (numArgumentos > 1) { // [7]
28 | faltaNombre = false;
29 | nombrePerro = args[1];
30 | System.out.println("Bub bub bub");
31 | } else {
32 | faltaNombre = true;
33 | System.out.println("Grr grr grr");
34 | }
35 | if (faltaNombre) { // [8]
36 | System.out.println("No sé como te llamas");
37 | } else {
38 | System.out.println("Hola " + nombrePerro);
39 | }
40 | } else {
41 | System.err.println("No sé que quieres que haga");
42 | }
43 | }
44 | } else {
45 | System.err.println("Necesito argumentos");
46 | }
47 | }
48 | }
--------------------------------------------------------------------------------
/cap03/Ejercicio03_05Sol.java:
--------------------------------------------------------------------------------
1 | public class Ejercicio03_05Sol {
2 | private static final String CANTA = "CANTA";
3 | private static final String LADRA = "LADRA";
4 |
5 | public static void main(String[] args) {
6 | boolean hayArgumentos = args.length > 0;
7 |
8 | if (!hayArgumentos) { // (3)
9 | System.err.println("No tengo argumentos");
10 | return;
11 | }
12 |
13 | int numArgumentos = args.length;
14 |
15 | String primerArgumento = args[0];
16 | if (primerArgumento.equals(CANTA)) { // (5)
17 | System.out.println("Un, dos, tres, un pasito palante María!");
18 | } else if (LADRA.equals(primerArgumento)) { // (6)
19 | // negamos la condición o giramos el >
20 | boolean faltaNombre = numArgumentos <= 1;
21 | if (!faltaNombre) { // (7)-(8)
22 | String nombrePerro = args[1];
23 | System.out.println("Bub bub bub");
24 | System.out.println("Hola " + nombrePerro);
25 | } else {
26 | System.out.println("Grr grr grr");
27 | System.out.println("No sé como te llamas");
28 | }
29 | } else {
30 | System.err.println("No sé que quieres que haga");
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/cap03/Ejercicio03_06.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 3.6: OPERADOR TERNARIO – Calcula el valor absoluto de un float recibido como parámetro.
2 | */
3 | public class Ejercicio03_06 {
4 | public static void main(String[] args) {
5 | float num = Float.valueOf(args[0]);
6 |
7 | // operador ternario: cond ? siCierto : siFalso
8 | float abs = num > 0 ? num : -num;
9 | // alternativa con if
10 | // if (num > 0) {
11 | // abs = num;
12 | // } else {
13 | // abs = -num;
14 | // }
15 |
16 | System.out.println("El valor absoluto de " + num + " es " + abs);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/cap04/Ejemplo04_01.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_01 {
2 | public static void main(String[] args) {
3 | // El bucle "for each" (aunque realmente se escribe for), recorre
4 | // todos los elementos de una colección. En cada iteración, s tendrá el
5 | // valor de uno de los elementos, y podemos hacer con ella lo que haríamos
6 | // con cualquier otra variable.
7 | for (String s : args) {
8 | System.out.println(s);
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_02.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_02 {
2 |
3 | private static final int NUM = 3;
4 |
5 | public static void main(String[] args) {
6 | for (int i = 0; i < NUM; i++) {
7 | System.out.println(i);
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_03.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_03 {
2 | public static void main(String[] args) {
3 | // El bucle "for each" (aunque realmente se escribe for), recorre
4 | // todos los elementos de una colección. En cada iteración, s tendrá el
5 | // valor de uno de los elementos, y podemos hacer con ella lo que haríamos
6 | // con cualquier otra variable.
7 | for (int i = 0; i < args.length; i ++) {
8 | String s = args[i];
9 | System.out.println(s);
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_04.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_04 {
2 | // Acuérdate de usar constantes
3 | private static final String FIN = "fin";
4 |
5 | public static void main(String[] args) {
6 | System.out.println("Se han recibido " + args.length + " argumentos:");
7 |
8 | // El bucle while itera hasta que se cumple la condición
9 | // No podemos olvidar controlar la posición
10 | int i = 0; // Punto de inicio
11 | // CUIDADO!!! No podemos comparar strings con ==
12 | while (i < args.length && !args[i].equals(FIN)) { // condición de terminación
13 | System.out.println(i + ")" + args[i]);
14 | i++; // actualización
15 | }
16 |
17 | // Como la i fue declarada fuera del bucle, aquí aún podemos usarla.
18 | System.out.println("\"fin\" estaba en la posición nº " + i);
19 | }
20 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_05a.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_05a {
2 | // Acuérdate de usar constantes
3 | private static final String FIN = "fin";
4 |
5 | public static void main(String[] args) {
6 | System.out.println("Se han recibido " + args.length + " argumentos:");
7 |
8 | // El bucle while itera hasta que se cumple la condición
9 | // No podemos olvidar controlar la posición
10 | int i = 0; // Punto de inicio
11 | do { // condición de terminación
12 | System.out.println(i + ")" + args[i]);
13 | i++; // actualización
14 | } while (!args[i].equals(FIN) && i < args.length);
15 |
16 | // Como la i fue declarada fuera del bucle, aquí aún podemos usarla.
17 | System.out.println("\"fin\" estaba en la posición nº " + i);
18 | }
19 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_05b.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_05b {
2 | // Acuérdate de usar constantes
3 | private static final String FIN = "fin";
4 |
5 | public static void main(String[] args) {
6 | // != será cierto si ambos operandos son distintos
7 | if (args.length != 0) {
8 | System.out.println("Se han recibido " + args.length + " argumentos:");
9 |
10 | // El bucle do while se ejecuta al menos una vez,
11 | // y hasta que se cumple la condición
12 | int i = 0;
13 | String palabra; // debemos declararla fuera del bucle para poderlo usar en la condición
14 | do {
15 | palabra = args[i];
16 | System.out.println(i + ")" + palabra);
17 | i++;
18 | } while (!palabra.equals(FIN) && i < args.length);
19 | } else {
20 | System.err.println("No se han recibido argumentos");
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_06.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Ejemplo04_06 {
4 |
5 | public static void main(String[] args) {
6 | Scanner scanner = new Scanner(System.in);
7 |
8 | System.out.println("¿Cómo te llamas?");
9 | String nombre = scanner.nextLine();
10 | System.out.println("¡Hola, " + nombre + "! ¿Qué tal?");
11 | }
12 |
13 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_07.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_07 {
2 | public static void main(String[] args) {
3 | int ancho = Integer.valueOf(args[0]);
4 | int alto = Integer.valueOf(args[1]);
5 | String s = "";
6 | for (int i = 0; i < alto; i++) {
7 | for (int j = 0; j < ancho; j++) {
8 | s += "X";
9 | }
10 | s += "\n";
11 | }
12 | System.out.println(s);
13 | }
14 | }
--------------------------------------------------------------------------------
/cap04/Ejemplo04_08.java:
--------------------------------------------------------------------------------
1 | public class Ejemplo04_08 {
2 | public static void main(String[] args) {
3 | System.out.println(
4 | "Debe copiar el texto \"I'm happy\" dentro del fichero:\n" +
5 | "tC:\\app\\nube\\recursos\\textos.txt");
6 | }
7 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_01.java:
--------------------------------------------------------------------------------
1 | public class Ejercicio04_01 {
2 | private static final int LIM = 5;
3 |
4 | public static void main(String[] args) {
5 | for (String s : args) {
6 | if (s.length() < LIM) {
7 | System.out.println(s.toUpperCase());
8 | } else {
9 | System.out.println(s.toLowerCase());
10 | }
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_02.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 4.2 - Lista todos los argumentos que recibas, pero mostrando su posición:
2 | *
3 | * java Ejercicio04_02 hola como estás
4 | * 0) hola
5 | * 1) como
6 | * 2) estás
7 | */
8 |
9 | public class Ejercicio04_02 {
10 | public static void main(String[] args) {
11 | for (int i = 0; i < args.length; i ++) {
12 | String s = args[i];
13 | System.out.println(i + ") " + s);
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_02ForEach.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 4.2 - Lista todos los argumentos que recibas, pero mostrando su posición:
2 | * Usando for each
3 | * java Ejercicio04_02ForEach hola como estás
4 | * 0) hola
5 | * 1) como
6 | * 2) estás
7 | */
8 |
9 | public class Ejercicio04_02ForEach {
10 | public static void main(String[] args) {
11 | int i = 0;
12 | for (String s : args) {
13 | System.out.println(i + ") " + s);
14 | i ++;
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_03.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 4.3 - Lista todos los argumentos que recibas, pero cumpliendo las siguientes reglas:
2 | * Si la palabra es corta (5 o menos caracteres), la imprimes 4 veces en la misma línea,
3 | * y si es larga la repites sólo 2 veces.
4 | */
5 |
6 | public class Ejercicio04_03 {
7 | // no te olvides de poner todos los números mágicos como constantes!
8 | private static final int LIM = 5;
9 | private static final int REP_CORTA = 4;
10 | private static final int REP_LARGA = 2;
11 |
12 | public static void main(String[] args) {
13 | for (String s : args) {
14 | if (s.length() < LIM) {
15 | for (int i = 0; i < REP_CORTA; i++) {
16 | System.out.print(s + " ");
17 | }
18 | System.out.println(); // no te olvides del salto de línea
19 | } else {
20 | for (int i = 0; i < REP_LARGA; i++) {
21 | System.out.print(s + " ");
22 | }
23 | System.out.println(); // no te olvides del salto de línea
24 | }
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_04.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 4.4 - Traduce este código de for a while.
2 | */
3 |
4 | public class Ejercicio04_04 {
5 | public static void main(String[] args) {
6 | if (args.length == 1) {
7 | int res = 1;
8 | for(int num = Integer.valueOf(args[0]); num > 0; num --) {
9 | res *= num;
10 | }
11 | System.out.println("Resultado: " + res);
12 | } else {
13 | System.err.println("Necesito un argumento, ni más ni menos");
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_04Sol.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 4.4 - Traduce este código de for a while.
2 | */
3 |
4 | public class Ejercicio04_04Sol {
5 | public static void main(String[] args) {
6 | if (args.length == 1) {
7 | int num = Integer.valueOf(args[0]);
8 | int res = 1;
9 | while (num > 0) {
10 | res *= num;
11 | num --;
12 | }
13 | System.out.println("Resultado: " + res);
14 | } else {
15 | System.err.println("Necesito un argumento, ni más ni menos");
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_05.java:
--------------------------------------------------------------------------------
1 | /* Ejercicio 4.5 - Indica la posición del primer argumento recibido que sea una
2 | * palabra demasiado larga (más de 10 caracteres): “La Xª palabra es demasiado
3 | * larga.” (empezando por la primera), o “Todas las palabras son correctas.”,
4 | * si no hay ninguna que sobrepase dicha longitud.
5 | */
6 |
7 | public class Ejercicio04_05 {
8 | private static final int LIM = 10;
9 |
10 | public static void main(String[] args) {
11 | int i = 0;
12 | boolean encontrada = false;
13 | while (i < args.length && !encontrada) {
14 | encontrada = args[i].length() > LIM;
15 | i ++;
16 | }
17 | if (encontrada) {
18 | System.out.println("La " + i + "ª palabra es demasiado larga.");
19 | } else {
20 | System.out.println("Todas las palabras son correctas.");
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_06.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Ejercicio04_06 {
4 |
5 | private static final String CLAVE = "abracadabra";
6 |
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | String palabra;
11 | do {
12 | System.out.println("¡Hola!, por favor, escribe '" + CLAVE + "':");
13 | palabra = scanner.nextLine();
14 | } while (!palabra.equals(CLAVE));
15 |
16 | System.out.println("TU: " + palabra);
17 | System.out.println("YO: ¡pata de cabra!");
18 | }
19 | }
--------------------------------------------------------------------------------
/cap04/Ejercicio04_07.java:
--------------------------------------------------------------------------------
1 | public class Ejercicio04_07 {
2 | private static final int TAM = 10;
3 |
4 | public static void main(String[] args) {
5 | for (int i = 0; i < TAM; i ++) {
6 | for (int j = 0; j < TAM; j++) {
7 | System.out.print(i + "" + j + " ");
8 | }
9 | System.out.println();
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/cap05/PiedraPapelTijeras.java:
--------------------------------------------------------------------------------
1 | /* Proyecto – Vamos a jugar a piedra-papel-tijeras contra el ordenador.
2 | * Tendrás que explicarle al jugador cómo se juega, pedirle que nos dé su jugada
3 | * (Piedra, papeL, Tijeras, Salir), generar una jugada aleatoria para el ordenador
4 | * y decidir quien ha ganado.
5 | */
6 |
7 | import java.util.Scanner;
8 |
9 | public class PiedraPapelTijeras {
10 | private static final String PIEDRA = "P";
11 | private static final String PAPEL = "L";
12 | private static final String TIJERAS = "T";
13 | private static final String SALIR = "S";
14 |
15 | private static final String[] JUEGO = {PIEDRA, PAPEL, TIJERAS};
16 |
17 | private static final int EMPATE = 0;
18 | private static final int GANAS = 1;
19 | private static final int PIERDES = 2;
20 |
21 | private static final int ERROR_NO_ENCONTRADA = -1;
22 |
23 | // Mensajes al usuario
24 | private static final String BIENVENIDA =
25 | "¡Bienvenido al juego Piedra-papel-tijeras!";
26 | private static final String OPCIONES =
27 | PIEDRA + " (piedra), " + PAPEL + " (papel), "
28 | + TIJERAS + " (tijeras) o " + SALIR + " (salir)";
29 | private static final String PEDIR_JUGADA =
30 | "¿Cuál es tu jugada? " + OPCIONES;
31 | private static final String PEDIR__NUEVA_JUGADA =
32 | "¿Cuál es tu nueva jugada? " + OPCIONES;
33 | private static final String FIN = "Fin de la partida";
34 |
35 | private static final String MSJ_ERROR_NO_ENCONTRADA =
36 | "No entiendo tu jugada";
37 |
38 | public static void main(String[] args) {
39 | // abrimos un scanner para leer la entrada del usuario
40 | Scanner s = new Scanner(System.in);
41 |
42 | // Instrucciones
43 | System.out.println(BIENVENIDA);
44 | System.out.println(PEDIR_JUGADA);
45 |
46 | while(true) { // iteramos para siempre
47 | // Jugada del ordenador
48 | int eleccionPC = (int)(Math.random() * JUEGO.length);
49 |
50 | // Jugada del usuario
51 | String sEleccionUsuario = s.next();
52 | if (sEleccionUsuario.equalsIgnoreCase(SALIR)) {
53 | break; // Si nos da una S, cortamos el bucle para terminar
54 | }
55 |
56 | // Interpretación de la jugada del usuario
57 | int eleccionUsuario = convertir(sEleccionUsuario);
58 | if (eleccionUsuario == ERROR_NO_ENCONTRADA) {
59 | System.err.println(MSJ_ERROR_NO_ENCONTRADA);
60 | continue; // Seguimos en el bucle, siguiente iteración
61 | }
62 |
63 | // Calcular el ganador de la jugada
64 | int resultado = usuarioGana(eleccionPC, eleccionUsuario);
65 |
66 | // Mostar el resultado de la jugada
67 | switch (resultado) {
68 | case GANAS:
69 | System.out.println("¡Enhorabuena! Tu "
70 | + JUEGO[eleccionUsuario] + " gana a "
71 | + JUEGO[eleccionPC]);
72 | break;
73 | case PIERDES:
74 | System.out.println("¡Lo siento! Tu "
75 | + JUEGO[eleccionUsuario] + " pierde ante "
76 | + JUEGO[eleccionPC]);
77 | break;
78 | case EMPATE:
79 | System.out.println("¡Empate a " + JUEGO[eleccionPC] + "!");
80 | break;
81 | }
82 | System.out.println("¿Cuál es tu nueva jugada? P (piedra), L (papel), T (tijeras) o S (salir)");
83 | }
84 | System.out.println(FIN);
85 | // cerramos lo que abrimos
86 | s.close();
87 | }
88 |
89 | private static int convertir(String sEleccionUsuario) {
90 | for (int i = 0; i < JUEGO.length; i++) {
91 | if (JUEGO[i].equalsIgnoreCase(sEleccionUsuario)) {
92 | // equalsIgnoreCase nos permite aceptar respuestas en mayúscula o minúscula
93 | return i;
94 | }
95 | }
96 | return ERROR_NO_ENCONTRADA; // TODO tratar esto correctamente
97 | }
98 |
99 | private static int usuarioGana(int eleccionPC, int eleccionUsuario) {
100 | int res = eleccionUsuario - eleccionPC;
101 | if (res < 0) {
102 | res += JUEGO.length;
103 | }
104 | return res;
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/cap06/SinEjemplos.txt:
--------------------------------------------------------------------------------
1 | Capítulo sin ejemplos de código.
--------------------------------------------------------------------------------
/cap07/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/cap07/.gitignore:
--------------------------------------------------------------------------------
1 | /bin/
2 |
--------------------------------------------------------------------------------
/cap07/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | sooper
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/cap07/src/sooper/IContenedor.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import java.util.Set;
4 |
5 | import sooper.enums.TipoContenedor;
6 |
7 | public interface IContenedor {
8 |
9 | String getReferencia();
10 |
11 | int getVolumen();
12 |
13 | int volumenDisponible();
14 |
15 | int getResistencia();
16 |
17 | Set getProductos();
18 |
19 | TipoContenedor getTipo();
20 |
21 | boolean meter(IProducto producto);
22 |
23 | boolean resiste(IProducto producto);
24 |
25 | int getSuperficie();
26 | }
27 |
--------------------------------------------------------------------------------
/cap07/src/sooper/IPedido.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import java.util.Set;
4 |
5 | public interface IPedido {
6 |
7 | String getReferencia();
8 |
9 | Set getProductos();
10 |
11 | Set getContenedores();
12 |
13 | void addContenedor(IContenedor contenedor);
14 |
15 | IContenedor addProducto(IProducto producto);
16 | }
17 |
--------------------------------------------------------------------------------
/cap07/src/sooper/IProducto.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import sooper.enums.Categoria;
4 |
5 | public interface IProducto {
6 |
7 | String getReferencia();
8 |
9 | int getPeso();
10 |
11 | int getVolumen();
12 |
13 | Categoria getCategoria();
14 |
15 | boolean esCompatible(IProducto p);
16 |
17 | boolean tengoEspacio(IContenedor contenedor);
18 |
19 | void meter(IContenedor contenedor);
20 | }
21 |
--------------------------------------------------------------------------------
/cap07/src/sooper/Pedido.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class Pedido implements IPedido {
7 |
8 | private String referencia;
9 | private Set contenedores;
10 |
11 | public Pedido(String referencia) {
12 | this.referencia = referencia;
13 | this.contenedores = new HashSet<>();
14 | }
15 |
16 | @Override
17 | public String getReferencia() {
18 | return referencia;
19 | }
20 |
21 | @Override
22 | public Set getProductos() {
23 | // TODO Auto-generated method stub
24 | return null;
25 | }
26 |
27 | @Override
28 | public Set getContenedores() {
29 | return contenedores;
30 | }
31 |
32 | @Override
33 | public void addContenedor(IContenedor contenedor) {
34 | contenedores.add(contenedor);
35 | }
36 |
37 | @Override
38 | public IContenedor addProducto(IProducto producto) {
39 | // TODO Auto-generated method stub
40 | return null;
41 | }
42 | }
--------------------------------------------------------------------------------
/cap07/src/sooper/Supermercado.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import sooper.contenedores.Bolsa;
4 | import sooper.contenedores.Caja;
5 |
6 | public class Supermercado {
7 |
8 | public static void main(String[] args) {
9 | IPedido miPedido = new Pedido("pedido001");
10 | IContenedor bolsa1 = new Bolsa("B111", 40, 25);
11 | IContenedor caja1 = new Caja("C222", 30, 50, 75);
12 | miPedido.addContenedor(bolsa1);
13 | miPedido.addContenedor(caja1);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/cap07/src/sooper/contenedores/Bolsa.java:
--------------------------------------------------------------------------------
1 | package sooper.contenedores;
2 |
3 | import sooper.enums.TipoContenedor;
4 |
5 | public class Bolsa extends Contenedor {
6 | private int ancho;
7 |
8 | public Bolsa(String referencia, int alto, int ancho) {
9 | super(referencia, alto);
10 | this.ancho = ancho;
11 | }
12 |
13 | @Override
14 | public TipoContenedor getTipo() {
15 | return TipoContenedor.BOLSA;
16 | }
17 |
18 | @Override
19 | public int getSuperficie() {
20 | int radio = getDiametro() / 2;
21 | return (int) (Math.PI * radio * radio);
22 | }
23 |
24 | private int getDiametro() {
25 | return (int) ((2 * ancho) / Math.PI);
26 | }
27 | }
--------------------------------------------------------------------------------
/cap07/src/sooper/contenedores/Caja.java:
--------------------------------------------------------------------------------
1 | package sooper.contenedores;
2 |
3 | import sooper.enums.TipoContenedor;
4 |
5 | public class Caja extends Contenedor {
6 | private int ancho;
7 | private int largo;
8 |
9 | public Caja(String referencia, int alto, int ancho, int largo) {
10 | super(referencia, alto);
11 | this.ancho = ancho;
12 | this.largo = largo;
13 | }
14 |
15 | @Override
16 | public TipoContenedor getTipo() {
17 | return TipoContenedor.CAJA;
18 | }
19 |
20 | @Override
21 | public int getSuperficie() {
22 | return ancho * largo;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/cap07/src/sooper/contenedores/Contenedor.java:
--------------------------------------------------------------------------------
1 | package sooper.contenedores;
2 |
3 | import java.util.Set;
4 |
5 | import sooper.IContenedor;
6 | import sooper.IProducto;
7 |
8 | public abstract class Contenedor implements IContenedor {
9 |
10 | private String referencia;
11 | private int alto;
12 | private int resistencia;
13 |
14 | private Set productos;
15 |
16 | public Contenedor(String referencia, int alto) {
17 | this.referencia = referencia;
18 | this.alto = alto;
19 | }
20 |
21 | @Override
22 | public String getReferencia() {
23 | return referencia;
24 | }
25 |
26 | @Override
27 | public int getVolumen() {
28 | return alto * getSuperficie();
29 | }
30 |
31 | @Override
32 | public int volumenDisponible() {
33 | // TODO Auto-generated method stub
34 | return 0;
35 | }
36 |
37 | @Override
38 | public int getResistencia() {
39 | return resistencia;
40 | }
41 |
42 | @Override
43 | public Set getProductos() {
44 | return productos;
45 | }
46 |
47 | @Override
48 | public boolean meter(IProducto producto) {
49 | // TODO Auto-generated method stub
50 | return false;
51 | }
52 |
53 | @Override
54 | public boolean resiste(IProducto producto) {
55 | // TODO Auto-generated method stub
56 | return false;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/cap07/src/sooper/enums/Categoria.java:
--------------------------------------------------------------------------------
1 | package sooper.enums;
2 |
3 | public enum Categoria {
4 | ALIMENTACION, DROGUERIA, HIGIENE, MASCOTAS;
5 | }
6 |
--------------------------------------------------------------------------------
/cap07/src/sooper/enums/TipoContenedor.java:
--------------------------------------------------------------------------------
1 | package sooper.enums;
2 |
3 | public enum TipoContenedor {
4 | BOLSA, CAJA;
5 | }
6 |
--------------------------------------------------------------------------------
/cap08/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/cap08/.gitignore:
--------------------------------------------------------------------------------
1 | /bin/
2 |
--------------------------------------------------------------------------------
/cap08/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | sooper
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/cap08/Estatica.java:
--------------------------------------------------------------------------------
1 | public class Estatica {
2 | private static final int CONSTANTE = 0;
3 | private static int compartida = 0;
4 | private final int noModificable;
5 | private int normal;
6 |
7 | public Estatica(int n) {
8 | noModificable = n;
9 | }
10 |
11 | private void incrementaTodo() {
12 | // CONSTANTE ++;
13 | compartida++;
14 | // noModificable ++;
15 | normal++;
16 | }
17 |
18 | private void pintaTodo(String titulo) {
19 | System.out.println(titulo);
20 | System.out.println("Constante: \t" + CONSTANTE);
21 | System.out.println("Compartida: \t" + compartida);
22 | System.out.println("No modificable: \t" + noModificable);
23 | System.out.println("Normal: \t" + normal);
24 | System.out.println();
25 | }
26 |
27 | public static void main(String[] args) {
28 | System.out.println("Constante: \t" + CONSTANTE);
29 | System.out.println("Compartida: \t" + compartida);
30 | // System.out.println("No modificable: \t" + noModificable);
31 | // System.out.println("Normal: \t" + normal);
32 | System.out.println();
33 | Estatica seis = new Estatica(6);
34 | Estatica ocho = new Estatica(8);
35 | Estatica diez = new Estatica(10);
36 | seis.pintaTodo("SEIS A: ");
37 | seis.incrementaTodo();
38 | seis.pintaTodo("SEIS B: ");
39 | ocho.incrementaTodo();
40 | seis.pintaTodo("SEIS C: ");
41 | diez.incrementaTodo();
42 | diez.incrementaTodo();
43 | seis.pintaTodo("SEIS D: ");
44 | ocho.pintaTodo("OCHO: ");
45 | diez.pintaTodo("DIEZ: ");
46 | }
47 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/IContenedor.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import java.util.Set;
4 |
5 | import sooper.enums.TipoContenedor;
6 |
7 | public interface IContenedor {
8 |
9 | String getReferencia();
10 |
11 | int getVolumen();
12 |
13 | int volumenDisponible();
14 |
15 | int getResistencia();
16 |
17 | Set getProductos();
18 |
19 | TipoContenedor getTipo();
20 |
21 | boolean meter(IProducto producto);
22 |
23 | boolean resiste(IProducto producto);
24 |
25 | int getSuperficie();
26 | }
27 |
--------------------------------------------------------------------------------
/cap08/src/sooper/IPedido.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import java.util.Set;
4 |
5 | public interface IPedido {
6 |
7 | String getReferencia();
8 |
9 | Set getProductos();
10 |
11 | Set getContenedores();
12 |
13 | void addContenedor(IContenedor contenedor);
14 |
15 | IContenedor addProducto(IProducto producto);
16 | }
17 |
--------------------------------------------------------------------------------
/cap08/src/sooper/IProducto.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import sooper.enums.Categoria;
4 |
5 | public interface IProducto {
6 |
7 | String getReferencia();
8 |
9 | int getPeso();
10 |
11 | int getVolumen();
12 |
13 | Categoria getCategoria();
14 |
15 | boolean esCompatible(IProducto p);
16 |
17 | boolean tengoEspacio(IContenedor contenedor);
18 |
19 | void meter(IContenedor contenedor);
20 | }
21 |
--------------------------------------------------------------------------------
/cap08/src/sooper/Pedido.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class Pedido implements IPedido {
7 |
8 | private String referencia;
9 | private Set contenedores;
10 |
11 | public Pedido(String referencia) {
12 | this.referencia = referencia;
13 | this.contenedores = new HashSet<>();
14 | }
15 |
16 | @Override
17 | public String getReferencia() {
18 | return referencia;
19 | }
20 |
21 | @Override
22 | public Set getProductos() {
23 | Set productos = null;
24 | for (IContenedor c : contenedores) {
25 | if (productos == null) {
26 | productos = c.getProductos();
27 | } else {
28 | productos.addAll(c.getProductos());
29 | }
30 | }
31 | return productos;
32 | }
33 |
34 | @Override
35 | public Set getContenedores() {
36 | return contenedores;
37 | }
38 |
39 | @Override
40 | public void addContenedor(IContenedor contenedor) {
41 | contenedores.add(contenedor);
42 | }
43 |
44 | @Override
45 | public IContenedor addProducto(IProducto producto) {
46 | for (IContenedor contenedor : contenedores) {
47 | if (contenedor.meter(producto)) {
48 | return contenedor;
49 | }
50 | }
51 | return null;
52 | }
53 |
54 | @Override
55 | public String toString() {
56 | StringBuilder sb = new StringBuilder();
57 | sb.append("Pedido: " + referencia + "\n");
58 | for (IContenedor contenedor : contenedores) {
59 | sb.append("\t" + contenedor + "\n");
60 | }
61 | return sb.toString();
62 | }
63 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/Supermercado.java:
--------------------------------------------------------------------------------
1 | package sooper;
2 |
3 | import sooper.contenedores.Bolsa;
4 | import sooper.contenedores.Caja;
5 | import sooper.productos.Congelado;
6 | import sooper.productos.Drogueria;
7 | import sooper.productos.Fresco;
8 | import sooper.productos.Higiene;
9 | import sooper.productos.Mascotas;
10 | import sooper.productos.NoPerecedero;
11 |
12 | public class Supermercado {
13 |
14 | public static void main(String[] args) {
15 | IPedido miPedido = new Pedido("pedido001");
16 | IContenedor bolsa1 = new Bolsa("B111", 40, 25, 900);
17 | IContenedor caja1 = new Caja("C222", 30, 50, 75);
18 | System.out.println("Bolsa: " + bolsa1);
19 | System.out.println("Caja: " + caja1);
20 | miPedido.addContenedor(bolsa1);
21 | miPedido.addContenedor(caja1);
22 | System.out.println("Mi pedido con contenedores: " + miPedido);
23 |
24 | IProducto manzanas = new Fresco("MNZ", 1000, 1500);
25 | IProducto helado = new Congelado("HLD", 800, 1000);
26 | IProducto papelWC = new Higiene("PWC", 500, 2500);
27 | IProducto peras = new Fresco("PER", 800, 1200);
28 |
29 | IContenedor contManzanas = miPedido.addProducto(manzanas);
30 | IContenedor contHelado = miPedido.addProducto(helado);
31 | IContenedor contPapel = miPedido.addProducto(papelWC);
32 | IContenedor contPeras = miPedido.addProducto(peras);
33 |
34 | for (int i = 0; i < 3; i++) {
35 | IContenedor caja = new Caja("C23" + i, 30, 40, 30);
36 | miPedido.addContenedor(caja);
37 | }
38 | for (int i = 0; i < 5; i++) {
39 | IContenedor bolsa = new Bolsa("B12" + i, 30, 25, 3000);
40 | miPedido.addContenedor(bolsa);
41 | }
42 | for (int i = 0; i < 12; i++) {
43 | IProducto leche = new NoPerecedero("LCH" + i, 6600, 7000);
44 | miPedido.addProducto(leche);
45 | }
46 | miPedido.addProducto(new Mascotas("GAT", 5000, 10000)); // comida gato
47 | miPedido.addProducto(new Mascotas("PER1", 10000, 20000)); // comida perro
48 | miPedido.addProducto(new Mascotas("PER2", 10000, 20000)); // más comida perro
49 | miPedido.addProducto(new Higiene("GEL", 1500, 1600)); // gel de ducha
50 | miPedido.addProducto(new Drogueria("DET", 2000, 1600)); // detergente lavadora
51 | miPedido.addProducto(new Drogueria("LEJ", 1000, 1000)); // lejía
52 | for (int i = 0; i < 24; i++) {
53 | miPedido.addProducto(new Fresco("YOG" + i, 250, 300)); // yogur
54 | }
55 | miPedido.addProducto(new NoPerecedero("ARR", 1000, 1000)); // arroz
56 | for (int i = 0; i < 5; i++) {
57 | miPedido.addProducto(new NoPerecedero("PAS" + i, 1000, 1200)); // pasta
58 | }
59 | System.out.println("Mi pedido con productos: " + miPedido);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/cap08/src/sooper/contenedores/Bolsa.java:
--------------------------------------------------------------------------------
1 | package sooper.contenedores;
2 |
3 | import sooper.enums.TipoContenedor;
4 |
5 | public class Bolsa extends Contenedor {
6 | private int ancho;
7 |
8 | public Bolsa(String referencia, int alto, int ancho, int resistencia) {
9 | super(referencia, alto, resistencia);
10 | this.ancho = ancho;
11 | }
12 |
13 | @Override
14 | public TipoContenedor getTipo() {
15 | return TipoContenedor.BOLSA;
16 | }
17 |
18 | @Override
19 | public int getSuperficie() {
20 | int radio = getDiametro() / 2;
21 | return (int) (Math.PI * radio * radio);
22 | }
23 |
24 | private int getDiametro() {
25 | return (int) ((2 * ancho) / Math.PI);
26 | }
27 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/contenedores/Caja.java:
--------------------------------------------------------------------------------
1 | package sooper.contenedores;
2 |
3 | import sooper.IProducto;
4 | import sooper.enums.TipoContenedor;
5 |
6 | public class Caja extends Contenedor {
7 | private int ancho;
8 | private int largo;
9 |
10 | public Caja(String referencia, int alto, int ancho, int largo) {
11 | super(referencia, alto, 0);
12 | this.ancho = ancho;
13 | this.largo = largo;
14 | }
15 |
16 | @Override
17 | public TipoContenedor getTipo() {
18 | return TipoContenedor.CAJA;
19 | }
20 |
21 | @Override
22 | public int getSuperficie() {
23 | return ancho * largo;
24 | }
25 |
26 | @Override
27 | public boolean resiste(IProducto producto) {
28 | return true;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/cap08/src/sooper/contenedores/Contenedor.java:
--------------------------------------------------------------------------------
1 | package sooper.contenedores;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | import sooper.IContenedor;
7 | import sooper.IProducto;
8 |
9 | public abstract class Contenedor implements IContenedor {
10 |
11 | private String referencia;
12 | private int alto;
13 | private int resistencia;
14 |
15 | private Set productos;
16 |
17 | public Contenedor(String referencia, int alto, int resistencia) {
18 | this.referencia = referencia;
19 | this.alto = alto;
20 | this.resistencia = resistencia;
21 | productos = new HashSet<>();
22 | }
23 |
24 | @Override
25 | public String getReferencia() {
26 | return referencia;
27 | }
28 |
29 | @Override
30 | public int getVolumen() {
31 | return alto * getSuperficie();
32 | }
33 |
34 | @Override
35 | public int volumenDisponible() {
36 | return getVolumen() - volumenOcupado();
37 | }
38 |
39 | private int volumenOcupado() {
40 | int res = 0;
41 | for (IProducto p : productos) {
42 | res += p.getVolumen();
43 | }
44 | return res;
45 | }
46 |
47 | @Override
48 | public int getResistencia() {
49 | return resistencia;
50 | }
51 |
52 | @Override
53 | public Set getProductos() {
54 | return productos;
55 | }
56 |
57 | @Override
58 | public boolean meter(IProducto producto) {
59 | boolean resistenciaOk = resiste(producto);
60 | boolean volumenOk = producto.tengoEspacio(this);
61 | boolean compatibilidadOk = true;
62 | for (IProducto p : productos) {
63 | boolean compatibleOk = producto.esCompatible(p);
64 | compatibilidadOk &= compatibleOk;
65 | }
66 | boolean acepta = resistenciaOk && volumenOk && compatibilidadOk;
67 | if (acepta) {
68 | productos.add(producto);
69 | producto.meter(this);
70 | }
71 | return acepta;
72 | }
73 |
74 | @Override
75 | public boolean resiste(IProducto producto) {
76 | return resistencia > producto.getPeso();
77 | }
78 |
79 | public String toString() {
80 | StringBuilder sb = new StringBuilder("Contenedor " + referencia + " ["
81 | + getTipo() + "] (sup " + getSuperficie() + "cm2 - vol "
82 | + getVolumen() + "cm3 - resistencia " + getResistencia() + " g).\n");
83 | if (productos.isEmpty()) {
84 | sb.append("\t\tvacío\n");
85 | }
86 | for (IProducto p : productos) {
87 | sb.append("\t\t" + p + "\n");
88 | }
89 | sb.append("\t\t>> Disponible vol " + volumenDisponible() + "cm3");
90 | return sb.toString();
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/cap08/src/sooper/enums/Categoria.java:
--------------------------------------------------------------------------------
1 | package sooper.enums;
2 |
3 | public enum Categoria {
4 | ALIMENTACION, DROGUERIA, HIGIENE, MASCOTAS;
5 | }
6 |
--------------------------------------------------------------------------------
/cap08/src/sooper/enums/TipoContenedor.java:
--------------------------------------------------------------------------------
1 | package sooper.enums;
2 |
3 | public enum TipoContenedor {
4 | BOLSA, CAJA;
5 | }
6 |
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/Alimentacion.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | import static sooper.enums.Categoria.ALIMENTACION;
4 | import sooper.IProducto;
5 | import sooper.enums.Categoria;
6 |
7 | public class Alimentacion extends Producto {
8 | public Alimentacion(String referencia, int peso, int volumen) {
9 | super(referencia, peso, volumen);
10 | }
11 |
12 | @Override
13 | public Categoria getCategoria() {
14 | return ALIMENTACION;
15 | }
16 |
17 | @Override
18 | public boolean esCompatible(IProducto p) {
19 | return Categoria.ALIMENTACION.equals(p.getCategoria());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/Congelado.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | public class Congelado extends Alimentacion {
4 | public Congelado(String referencia, int peso, int volumen) {
5 | super(referencia, peso, volumen);
6 | }
7 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/Drogueria.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | import sooper.IProducto;
4 | import sooper.enums.Categoria;
5 |
6 | public class Drogueria extends Producto {
7 | public Drogueria(String referencia, int peso, int volumen) {
8 | super(referencia, peso, volumen);
9 | }
10 |
11 | @Override
12 | public Categoria getCategoria() {
13 | return Categoria.DROGUERIA;
14 | }
15 |
16 | @Override
17 | public boolean esCompatible(IProducto p) {
18 | return !Categoria.ALIMENTACION.equals(p.getCategoria())
19 | && !Categoria.MASCOTAS.equals(p.getCategoria());
20 | }
21 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/Fresco.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | public class Fresco extends Alimentacion {
4 | public Fresco(String referencia, int peso, int volumen) {
5 | super(referencia, peso, volumen);
6 | }
7 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/Higiene.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | import sooper.IProducto;
4 | import sooper.enums.Categoria;
5 |
6 | public class Higiene extends Producto {
7 | public Higiene(String referencia, int peso, int volumen) {
8 | super(referencia, peso, volumen);
9 | }
10 |
11 | @Override
12 | public Categoria getCategoria() {
13 | return Categoria.HIGIENE;
14 | }
15 |
16 | @Override
17 | public boolean esCompatible(IProducto p) {
18 | return !Categoria.ALIMENTACION.equals(p.getCategoria());
19 | }
20 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/Mascotas.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | import sooper.IProducto;
4 | import sooper.enums.Categoria;
5 |
6 | public class Mascotas extends Producto {
7 | public Mascotas(String referencia, int peso, int volumen) {
8 | super(referencia, peso, volumen);
9 | }
10 |
11 | @Override
12 | public Categoria getCategoria() {
13 | return Categoria.MASCOTAS;
14 | }
15 |
16 | @Override
17 | public boolean esCompatible(IProducto p) {
18 | return !Categoria.DROGUERIA.equals(p.getCategoria());
19 | }
20 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/NoPerecedero.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | public class NoPerecedero extends Alimentacion {
4 | public NoPerecedero(String referencia, int peso, int volumen) {
5 | super(referencia, peso, volumen);
6 | }
7 | }
--------------------------------------------------------------------------------
/cap08/src/sooper/productos/Producto.java:
--------------------------------------------------------------------------------
1 | package sooper.productos;
2 |
3 | import sooper.IContenedor;
4 | import sooper.IProducto;
5 |
6 | public abstract class Producto implements IProducto {
7 |
8 | private String referencia;
9 | private int peso;
10 | private int volumen;
11 | private IContenedor contenedor;
12 |
13 | public Producto(String referencia, int peso, int volumen) {
14 | this.referencia = referencia;
15 | this.peso = peso;
16 | this.volumen = volumen;
17 | }
18 |
19 | @Override
20 | public String getReferencia() {
21 | return referencia;
22 | }
23 |
24 | @Override
25 | public int getPeso() {
26 | return peso;
27 | }
28 |
29 | @Override
30 | public int getVolumen() {
31 | return volumen;
32 | }
33 |
34 | @Override
35 | public boolean tengoEspacio(IContenedor contenedor) {
36 | return contenedor.volumenDisponible() > volumen;
37 | }
38 |
39 | @Override
40 | public void meter(IContenedor contenedor) {
41 | this.contenedor = contenedor;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | return "Producto [categoria=" + getCategoria() + ", referencia="
47 | + referencia + ", peso=" + peso + ", volumen="
48 | + volumen + ", contenedor=" + contenedor.getReferencia() + "]";
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/cap09/huerto/Huerto.java:
--------------------------------------------------------------------------------
1 | package huerto;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class Huerto implements IHuerto {
7 |
8 | private String nombre;
9 | private Set macetas;
10 |
11 | public Huerto(String nombre) {
12 | this.nombre = nombre;
13 | macetas = new HashSet<>();
14 | }
15 |
16 | @Override
17 | public void addMaceta(IMaceta maceta) {
18 | macetas.add(maceta);
19 | }
20 |
21 | @Override
22 | public IMaceta plantar(IPlanta planta) {
23 | for (IMaceta maceta : macetas) {
24 | if (maceta.plantar(planta)) {
25 | return maceta;
26 | }
27 | }
28 | return null;
29 | }
30 |
31 | @Override
32 | public String toString() {
33 | StringBuilder sb = new StringBuilder();
34 | sb.append("Huerto: " + nombre + "\n");
35 | for (IMaceta maceta : macetas) {
36 | sb.append("\t" + maceta + "\n");
37 | }
38 | return sb.toString();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/cap09/huerto/IHuerto.java:
--------------------------------------------------------------------------------
1 | package huerto;
2 |
3 | public interface IHuerto {
4 |
5 | void addMaceta(IMaceta maceta);
6 | IMaceta plantar(IPlanta planta);
7 | }
8 |
--------------------------------------------------------------------------------
/cap09/huerto/IMaceta.java:
--------------------------------------------------------------------------------
1 | package huerto;
2 |
3 | import huerto.enums.FormaMaceta;
4 |
5 | import java.util.Set;
6 |
7 | public interface IMaceta {
8 |
9 | String getNombre();
10 |
11 | int getVolumen();
12 | int volumenDisponible();
13 |
14 | int getSuperficie();
15 | int superficieDisponible();
16 |
17 | int getProfundidad();
18 |
19 | FormaMaceta getForma();
20 |
21 | boolean plantar(IPlanta planta);
22 | Set getPlantas();
23 | }
24 |
--------------------------------------------------------------------------------
/cap09/huerto/IPlanta.java:
--------------------------------------------------------------------------------
1 | package huerto;
2 |
3 | import huerto.enums.Especie;
4 | import huerto.enums.Familia;
5 |
6 | public interface IPlanta {
7 |
8 | String getNombre();
9 |
10 | int getSuperficieRequerida();
11 | int getVolumenRequerido();
12 |
13 | Familia getFamilia();
14 | Especie getEspecie();
15 |
16 | boolean esCompatible(IPlanta planta);
17 | void plantar(IMaceta maceta);
18 | boolean tengoEspacio(IMaceta maceta);
19 | }
20 |
--------------------------------------------------------------------------------
/cap09/huerto/Sistema.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSRschool/Anaya-MI-Java/3b891f0d3513e19937d5c9d096d40ddf7f448442/cap09/huerto/Sistema.java
--------------------------------------------------------------------------------
/cap09/huerto/enums/Especie.java:
--------------------------------------------------------------------------------
1 | package huerto.enums;
2 |
3 | public enum Especie {
4 | LECHUGA, ZANAHORIA, TOMATE, PEREJIL, ESPINACA, REMOLACHA, HINOJO;
5 | }
6 |
--------------------------------------------------------------------------------
/cap09/huerto/enums/Familia.java:
--------------------------------------------------------------------------------
1 | package huerto.enums;
2 |
3 | public enum Familia {
4 | HOJA, RAIZ, FRUTO, AROMATICA;
5 | }
6 |
--------------------------------------------------------------------------------
/cap09/huerto/enums/FormaMaceta.java:
--------------------------------------------------------------------------------
1 | package huerto.enums;
2 |
3 | public enum FormaMaceta {
4 | RECTANGULAR, TUBULAR;
5 | }
6 |
--------------------------------------------------------------------------------
/cap09/huerto/macetas/Maceta.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSRschool/Anaya-MI-Java/3b891f0d3513e19937d5c9d096d40ddf7f448442/cap09/huerto/macetas/Maceta.java
--------------------------------------------------------------------------------
/cap09/huerto/macetas/MacetaRectangular.java:
--------------------------------------------------------------------------------
1 | package huerto.macetas;
2 |
3 | import huerto.enums.FormaMaceta;
4 |
5 | public class MacetaRectangular extends Maceta {
6 |
7 | private int ancho;
8 | private int largo;
9 |
10 | public MacetaRectangular(String nombre, int alto, int ancho, int largo) {
11 | super(nombre, alto);
12 | this.ancho = ancho;
13 | this.largo = largo;
14 | }
15 |
16 | @Override
17 | public int getSuperficie() {
18 | return ancho * largo;
19 | }
20 |
21 | @Override
22 | public FormaMaceta getForma() {
23 | return FormaMaceta.RECTANGULAR;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/cap09/huerto/macetas/MacetaTubular.java:
--------------------------------------------------------------------------------
1 | package huerto.macetas;
2 |
3 | import huerto.enums.FormaMaceta;
4 |
5 | public class MacetaTubular extends Maceta {
6 |
7 | private int diametro;
8 |
9 | public MacetaTubular(String nombre, int alto, int diametro) {
10 | super(nombre, alto);
11 | this.diametro = diametro;
12 | }
13 |
14 | @Override
15 | public int getSuperficie() {
16 | return (int)(Math.PI * (diametro/2) * (diametro/2));
17 | }
18 |
19 | @Override
20 | public FormaMaceta getForma() {
21 | return FormaMaceta.TUBULAR;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/Hinojo.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Especie;
4 |
5 | public class Hinojo extends PlantaAromatica {
6 |
7 | public Hinojo(String nombre) {
8 | super(nombre, 10, 8);
9 | especie = Especie.HINOJO;
10 | incompatibles.add(Especie.TOMATE);
11 | incompatibles.add(Especie.ZANAHORIA);
12 | compatibles.add(Especie.LECHUGA);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/Lechuga.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Especie;
4 |
5 | public class Lechuga extends PlantaHoja {
6 |
7 | public Lechuga(String nombre) {
8 | super(nombre, 12, 22);
9 | especie = Especie.LECHUGA;
10 | compatibles.add(Especie.TOMATE);
11 | compatibles.add(Especie.ZANAHORIA);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/Perejil.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Especie;
4 |
5 | public class Perejil extends PlantaAromatica {
6 |
7 | public Perejil(String nombre) {
8 | super(nombre, 8, 5);
9 | especie = Especie.PEREJIL;
10 | incompatibles.add(Especie.LECHUGA);
11 | incompatibles.add(Especie.ZANAHORIA);
12 | compatibles.add(Especie.TOMATE);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/Planta.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.IMaceta;
4 | import huerto.IPlanta;
5 | import huerto.enums.Especie;
6 | import huerto.enums.Familia;
7 |
8 | import java.util.Date;
9 | import java.util.HashSet;
10 | import java.util.Set;
11 |
12 | public abstract class Planta implements IPlanta {
13 |
14 | protected Especie especie;
15 | protected Familia familia;
16 | protected Set incompatibles;
17 | protected Set compatibles;
18 |
19 | private String nombre;
20 | private int superficieRequerida;
21 | private int volumenRequerido;
22 | private Date fechaSiembra;
23 | private IMaceta maceta;
24 |
25 | public Planta(String nombre, int distancia, int litros) {
26 | this(nombre);
27 | this.superficieRequerida = distancia^2;
28 | this.volumenRequerido = litros * 1000;
29 | incompatibles = new HashSet();
30 | compatibles = new HashSet();
31 | }
32 |
33 | @Override
34 | public boolean esCompatible(IPlanta planta) {
35 | boolean compatible = true;
36 | if (!especie.equals(planta.getEspecie())) {
37 | if (!compatibles.contains(planta.getEspecie())) {
38 | compatible &= !familia.equals(planta.getFamilia());
39 | compatible &= !incompatibles.contains(planta.getEspecie());
40 | }
41 | }
42 | return compatible;
43 | }
44 |
45 | @Override
46 | public boolean tengoEspacio(IMaceta maceta) {
47 | boolean superficieOk = maceta.superficieDisponible() > getSuperficieRequerida();
48 | if (!superficieOk) {
49 | System.out.println("--- Superficie ko para " + getNombre() + " en " + maceta.getNombre());
50 | }
51 |
52 | boolean volumenOk = maceta.volumenDisponible() > getVolumenRequerido();
53 | if (!volumenOk) {
54 | System.out.println("--- Volumen ko para " + getNombre() + " en " + maceta.getNombre());
55 | }
56 |
57 | return superficieOk && volumenOk;
58 | }
59 |
60 | @Override
61 | public void plantar(IMaceta maceta) {
62 | fechaSiembra = new Date(); // hoy
63 | this.maceta = maceta;
64 | }
65 |
66 | public String getNombre() {
67 | return nombre;
68 | }
69 |
70 | public void setNombre(String nombre) {
71 | this.nombre = nombre;
72 | }
73 |
74 | public int getSuperficieRequerida() {
75 | return superficieRequerida;
76 | }
77 |
78 | public void setSuperficieRequerida(int superficieRequerida) {
79 | this.superficieRequerida = superficieRequerida;
80 | }
81 |
82 | public int getVolumenRequerido() {
83 | return volumenRequerido;
84 | }
85 |
86 | public void setVolumenRequerido(int volumenRequerido) {
87 | this.volumenRequerido = volumenRequerido;
88 | }
89 |
90 | public Especie getEspecie() {
91 | return especie;
92 | }
93 |
94 | public void setEspecie(Especie especie) {
95 | this.especie = especie;
96 | }
97 |
98 | public Familia getFamilia() {
99 | return familia;
100 | }
101 |
102 | public void setFamilia(Familia familia) {
103 | this.familia = familia;
104 | }
105 |
106 | @Override
107 | public String toString() {
108 | return "Planta " + nombre + " [especie=" + especie + ", familia=" + familia
109 | + ", superficieRequerida="
110 | + superficieRequerida + ", volumenRequerido="
111 | + volumenRequerido + ", incompatibles=" + incompatibles
112 | + ", fechaSiembra=" + fechaSiembra + ", maceta=" + maceta.getNombre() + "]";
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/PlantaAromatica.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Familia;
4 |
5 | public abstract class PlantaAromatica extends Planta {
6 |
7 | protected PlantaAromatica(String nombre, int distancia, int litros) {
8 | super(nombre, distancia, litros);
9 | familia = Familia.AROMATICA;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/PlantaFruto.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Familia;
4 |
5 | public abstract class PlantaFruto extends Planta {
6 |
7 | protected PlantaFruto(String nombre, int distancia, int litros) {
8 | super(nombre, distancia, litros);
9 | familia = Familia.FRUTO;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/PlantaHoja.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Familia;
4 |
5 | public abstract class PlantaHoja extends Planta {
6 |
7 | protected PlantaHoja(String nombre, int distancia, int litros) {
8 | super(nombre, distancia, litros);
9 | familia = Familia.HOJA;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/PlantaRaiz.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.IMaceta;
4 | import huerto.enums.Familia;
5 |
6 | public abstract class PlantaRaiz extends Planta {
7 |
8 | private int profunidadRequerida;
9 |
10 | protected PlantaRaiz(String nombre, int distancia, int litros, int profundidad) {
11 | super(nombre, distancia, litros);
12 | profunidadRequerida = profundidad;
13 | familia = Familia.RAIZ;
14 | }
15 |
16 | @Override
17 | public boolean tengoEspacio(IMaceta maceta) {
18 | boolean profundidadOk = maceta.getProfundidad() > profunidadRequerida;
19 | if (!profundidadOk) {
20 | System.out.println("--- Profundidad ko para " + getNombre() + " en " + maceta.getNombre());
21 | }
22 | return super.tengoEspacio(maceta) && profundidadOk;
23 | }
24 |
25 | public int getProfunidadRequerida() {
26 | return profunidadRequerida;
27 | }
28 |
29 | public void setProfunidadRequerida(int profunidadRequerida) {
30 | this.profunidadRequerida = profunidadRequerida;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/Tomate.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Especie;
4 |
5 | public class Tomate extends PlantaFruto {
6 |
7 | public Tomate(String nombre) {
8 | this(nombre, 30, 18);
9 | }
10 |
11 | protected Tomate(String nombre, int superficie, int volumen) {
12 | super(nombre, superficie, volumen);
13 | especie = Especie.TOMATE;
14 | incompatibles.add(Especie.HINOJO);
15 | compatibles.add(Especie.LECHUGA);
16 | compatibles.add(Especie.PEREJIL);
17 | compatibles.add(Especie.ZANAHORIA);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/TomateCherry.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | public class TomateCherry extends Tomate {
4 |
5 | public TomateCherry(String string) {
6 | super(string, 25, 15);
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/cap09/huerto/plantas/Zanahoria.java:
--------------------------------------------------------------------------------
1 | package huerto.plantas;
2 |
3 | import huerto.enums.Especie;
4 |
5 | public class Zanahoria extends PlantaRaiz {
6 |
7 | public Zanahoria(String nombre) {
8 | super(nombre, 10, 3, 25);
9 | especie = Especie.ZANAHORIA;
10 | incompatibles.add(Especie.PEREJIL);
11 | incompatibles.add(Especie.HINOJO);
12 | compatibles.add(Especie.REMOLACHA);
13 | compatibles.add(Especie.TOMATE);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/cap10/ejemplos/BusinessException.java:
--------------------------------------------------------------------------------
1 | public class BusinessException extends Exception {
2 |
3 | private ErrorCode errorCode;
4 |
5 | public BusinessException(ErrorCode errorCode, String detailMessage) {
6 | this(errorCode, detailMessage, null);
7 | }
8 |
9 | public BusinessException(ErrorCode errorCode, String detailMessage, Throwable cause) {
10 | super(generateMessage(errorCode, detailMessage), cause);
11 | this.errorCode = errorCode;
12 | }
13 |
14 | private static String generateMessage(ErrorCode errorCode, String detailMessage) {
15 | return errorCode + detailMessage;
16 | }
17 |
18 | public ErrorCode getErrorCode() {
19 | return errorCode;
20 | }
21 |
22 | enum ErrorCode {
23 | NEGATIVE("El número recibido es negativo"),
24 | EVEN("El número recibido es par");
25 |
26 | private String message;
27 |
28 | ErrorCode(String message) {
29 | this.message = message;
30 | }
31 |
32 | @Override
33 | public String toString() {
34 | return "ERROR: " + message + ". Detalle: ";
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/cap10/ejemplos/NoQuiero.java:
--------------------------------------------------------------------------------
1 | public class NoQuiero {
2 |
3 | public final static void main(String[] args) throws Exception {
4 | noQuieroParesNiNegativos(Integer.parseInt(args[0]));
5 | }
6 |
7 | private static void noQuieroParesNiNegativos(int a)
8 | throws ParException, NegativoException {
9 | if (esPar(a)) {
10 | throw new ParException(a + " es par!");
11 | }
12 | if (a < 0) {
13 | throw new NegativoException(a + " es negativo :(");
14 | }
15 | }
16 |
17 | private static boolean esPar(int num) {
18 | return num % 2 == 0;
19 | }
20 | }
21 |
22 | class ParException extends Exception {
23 |
24 | public ParException(String message) {
25 | super(message);
26 | }
27 | }
28 |
29 | class NegativoException extends Exception {
30 |
31 | public NegativoException(String message) {
32 | super(message);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/cap10/ejemplos/TechnicalException.java:
--------------------------------------------------------------------------------
1 | public class TechnicalException extends RuntimeException {
2 | public TechnicalException(String message) {
3 | super(message);
4 | }
5 |
6 | public TechnicalException(String message, Throwable cause) {
7 | super(message, cause);
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/cap10/ejemplos/TestExcepcional.java:
--------------------------------------------------------------------------------
1 | public class TestExcepcional {
2 | private static final String TECH_SIN_ARGUMENTOS = "Se esperaba al menos 1 argumento";
3 | private static final String TECH_MAL_FORMATO = "El primer argumento debe ser un número entero";
4 |
5 | public static void main(String[] args) {
6 | try {
7 | int res = trataNumero(args);
8 | System.out.println("El resultado es " + res);
9 | } catch (BusinessException be) {
10 | System.out.println("===== ERROR FUNCIONAL =====");
11 | System.out.println("Se ha producido un error funcional: " + be);
12 |
13 | switch (be.getErrorCode()) {
14 | case EVEN:
15 | System.out.println("Prefiero números impares (1, 3, 5, ...)");
16 | break;
17 | case NEGATIVE:
18 | System.out.println("Quiero números positivos");
19 | break;
20 | }
21 | } catch (TechnicalException te) {
22 | System.err.println("***** ERROR TECNICO *****");
23 | System.err.println("Se ha producido un error técnico: " + te);
24 | } finally {
25 | System.out.println("¡Gracias por usar este programa!");
26 | }
27 | }
28 |
29 | private static int trataNumero(String[] args) throws BusinessException {
30 | if (args.length == 0) {
31 | throw new TechnicalException(TECH_SIN_ARGUMENTOS);
32 | }
33 | try {
34 | int num = Integer.parseInt(args[0]);
35 | noQuieroPares(num);
36 | noQuieroNegativos(num);
37 | return num * num;
38 | } catch (NumberFormatException nfe) {
39 | throw new TechnicalException(TECH_MAL_FORMATO, nfe);
40 | }
41 | }
42 |
43 | private static void noQuieroPares(int n) throws BusinessException {
44 | if (n % 2 == 0) {
45 | throw new BusinessException(BusinessException.ErrorCode.EVEN, "Valor " + n);
46 | }
47 | }
48 |
49 | private static void noQuieroNegativos(int n) throws BusinessException {
50 | if (n < 0) {
51 | throw new BusinessException(BusinessException.ErrorCode.NEGATIVE, "Valor " + n);
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/cap10/ejercicios/LanzadorMultiple.java:
--------------------------------------------------------------------------------
1 | public class LanzadorMultiple {
2 |
3 | public static void queMeSalgo() {
4 | // Inténtalo aquí: escribe cualquier código
5 | // que lance una IndexOutOfBoundsException
6 | String[] lista = {"uno", "dos"};
7 | String tercero = lista[2];
8 | System.out.println(tercero);
9 | }
10 |
11 | public static void malditaCasta() {
12 | // Inténtalo aquí: escribe cualquier código
13 | // que lance una ClassCastException
14 | Number numero = new Integer(3);
15 | Double decimal = (Double) numero;
16 | System.out.println(decimal);
17 | }
18 |
19 | public static void siemprePositivoNuncaNegativo() {
20 | // Inténtalo aquí: escribe cualquier código
21 | // que lance una NegativeArraySizeException
22 | String[] lista = new String[-2];
23 | }
24 | }
--------------------------------------------------------------------------------
/cap10/ejercicios/LanzadorMultipleTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 | import org.junit.Assert;
3 |
4 | public class LanzadorMultipleTest {
5 | @Test
6 | public void testLanzadorIndexOutOfBounds() {
7 | try {
8 | LanzadorMultiple.queMeSalgo();
9 | Assert.fail("¡Vuelve a intentarlo! ¡Quiero que provoques una IndexOutOfBoundsException! Pista... Necesitas un array para poderte salir él.");
10 | } catch (IndexOutOfBoundsException npw) {
11 | // Bien
12 | } catch (Throwable t) {
13 | Assert.fail("¡Casi! Pero quiero que provoques una IndexOutOfBoundsException, ¡no una "
14 | + t.getClass().getSimpleName() + "! Pista... Necesitas un array para poderte salir él.");
15 | }
16 | }
17 |
18 | @Test
19 | public void testLanzadorClassCast() {
20 | try {
21 | LanzadorMultiple.malditaCasta();
22 | Assert.fail("¡Vuelve a intentarlo! Quiero que provoques una ClassCastException! Pista... Intenta convertir un objeto de un tipo en algo que no es.");
23 | } catch (ClassCastException npw) {
24 | // Bien
25 | } catch (Throwable t) {
26 | Assert.fail("¡Casi! Pero quiero que provoques una ClassCastException, ¡no una "
27 | + t.getClass().getSimpleName() + "! Pista... Intenta convertir un objeto de un tipo en algo que no es.");
28 | }
29 | }
30 |
31 | @Test
32 | public void testLanzadorNegativeArray() {
33 | try {
34 | LanzadorMultiple.siemprePositivoNuncaNegativo();
35 | Assert.fail("¡Vuelve a intentarlo! ¡Quiero que provoques una NegativeArraySizeException! Pista... En este caso también necesitas un array. El API de Java puede ayudarte a saber qué perrería hacerle para lograr esta excepción ;)");
36 | } catch (NegativeArraySizeException npw) {
37 | // Bien
38 | } catch (Throwable t) {
39 | Assert.fail("¡Casi! Pero quiero que provoques una NegativeArraySizeException, no una "
40 | + t.getClass().getSimpleName() + "! Pista... En este caso también necesitas un array. El API de Java puede ayudarte a saber qué perrería hacerle para lograr esta excepción ;)");
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/cap10/ejercicios/LanzadorNullPointer.java:
--------------------------------------------------------------------------------
1 | public class LanzadorNullPointer {
2 |
3 | public static void lloron() {
4 | // Inténtalo aquí: escribe cualquier código que lance una NullPointerException
5 | String saludo = null;
6 | saludo.toUpperCase();
7 | System.out.println(saludo);
8 | }
9 | }
--------------------------------------------------------------------------------
/cap10/ejercicios/LanzadorNullPointerTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 | import org.junit.Assert;
3 |
4 | public class LanzadorNullPointerTest {
5 | @Test
6 | public void testLanzadorNullPointer() {
7 | try {
8 | LanzadorNullPointer.lloron();
9 | Assert.fail("¡Esto no llora! Quiero que provoques una NullPointerException!");
10 | } catch (NullPointerException npw) {
11 | // Bien
12 | } catch (Throwable t) {
13 | Assert.fail("¡No seas tan llorica! Quiero que provoques una NullPointerException, ¡no una "
14 | + t.getClass().getSimpleName() + "!");
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/cap10/ejercicios/OrdenEjecucion.java:
--------------------------------------------------------------------------------
1 | public class OrdenEjecucion {
2 | private static final String CASO_0 = "ABCGHI";
3 | private static final String CASO_1 = "ABDGHI";
4 | private static final String CASO_2 = "ABEGH";
5 | private static final String CASO_3 = "ABCG";
6 | private static final String CASO_4 = "ABDG";
7 | private static final String[] CASOS = {CASO_0, CASO_1, CASO_2, CASO_3, CASO_4};
8 |
9 | static String res = "";
10 |
11 | // 0 - Si no se producen excepciones: A-B-C-G-H-I
12 | // 1 - Si metodoUno lanza AException: A-B-D-G-H-I
13 | // 2 - Si metodoUno lanza BException: A-B-E-G-H
14 | // 3 - Si metodoDos lanza algo: A-B-C-G
15 | // 4 - Si metodoUno lanza AException y metodoDos lanza algo: A-B-D-G
16 | public static void main(String[] args) {
17 | for (int i = 0; i < CASOS.length; i ++) {
18 | try {
19 | ordename(i);
20 | } catch (Exception e) {
21 | // aunque falle, quiero seguir y ver cómo dejó res
22 | }
23 | System.out.println("Caso " + i + ": " + res + " " + (res.equals(CASOS[i])));
24 | }
25 | }
26 |
27 | public static void ordename(int caso) throws BException {
28 | res = "A";
29 | try {
30 | res += "B";
31 | metodoUno(caso);
32 | res += "C";
33 | } catch (AException ae) {
34 | res += "D";
35 | } catch (BException be) {
36 | res += "E";
37 | throw be;
38 | // ni compila, si la pongo res += "F";
39 | } finally {
40 | res += "G";
41 | metodoDos(caso);
42 | res += "H";
43 | }
44 | res += "I";
45 | }
46 |
47 | private static void metodoUno(int caso) throws AException, BException {
48 | switch (caso) {
49 | case 1:
50 | case 4:
51 | throw new AException();
52 | case 2:
53 | throw new BException();
54 | default:
55 | // todo bien
56 | }
57 | }
58 |
59 | private static void metodoDos(int caso) {
60 | switch (caso) {
61 | case 3:
62 | case 4:
63 | throw new RuntimeException();
64 | default:
65 | // todo bien
66 | }
67 | }
68 | }
69 |
70 | class AException extends Exception {
71 |
72 | }
73 |
74 | class BException extends Exception {
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/cap10/ejercicios/OrdenEjecucionTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 | import org.junit.Assert;
3 |
4 | public class OrdenEjecucionTest {
5 | private static final String CASO_0 = "ABCGHI";
6 | private static final String CASO_1 = "ABDGHI";
7 | private static final String CASO_2 = "ABEGH";
8 | private static final String CASO_3 = "ABCG";
9 | private static final String CASO_4 = "ABDG";
10 |
11 | @Test
12 | public void testCaso0() {
13 | try {
14 | OrdenEjecucion.ordename(0);
15 | } catch (Exception e) {
16 | Assert.fail("En el caso 0 no deberían saltar excepciones.");
17 | }
18 | Assert.assertEquals("Caso 0 ko", CASO_0, OrdenEjecucion.res);
19 | }
20 |
21 | @Test
22 | public void testCaso1() {
23 | try {
24 | OrdenEjecucion.ordename(1);
25 | } catch (Exception e) {
26 | Assert.fail("En el caso 1 no deberían saltar excepciones.");
27 | }
28 | Assert.assertEquals("Caso 1 ko", CASO_1, OrdenEjecucion.res);
29 | }
30 |
31 | @Test
32 | public void testCaso2() {
33 | try {
34 | OrdenEjecucion.ordename(2);
35 | } catch (Exception e) {
36 | }
37 | Assert.assertEquals("Caso 2 ko", CASO_2, OrdenEjecucion.res);
38 | }
39 |
40 | @Test
41 | public void testCaso3() {
42 | try {
43 | OrdenEjecucion.ordename(3);
44 | } catch (Exception e) {
45 | }
46 | Assert.assertEquals("Caso 3 ko", CASO_3, OrdenEjecucion.res);
47 | }
48 |
49 | @Test
50 | public void testCaso4() {
51 | try {
52 | OrdenEjecucion.ordename(4);
53 | } catch (Exception e) {
54 | }
55 | Assert.assertEquals("Caso 4 ko", CASO_4, OrdenEjecucion.res);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/cap10/ejercicios/TodoControlado.java:
--------------------------------------------------------------------------------
1 | import java.io.UnsupportedEncodingException; // No olvides importar la clase de la excepción!
2 |
3 | public class TodoControlado {
4 |
5 | // Como getBytes puede lanzar una UnsupportedEncodingException
6 | // necesito declararlo con "throws"
7 | public static int cuentaBytes() throws UnsupportedEncodingException {
8 | String s = "Me ilusiona tener las excepciones controladas";
9 | byte[] misBytes = s.getBytes("encodingQueNoExiste");
10 | return misBytes.length;
11 | }
12 | }
--------------------------------------------------------------------------------
/cap10/ejercicios/TodoControladoTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 | import org.junit.Assert;
3 | import java.io.UnsupportedEncodingException;
4 |
5 | public class TodoControladoTest {
6 |
7 | @Test
8 | public void testExercise() {
9 | try {
10 | int num = TodoControlado.cuentaBytes();
11 | Assert.fail("No está mal, parece que has logrado que tu código compile. Pero no queríamos ocultar los problemas, así que mejor, en vez de tratar la excepción, simplemente declárala y déjala pasar. ");
12 | } catch (UnsupportedEncodingException e) {
13 | // Bien
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/cap11/Tests11.java:
--------------------------------------------------------------------------------
1 |
2 | public class Tests11 {
3 | public static void main(String[] args) {
4 | metodo(1);
5 | metodo(2);
6 | }
7 |
8 | private static void metodo(int n) {
9 | System.out.println("a" + n);
10 | System.out.println("b" + n);
11 | System.out.println("c" + n);
12 |
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/cap12/Mockeando/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/cap12/Mockeando/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Mockeando
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/cap12/Mockeando/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/cap12/Mockeando/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.8
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
12 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
13 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
14 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
15 | org.eclipse.jdt.core.compiler.release=disabled
16 | org.eclipse.jdt.core.compiler.source=1.8
17 |
--------------------------------------------------------------------------------
/cap12/Mockeando/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/cap12/Mockeando/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.linkedin.learning
6 | moqueando
7 | 0.0.1-SNAPSHOT
8 | jar
9 |
10 | moqueando
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 |
20 | org.junit
21 | junit5-engine
22 | 5.0.0-ALPHA
23 |
24 |
25 |
26 |
27 | org.mockito
28 | mockito-junit-jupiter
29 | 3.4.4
30 | test
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/cap12/Mockeando/src/main/java/cap12/mockeando/SuperCalculadora.java:
--------------------------------------------------------------------------------
1 | package cap12.mockeando;
2 |
3 | public interface SuperCalculadora {
4 | double raiz(int num);
5 | }
6 |
--------------------------------------------------------------------------------
/cap12/Mockeando/src/main/java/cap12/mockeando/SuperCalculadoraImpl.java:
--------------------------------------------------------------------------------
1 | package cap12.mockeando;
2 |
3 | public class SuperCalculadoraImpl implements SuperCalculadora {
4 |
5 | @Override
6 | public double raiz(int num) {
7 | // TODO Apéndice de método generado automáticamente
8 | return 0;
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/cap12/Mockeando/src/test/java/cap12/mockeando/SuperCalculadoraTest.java:
--------------------------------------------------------------------------------
1 | package cap12.mockeando;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 | import org.junit.jupiter.api.extension.ExtendWith;
7 | import org.mockito.Mock;
8 | import org.mockito.Mockito;
9 | import org.mockito.junit.jupiter.MockitoExtension;
10 |
11 | @ExtendWith(MockitoExtension.class)
12 | class SuperCalculadoraTest {
13 |
14 | @Mock
15 | SuperCalculadora sc;
16 |
17 | @Test
18 | final void test() {
19 | sc = new SuperCalculadoraImpl();
20 | Mockito.when(sc.raiz(4)).thenReturn(2.0);
21 |
22 | double res = sc.raiz(4);
23 | assertEquals(2.0, res);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/cap12/TestUnitarios/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/cap12/TestUnitarios/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | TestUnitarios
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/cap12/TestUnitarios/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/cap12/TestUnitarios/src/cap12/Calculadora.java:
--------------------------------------------------------------------------------
1 | package cap12;
2 |
3 | public class Calculadora {
4 | public static int suma(int a, int b) {
5 | return a + b;
6 | }
7 |
8 | public static int resta(int a, int b) {
9 | return a + b;
10 | }
11 |
12 | public static int multiplica(int a, int b) {
13 | return a * b;
14 | }
15 |
16 | public static int divide(int a, int b)
17 | {
18 | return a / b;
19 | }
20 |
21 | public static int divideB(int a, int b) {
22 | if (b == 0) {
23 | throw new IllegalArgumentException("No podemos dividir entre cero.");
24 | }
25 | return a / b;
26 | }
27 |
28 | public static int divideC(int a, int b) throws ExcepcionPropia {
29 | if (b == 0) {
30 | throw new ExcepcionPropia("No podemos dividir entre cero.");
31 | }
32 | return a / b;
33 | }
34 | }
--------------------------------------------------------------------------------
/cap12/TestUnitarios/src/cap12/ExcepcionPropia.java:
--------------------------------------------------------------------------------
1 | package cap12;
2 |
3 | public class ExcepcionPropia extends Exception {
4 |
5 | public ExcepcionPropia() {
6 | super();
7 | }
8 |
9 | public ExcepcionPropia(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
10 | super(message, cause, enableSuppression, writableStackTrace);
11 | }
12 |
13 | public ExcepcionPropia(String message, Throwable cause) {
14 | super(message, cause);
15 | }
16 |
17 | public ExcepcionPropia(String message) {
18 | super(message);
19 | }
20 |
21 | public ExcepcionPropia(Throwable cause) {
22 | super(cause);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/cap12/TestUnitarios/test/cap12/CalculadoraTest.java:
--------------------------------------------------------------------------------
1 | package cap12;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class CalculadoraTest {
8 |
9 | @Test
10 | void testSuma1() {
11 | int res = Calculadora.suma(2, 3);
12 | assertEquals(5, res);
13 | }
14 |
15 | @Test
16 | void testSuma2() {
17 | int algo = 8;
18 | int res = Calculadora.suma(0, algo);
19 | assertEquals(algo, res);
20 | }
21 |
22 | @Test
23 | void testSuma3() {
24 | int algo = 7;
25 | int res = Calculadora.suma(algo, 0);
26 | assertEquals(algo, res);
27 | }
28 |
29 | @Test
30 | void testSuma4() {
31 | int res = Calculadora.suma(0, 0);
32 | assertEquals(0, res);
33 | }
34 |
35 | @Test
36 | void testSuma5() {
37 | int algo = 3;
38 | int res = Calculadora.suma(algo, -algo);
39 | assertEquals(0, res);
40 | }
41 |
42 | @Test
43 | void testSuma6() {
44 | int algo = 5;
45 | int res = Calculadora.suma(-algo, algo);
46 | assertEquals(0, res);
47 | }
48 |
49 | @Test
50 | void testSuma7() {
51 | int a = 2;
52 | int b = 3;
53 | assertEquals(Calculadora.suma(a, b), Calculadora.suma(b, a));
54 | }
55 |
56 | @Test
57 | void testResta1() {
58 | int res = Calculadora.resta(8, 3);
59 | assertEquals(5, res);
60 | }
61 |
62 | @Test
63 | void testResta2() {
64 | int algo = 3;
65 | int res = Calculadora.resta(0, algo);
66 | assertEquals(-algo, res);
67 | }
68 |
69 | @Test
70 | void testResta3() {
71 | int algo = 8;
72 | int res = Calculadora.resta(algo, 0);
73 | assertEquals(algo, res);
74 | }
75 |
76 | @Test
77 | void testResta4() {
78 | int res = Calculadora.resta(0, 0);
79 | assertEquals(0, res);
80 | }
81 |
82 | @Test
83 | void testResta5() {
84 | int algo = 7;
85 | int res = Calculadora.resta(algo, algo);
86 | assertEquals(0, res);
87 | }
88 |
89 | @Test
90 | void testResta6() {
91 | int algo = 7;
92 | int res = Calculadora.resta(algo, -algo);
93 | assertEquals(2 * algo, res);
94 | }
95 |
96 | @Test
97 | void testResta7() {
98 | int a = 3;
99 | int b = 2;
100 | assertNotEquals(Calculadora.resta(a, b), Calculadora.resta(b, a));
101 | }
102 |
103 | @Test
104 | void testMultiplica1() {
105 | int res = Calculadora.multiplica(2, 3);
106 | assertEquals(6, res);
107 | }
108 |
109 | @Test
110 | void testMultiplica2() {
111 | int algo = 9;
112 | int res = Calculadora.multiplica(algo, 1);
113 | assertEquals(algo, res);
114 | }
115 |
116 | @Test
117 | void testMultiplica3() {
118 | int algo = 9;
119 | int res = Calculadora.multiplica(1, algo);
120 | assertEquals(algo, res);
121 | }
122 |
123 | @Test
124 | void testMultiplica4() {
125 | int res = Calculadora.multiplica(1, 1);
126 | assertEquals(1, res);
127 | }
128 |
129 | @Test
130 | void testMultiplica5() {
131 | int algo = 4;
132 | int res = Calculadora.multiplica(algo, 0);
133 | assertEquals(0, res);
134 | }
135 |
136 | @Test
137 | void testMultiplica6() {
138 | int algo = 4;
139 | int res = Calculadora.multiplica(0, algo);
140 | assertEquals(0, res);
141 | }
142 |
143 | @Test
144 | void testMultiplica7() {
145 | int res = Calculadora.multiplica(0, 0);
146 | assertEquals(0, res);
147 | }
148 |
149 | @Test
150 | void testMultiplica8() {
151 | assertTrue(Calculadora.multiplica(1, 1) > 0);
152 | assertTrue(Calculadora.multiplica(-1, -1) > 0);
153 | assertTrue(Calculadora.multiplica(1, -1) < 0);
154 | assertTrue(Calculadora.multiplica(-1, 1) < 0);
155 | }
156 |
157 | @Test
158 | void testDivide1() {
159 | int res = Calculadora.divide(8, 2);
160 | assertEquals(4, res);
161 | }
162 |
163 | @Test
164 | void testDivide2() {
165 | int algo = 7;
166 | int res = Calculadora.divide(algo, 1);
167 | assertEquals(algo, res);
168 | }
169 |
170 | @Test
171 | void testDivide3() {
172 | int a = 3;
173 | int b = 5;
174 | int res = Calculadora.divide(Calculadora.multiplica(a, b), b);
175 | assertEquals(a, res);
176 | }
177 |
178 | @Test
179 | void testDivide4() {
180 | int a = 3;
181 | int b = 5;
182 | int res = Calculadora.divide(Calculadora.multiplica(a, b) + 1, b);
183 | assertEquals(a, res);
184 | }
185 |
186 | @Test
187 | void testDivide5() {
188 | int algo = 7;
189 | int res = Calculadora.divide(1, algo);
190 | assertEquals(0, res);
191 | }
192 |
193 | @Test
194 | void testDivide6() {
195 | int res = Calculadora.divide(1, 1);
196 | assertEquals(1, res);
197 | }
198 |
199 | @Test
200 | void testDivide7() {
201 | int algo = 7;
202 | assertThrows(ArithmeticException.class, () -> {
203 | Calculadora.divide(algo, 0);
204 | });
205 | }
206 |
207 | @Test
208 | void testDivide7A() {
209 | int algo = 7;
210 | try {
211 | int res = Calculadora.divide(algo, 0);
212 | fail("Aquí no debería llegar");
213 | } catch (ArithmeticException ae) {
214 | assertTrue(true);
215 | } catch (Throwable t) {
216 | fail("No debería lanzar ningún throwable");
217 | }
218 | }
219 |
220 | @Test
221 | void testDivide7B() {
222 | int algo = 7;
223 | assertThrows(IllegalArgumentException.class, () -> {
224 | Calculadora.divideB(algo, 0);
225 | });
226 | try {
227 | int res = Calculadora.divideB(algo, 0);
228 | fail("Aquí no debería llegar");
229 | } catch (IllegalArgumentException ae) {
230 | assertTrue(true);
231 | } catch (Throwable t) {
232 | fail("No debería lanzar ningún throwable");
233 | }
234 | }
235 |
236 | @Test
237 | void testDivide7C() {
238 | int algo = 7;
239 | assertThrows(ExcepcionPropia.class, () -> {
240 | Calculadora.divideC(algo, 0);
241 | });
242 | try {
243 | int res = Calculadora.divideC(algo, 0);
244 | fail("Aquí no debería llegar");
245 | } catch (ExcepcionPropia ep) {
246 | assertTrue(true);
247 | assertEquals("No podemos dividir entre cero.", ep.getMessage());
248 | } catch (Throwable t) {
249 | fail("No debería lanzar ningún throwable");
250 | }
251 | }
252 | }
253 |
--------------------------------------------------------------------------------
/cap13/trazas/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/cap13/trazas/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | trazas
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/cap13/trazas/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/cap13/trazas/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
3 | org.eclipse.jdt.core.compiler.compliance=1.5
4 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
5 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
6 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
7 | org.eclipse.jdt.core.compiler.release=disabled
8 | org.eclipse.jdt.core.compiler.source=1.5
9 |
--------------------------------------------------------------------------------
/cap13/trazas/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/cap13/trazas/pom.xml:
--------------------------------------------------------------------------------
1 |
4 | 4.0.0
5 |
6 | cap13
7 | trazas
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | trazas
12 | http://maven.apache.org
13 |
14 |
15 | UTF-8
16 |
17 |
18 |
19 |
20 | junit
21 | junit
22 | 3.8.1
23 | test
24 |
25 |
26 |
27 | org.apache.logging.log4j
28 | log4j-core
29 | 2.17.1
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/cap13/trazas/src/main/java/cap13/trazas/App.java:
--------------------------------------------------------------------------------
1 | package cap13.trazas;
2 |
3 | import java.text.MessageFormat;
4 |
5 | import org.apache.logging.log4j.Level;
6 | import org.apache.logging.log4j.LogManager;
7 | import org.apache.logging.log4j.Logger;
8 |
9 | public class App {
10 | private static Logger logger = LogManager.getLogger(App.class);
11 |
12 | public static void main(String[] args) {
13 | logger.fatal(MessageFormat.format("Nivel actual del log: {0}", logger.getLevel()));
14 |
15 | logger.trace("hola trace");
16 | logger.debug("hola debug");
17 | logger.info("hola info");
18 | logger.warn("hola warn");
19 | logger.error("hola error");
20 | logger.fatal("hola fatal");
21 |
22 | logger.log(Level.INFO, "otra forma de hacerlo");
23 | if (logger.isInfoEnabled()) {
24 | logger.info(calculoPesado(1));
25 | }
26 | logger.info(calculoPesado(2));
27 | }
28 |
29 | public static String calculoPesado(int n) {
30 | String mensaje = "*** Aquí hacemos algo muy muy pesado " + n;
31 | System.out.println(mensaje);
32 | return mensaje;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/cap13/trazas/src/main/resources/log4j2.properties:
--------------------------------------------------------------------------------
1 | status = warn
2 |
3 | # Log to console and rolling file
4 | logger.app.name = cap13.trazas
5 | logger.app.level = trace
6 | logger.app.additivity = false
7 | logger.app.appenderRef.rolling.ref = LogToRollingFile
8 | logger.app.appenderRef.console.ref = LogToConsole
9 |
10 | appender.console.type = Console
11 | appender.console.name = LogToConsole
12 | appender.console.layout.type = PatternLayout
13 | appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} [%-5level] - %msg%n
14 |
15 | # Rotate log file
16 | appender.rolling.type = RollingFile
17 | appender.rolling.name = LogToRollingFile
18 | appender.rolling.fileName = logs/trazas.log
19 | appender.rolling.filePattern = logs/$${date:yyyy-MM}/trazas-%d{yyyyMMdd}-%i.log.gz
20 | appender.rolling.layout.type = PatternLayout
21 | appender.rolling.layout.pattern = %p %C{1.} > %m%n
22 | appender.rolling.policies.type = Policies
23 | appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
24 | appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
25 | appender.rolling.policies.size.size=1KB
26 | appender.rolling.strategy.type = DefaultRolloverStrategy
27 | appender.rolling.strategy.max = 10
28 |
29 | rootLogger.level = warn
30 | rootLogger.appenderRef.stdout.ref = LogToConsole
--------------------------------------------------------------------------------
/cap14/recordsManager/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/cap14/recordsManager/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | recordsManager
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/cap14/recordsManager/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/cap14/recordsManager/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.8
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
12 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
13 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
14 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
15 | org.eclipse.jdt.core.compiler.release=disabled
16 | org.eclipse.jdt.core.compiler.source=1.8
17 |
--------------------------------------------------------------------------------
/cap14/recordsManager/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/cap14/recordsManager/pom.xml:
--------------------------------------------------------------------------------
1 |
4 | 4.0.0
5 |
6 | cap14
7 | recordsManager
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | recordsManager
12 | http://maven.apache.org
13 |
14 |
15 | UTF-8
16 |
17 |
18 |
19 |
20 |
21 | org.apache.logging.log4j
22 | log4j-core
23 | 2.17.1
24 |
25 |
26 | org.junit.jupiter
27 | junit-jupiter-engine
28 | 5.7.0
29 | test
30 |
31 |
32 |
33 | org.junit.jupiter
34 | junit-jupiter-api
35 | 5.7.0
36 | test
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/cap14/recordsManager/puntuaciones.txt:
--------------------------------------------------------------------------------
1 | Margarita 12345
2 | Pedro 2134
3 | Juanjo 165
4 | An 123456
5 | Li 12
6 | Alex 987
--------------------------------------------------------------------------------
/cap14/recordsManager/src/main/java/cap14/recordsManager/PlayerNameTooShortException.java:
--------------------------------------------------------------------------------
1 | package cap14.recordsManager;
2 |
3 | public class PlayerNameTooShortException extends Exception {
4 | private String name;
5 |
6 | public PlayerNameTooShortException(String name) {
7 | super(name);
8 | this.name = name;
9 | }
10 |
11 | public String getName() {
12 | return name;
13 | }
14 |
15 | @Override
16 | public String getMessage() {
17 | return "El nombre del jugador (" + name + ") es demasiado corto.";
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/cap14/recordsManager/src/main/java/cap14/recordsManager/RecordsManager.java:
--------------------------------------------------------------------------------
1 | package cap14.recordsManager;
2 |
3 | import java.io.File;
4 | import java.io.FileNotFoundException;
5 | import java.io.FileOutputStream;
6 | import java.io.IOException;
7 | import java.util.HashMap;
8 | import java.util.Map;
9 | import java.util.Random;
10 | import java.util.Scanner;
11 |
12 | import org.apache.logging.log4j.LogManager;
13 | import org.apache.logging.log4j.Logger;
14 |
15 | public class RecordsManager {
16 | private static Logger logger = LogManager.getLogger(RecordsManager.class);
17 |
18 | private static final String INPUT_FILE = "puntuaciones.txt";
19 | private static final String OUTPUT_FILE = "records.txt";
20 | private static final int MIN_NAME_LENGTH = 6;
21 | private static final int MIN_SCORE = 1000;
22 |
23 | private static Random r = new Random();
24 |
25 | public static void main(String[] args) {
26 |
27 | /// (9) Cerramos el scanner del fichero de entrada
28 | // usando el try con recursos nos aseguramos de que el scanner se cierra
29 | try (Scanner sInput = new Scanner(new File(INPUT_FILE))) {
30 | Map players = new HashMap<>();
31 |
32 | /// (1) Leer fichero de entrada
33 | while (sInput.hasNextLine()) {
34 | String line = sInput.nextLine();
35 | String[] data = line.split(" ");
36 | try {
37 | String name = data[0];
38 | int score = Integer.parseInt(data[1]);
39 | /// (7) Tratamos los problemas de validación del jugado
40 | try {
41 | validateName(name);
42 | } catch (PlayerNameTooShortException pntse) {
43 | logger.warn(pntse.getMessage());
44 | name = generateNewName(name);
45 | System.out.println(" El nuevo nombre de usuario es " + name);
46 | }
47 | /// (8) Validamos la puntuación
48 | try {
49 | validateScore(name, score);
50 | } catch (ScoreTooLowException stle) {
51 | logger.error(stle.getMessage());
52 | System.out.println(" Jugador descartado");
53 | continue;
54 | }
55 | players.put(name, score);
56 | logger.info("Línea tratada correctamente: " + name + " - " + score);
57 | } catch (IndexOutOfBoundsException | NumberFormatException e) {
58 | logger.error("La línea no contiene los datos esperados ("
59 | + line + ")");
60 | // y seguimos con el while
61 | }
62 | }
63 |
64 | /// (2) Mostrar por consola todos los datos guardados
65 | System.out.println("Datos procesados: ");
66 | for (String name : players.keySet()) {
67 | System.out.println(name + ":\t" + players.get(name));
68 | }
69 |
70 | /// (3) Pedir confirmación al usuario
71 | System.out.println("¿Son correctos? [S]i/[N]o");
72 | /// (10) Cerramos el escáner de consola
73 | String answer;
74 | try (Scanner sConsole = new Scanner(System.in)) {
75 | answer = sConsole.next();
76 | }
77 | boolean confirmed = answer.equalsIgnoreCase("S");
78 |
79 | /// (4) Escribir a fichero
80 | if (confirmed) {
81 | System.out.println("Procedemos al volcado de datos del fichero...");
82 | /// (11) Cerramos el fichero de salida y controlamos IOE
83 | try (FileOutputStream fos = new FileOutputStream(OUTPUT_FILE)) {
84 | for (String name : players.keySet()) {
85 | fos.write((name + " " + players.get(name) + "\n").getBytes());
86 | }
87 | } catch (IOException ioe) {
88 | logger.error("No hemos podido escribir los resultados en el " +
89 | "fichero porque algo ha fallado: " + ioe.getMessage());
90 | }
91 | }
92 | } catch (FileNotFoundException fnfe) {
93 | logger.error("No podemos ejecutar el programa porque no se encuentra "
94 | + "el fichero de entrada esperado: " + INPUT_FILE);
95 | }
96 | }
97 |
98 | protected static void validateName(String name)
99 | throws PlayerNameTooShortException {
100 | /// (5) Validamos la longitud del nombre
101 | if (name.length() < MIN_NAME_LENGTH) {
102 | throw new PlayerNameTooShortException(name);
103 | }
104 | }
105 |
106 | protected static void validateScore(String name, int score)
107 | throws ScoreTooLowException {
108 | /// (6) Validamos la puntuación mínima
109 | if (score < MIN_SCORE) {
110 | throw new ScoreTooLowException(name, score);
111 | }
112 | }
113 |
114 | protected static String generateNewName(String name) {
115 | int randomSize = MIN_NAME_LENGTH - name.length();
116 | for (int i = 0; i < randomSize; i ++) {
117 | int randomNum = r.nextInt(10);
118 | name += randomNum;
119 | }
120 | return name;
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/cap14/recordsManager/src/main/java/cap14/recordsManager/ScoreTooLowException.java:
--------------------------------------------------------------------------------
1 | package cap14.recordsManager;
2 |
3 | public class ScoreTooLowException extends Exception {
4 |
5 | private String name;
6 | private int score;
7 |
8 | public ScoreTooLowException(String name, int score) {
9 | this.name = name;
10 | this.score = score;
11 | }
12 |
13 | public String getName() {
14 | return name;
15 | }
16 |
17 | public int getScore() {
18 | return score;
19 | }
20 |
21 | @Override
22 | public String getMessage() {
23 | return "El usuario " + name + " tiene menos puntos ("
24 | + score + ") de los requeridos.";
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/cap14/recordsManager/src/main/resources/log4j2.properties:
--------------------------------------------------------------------------------
1 | status = warn
2 |
3 | # Log to console and rolling file
4 | logger.app.name = cap14.trazas
5 | logger.app.level = trace
6 | logger.app.additivity = false
7 | logger.app.appenderRef.rolling.ref = LogToRollingFile
8 | logger.app.appenderRef.console.ref = LogToConsole
9 |
10 | appender.console.type = Console
11 | appender.console.name = LogToConsole
12 | appender.console.layout.type = PatternLayout
13 | appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} [%-5level] - %msg%n
14 |
15 | # Rotate log file
16 | appender.rolling.type = RollingFile
17 | appender.rolling.name = LogToRollingFile
18 | appender.rolling.fileName = logs/trazas.log
19 | appender.rolling.filePattern = logs/$${date:yyyy-MM}/trazas-%d{yyyyMMdd}-%i.log.gz
20 | appender.rolling.layout.type = PatternLayout
21 | appender.rolling.layout.pattern = %p %C{1.} > %m%n
22 | appender.rolling.policies.type = Policies
23 | appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
24 | appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
25 | appender.rolling.policies.size.size=1KB
26 | appender.rolling.strategy.type = DefaultRolloverStrategy
27 | appender.rolling.strategy.max = 10
28 |
29 | rootLogger.level = warn
30 | rootLogger.appenderRef.stdout.ref = LogToConsole
--------------------------------------------------------------------------------
/cap14/recordsManager/src/test/java/cap14/recordsManager/RecordsManagerTest.java:
--------------------------------------------------------------------------------
1 | package cap14.recordsManager;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertNotEquals;
5 | import static org.junit.jupiter.api.Assertions.assertTrue;
6 | import static org.junit.jupiter.api.Assertions.fail;
7 |
8 | import org.junit.jupiter.api.Test;
9 |
10 | class RecordsManagerTest {
11 |
12 | private static final String ALEX = "Alex";
13 | private static final String ALEJANDRO = "Alejandro";
14 |
15 | @Test
16 | void validateNameLargoTest() {
17 | try {
18 | RecordsManager.validateName(ALEJANDRO);
19 | assertTrue(true);
20 | } catch (PlayerNameTooShortException e) {
21 | fail(e.getMessage());
22 | }
23 | }
24 |
25 | @Test
26 | void validateNameCortoTest() {
27 | try {
28 | RecordsManager.validateName(ALEX);
29 | fail("Debería haber fallado, " + ALEX + " es corto");
30 | } catch (PlayerNameTooShortException e) {
31 | assertTrue(true);
32 | assertTrue(e.getMessage().contains(ALEX));
33 | }
34 | }
35 |
36 | @Test
37 | void validateNameCasiTest() {
38 | String nombre = "Alejo";
39 | try {
40 | RecordsManager.validateName(nombre);
41 | fail("Debería haber fallado, " + nombre + " es corto");
42 | } catch (PlayerNameTooShortException e) {
43 | assertTrue(true);
44 | assertTrue(e.getMessage().contains(nombre));
45 | }
46 | }
47 |
48 | @Test
49 | void validateNameExactoTest() {
50 | String nombre = "Alejor";
51 | try {
52 | RecordsManager.validateName(nombre);
53 | assertTrue(true);
54 | } catch (PlayerNameTooShortException e) {
55 | fail(e.getMessage());
56 | }
57 | }
58 |
59 | @Test
60 | void validateScore1000Test() {
61 | try {
62 | RecordsManager.validateScore(ALEJANDRO, 1000);
63 | assertTrue(true);
64 | } catch (ScoreTooLowException e) {
65 | fail(e.getMessage());
66 | }
67 | }
68 |
69 | @Test
70 | void validateScore999Test() {
71 | try {
72 | RecordsManager.validateScore(ALEJANDRO, 999);
73 | fail("Debería haber fallado, 999 son pocos puntos");
74 | } catch (ScoreTooLowException e) {
75 | assertTrue(e.getMessage().contains(ALEJANDRO));
76 | assertTrue(e.getMessage().contains("999"));
77 | }
78 | }
79 |
80 | @Test
81 | void generateNewNameLargoTest() {
82 | String nuevoNombre = RecordsManager.generateNewName(ALEJANDRO);
83 | assertEquals(ALEJANDRO, nuevoNombre);
84 | }
85 |
86 | @Test
87 | void generateNewNameCortoTest() {
88 | String nuevoNombre = RecordsManager.generateNewName(ALEX);
89 | assertNotEquals(ALEX, nuevoNombre);
90 | assertTrue(nuevoNombre.contains(ALEX));
91 | assertTrue(nuevoNombre.startsWith(ALEX));
92 | String numero = nuevoNombre.substring(ALEX.length());
93 | assertTrue(Integer.valueOf(numero) > 0);
94 | assertEquals(6, nuevoNombre.length());
95 | }
96 |
97 | @Test
98 | void generateNewNameVacioTest() {
99 | String nuevoNombre = RecordsManager.generateNewName("");
100 | assertNotEquals("", nuevoNombre);
101 | assertTrue(Integer.valueOf(nuevoNombre) > 0);
102 | assertEquals(6, nuevoNombre.length());
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/cap15/Estructuras/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/cap15/Estructuras/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Estructuras
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/cap15/Estructuras/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/cap15/Estructuras/resources/ejercicio15_05.properties:
--------------------------------------------------------------------------------
1 | mensaje = {0} came out {1} times\n
2 |
3 |
--------------------------------------------------------------------------------
/cap15/Estructuras/resources/ejercicio15_05_zh_CN.properties:
--------------------------------------------------------------------------------
1 | mensaje = {0}\u51FA\u6765\u4E86{1}\u6B21\n
--------------------------------------------------------------------------------
/cap15/Estructuras/resources/ejercicio15_05_zh_TW.properties:
--------------------------------------------------------------------------------
1 | mensaje = {0}\u51FA\u4F86\u4E86{1}\u6B21\n
--------------------------------------------------------------------------------
/cap15/Estructuras/resources/estructuras_en.properties:
--------------------------------------------------------------------------------
1 | mensaje = This is a {1} {0}.
2 | color = red
3 | objeto = car
4 |
--------------------------------------------------------------------------------
/cap15/Estructuras/resources/estructuras_es.properties:
--------------------------------------------------------------------------------
1 | mensaje = Es un {0} {1}.
2 | color = rojo
3 | objeto = coche
4 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Ejercicio15_01.java:
--------------------------------------------------------------------------------
1 | public class Ejercicio15_01 {
2 | private static final char COMA = ',';
3 | public static final String TEXTO = "Con diez cañones por banda, "
4 | + "viento en popa a toda vela, no corta el mar, sino vuela "
5 | + "un velero bergantín";
6 |
7 | public static void main(String[] args) {
8 | int res = cuentaComas(TEXTO);
9 | System.out.println("El texto tiene " + res + " comas.");
10 | }
11 |
12 | private static int cuentaComas(String texto) {
13 | int res = 0;
14 | int pos = texto.indexOf(COMA);
15 | while (pos != -1) {
16 | res ++;
17 | pos = texto.indexOf(COMA, pos+1);
18 | }
19 |
20 | return res;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Ejercicio15_02.java:
--------------------------------------------------------------------------------
1 | import java.util.StringTokenizer;
2 |
3 | public class Ejercicio15_02 {
4 | private static final String COMA = ",";
5 | public static final String TEXTO = "Con diez cañones por banda, "
6 | + "viento en popa a toda vela, no corta el mar, sino vuela "
7 | + "un velero bergantín";
8 |
9 | public static void main(String[] args) {
10 | String[] res = separa(TEXTO);
11 | for (String string : res) {
12 | System.out.println(string);
13 | }
14 | }
15 |
16 | private static String[] separa(String texto) {
17 | StringTokenizer st = new StringTokenizer(texto, COMA);
18 | String[] res = new String[st.countTokens()];
19 | int i = 0;
20 | while (st.hasMoreTokens()) {
21 | res[i++] = st.nextToken().trim();
22 | }
23 | return res;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Ejercicio15_03.java:
--------------------------------------------------------------------------------
1 | import java.time.LocalDate;
2 | import java.time.Month;
3 | import java.time.Period;
4 |
5 | public class Ejercicio15_03 {
6 | public static void main(String[] args) {
7 | LocalDate miNacimiento = LocalDate.of(1980, Month.JULY, 1);
8 | LocalDate now = LocalDate.now();
9 | Period edad = Period.between(miNacimiento, now);
10 | System.out.println("Tengo " + edad.getYears() + " años, " + edad.getMonths()
11 | + " meses y " + edad.getDays() + " días.");
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Ejercicio15_04.java:
--------------------------------------------------------------------------------
1 | import java.text.MessageFormat;
2 | import java.util.ArrayList;
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Map;
6 | import java.util.Map.Entry;
7 | import java.util.Random;
8 |
9 | public class Ejercicio15_04 {
10 | private static final Random RND = new Random();
11 | private static final int NUM_LETRAS = 26;
12 | private static final char PRIMERA_LETRA = 'a';
13 | private static final int TAM = 1000;
14 |
15 | public static void main(String[] args) {
16 | List lista = generaLista();
17 | Map mapa = cuentaLetras(lista);
18 | pintaMapa(mapa);
19 | }
20 |
21 | private static void pintaMapa(Map mapa) {
22 | StringBuilder sb = new StringBuilder();
23 | for (Entry entry : mapa.entrySet()) {
24 | String m = MessageFormat.format("{0} ha salido {1} veces\n", entry.getKey(), entry.getValue());
25 | sb.append(m);
26 | }
27 | System.out.println(sb.toString());
28 | }
29 |
30 | private static Map cuentaLetras(List lista) {
31 | Map mapa = new HashMap<>();
32 | for (String silaba : lista) {
33 | Character c = getPrimero(silaba);
34 | Integer cont = mapa.get(c);
35 | if (cont == null) {
36 | cont = 0;
37 | }
38 | mapa.put(c, ++cont);
39 | }
40 | return mapa;
41 | }
42 |
43 | private static Character getPrimero(String silaba) {
44 | return silaba.charAt(0);
45 | }
46 |
47 | private static List generaLista() {
48 | List lista = new ArrayList<>(TAM);
49 | for (int i = 0; i < TAM; i++) {
50 | lista.add(generaSilaba());
51 | }
52 | return lista;
53 | }
54 |
55 | private static String generaSilaba() {
56 | return generaLetra() + generaLetra();
57 | }
58 |
59 | private static String generaLetra() {
60 | char c = (char) (PRIMERA_LETRA + RND.nextInt(NUM_LETRAS));
61 | return Character.toString(c);
62 | }
63 | }
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Ejercicio15_05.java:
--------------------------------------------------------------------------------
1 | import java.text.MessageFormat;
2 | import java.util.ArrayList;
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Locale;
6 | import java.util.Map;
7 | import java.util.Map.Entry;
8 | import java.util.Random;
9 | import java.util.ResourceBundle;
10 |
11 | public class Ejercicio15_05 {
12 | private static final Random RND = new Random();
13 | private static final int NUM_LETRAS = 26;
14 | private static final char PRIMERA_LETRA = 'a';
15 | private static final int TAM = 10;
16 |
17 | public static void main(String[] args) {
18 | Locale.setDefault(Locale.CHINA);
19 | // Locale.setDefault(Locale.TAIWAN);
20 |
21 | List lista = generaLista();
22 | Map mapa = cuentaLetras(lista);
23 | pintaMapa(mapa);
24 | }
25 |
26 | private static void pintaMapa(Map mapa) {
27 | ResourceBundle bundle = ResourceBundle.getBundle("ejercicio15_05");
28 | String mensaje = bundle.getString("mensaje");
29 | StringBuilder sb = new StringBuilder();
30 | for (Entry entry : mapa.entrySet()) {
31 | String m = MessageFormat.format(mensaje, entry.getKey(), entry.getValue());
32 | sb.append(m);
33 | }
34 | System.out.println(sb.toString());
35 | }
36 |
37 | private static Map cuentaLetras(List lista) {
38 | Map mapa = new HashMap<>();
39 | for (String silaba : lista) {
40 | Character c = getPrimero(silaba);
41 | Integer cont = mapa.get(c);
42 | if (cont == null) {
43 | cont = 0;
44 | }
45 | mapa.put(c, ++cont);
46 | }
47 | return mapa;
48 | }
49 |
50 | private static Character getPrimero(String silaba) {
51 | return silaba.charAt(0);
52 | }
53 |
54 | private static List generaLista() {
55 | List lista = new ArrayList<>(TAM);
56 | for (int i = 0; i < TAM; i++) {
57 | lista.add(generaSilaba());
58 | }
59 | return lista;
60 | }
61 |
62 | private static String generaSilaba() {
63 | return generaLetra() + generaLetra();
64 | }
65 |
66 | private static String generaLetra() {
67 | char c = (char) (PRIMERA_LETRA + RND.nextInt(NUM_LETRAS));
68 | return Character.toString(c);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/FechasNuevas.java:
--------------------------------------------------------------------------------
1 | import java.time.*;
2 |
3 | public class FechasNuevas {
4 | public static void main(String[] args) {
5 | Instant instant = Instant.now();
6 | System.out.println("Instant: " + instant);
7 | LocalDate localDate = LocalDate.now().plusMonths(1);
8 | System.out.println("LocalDate +1m: " + localDate);
9 | LocalTime localTime = LocalTime.now();
10 | System.out.println("LocalTime: " + localTime);
11 | LocalDateTime localDateTime = LocalDateTime.now();
12 | System.out.println("LocalDateTime: " + localDateTime);
13 | ZonedDateTime zonedDateTime = ZonedDateTime.now();
14 | System.out.println("ZonedDateTime: " + zonedDateTime);
15 | Duration duration = Duration.ofDays(1);
16 | System.out.println("Duration: " + duration);
17 | LocalDate inicio = LocalDate.of(2019, Month.JULY, 23);
18 | LocalDate fin = LocalDate.of(2023, Month.APRIL, 18);
19 | Period period = Period.between(inicio, fin);
20 | System.out.println("Period: " + period);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/FechasViejas.java:
--------------------------------------------------------------------------------
1 | import java.text.DateFormat;
2 | import java.text.SimpleDateFormat;
3 | import java.util.Calendar;
4 | import java.util.Date;
5 | import java.util.GregorianCalendar;
6 | import java.util.Locale;
7 |
8 | public class FechasViejas {
9 | public static void main(String[] args) {
10 | long ahora = System.currentTimeMillis();
11 | System.out.println("Ahora: " + ahora);
12 | Date fecha = new Date();
13 | System.out.println("Fecha: " + fecha);
14 | Calendar cal = GregorianCalendar.getInstance();
15 | cal.set(2020, 0, 1, 2, 3, 4); // los meses también empiezan en cero
16 | Date fechaCal = cal.getTime();
17 | System.out.println("Calendar: " + fechaCal);
18 | DateFormat df = new SimpleDateFormat("EEEE, d MMMM yyyy HH:mm:ss Z", Locale.GERMAN);
19 | System.out.println("Formateo: " + df.format(fechaCal));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Mensajes.java:
--------------------------------------------------------------------------------
1 | import java.text.MessageFormat;
2 | import java.util.Locale;
3 | import java.util.ResourceBundle;
4 |
5 | public class Mensajes {
6 | public static void main(String[] args) {
7 | ResourceBundle bundle = ResourceBundle.getBundle("estructuras", Locale.UK);
8 | // ResourceBundle bundle = ResourceBundle.getBundle("estructuras");
9 | String mensaje = bundle.getString("mensaje");
10 | String objeto = bundle.getString("objeto");
11 | String color = bundle.getString("color");
12 |
13 | System.out.println(MessageFormat.format(mensaje, objeto, color));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Monedas.java:
--------------------------------------------------------------------------------
1 | import java.text.NumberFormat;
2 | import java.util.Locale;
3 |
4 | public class Monedas {
5 | public static void main(String[] args) {
6 | double precio = 1234.56;
7 | NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
8 | System.out.println("Precio en Francia: " + nf.format(precio));
9 | NumberFormat nf2 = NumberFormat.getCurrencyInstance(Locale.US);
10 | System.out.println("Precio en EE. UU.: " + nf2.format(precio));
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/cap15/Estructuras/src/Numeros.java:
--------------------------------------------------------------------------------
1 | import java.math.BigInteger;
2 |
3 | public class Numeros {
4 | public static void main(String[] args) {
5 | BigInteger numGrande = new BigInteger("12345678901234567890123456789");
6 | System.out.println("Número grande: " + numGrande);
7 | BigInteger masUno = numGrande.add(BigInteger.ONE);
8 | System.out.println("Más uno: " + masUno);
9 | BigInteger alCuadrado = numGrande.multiply(numGrande);
10 | System.out.println("Al cuadrado: " + alCuadrado);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/cap16/gestor/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/cap16/gestor/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | gestor
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/cap16/gestor/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/cap16/gestor/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
13 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
14 | org.eclipse.jdt.core.compiler.release=disabled
15 | org.eclipse.jdt.core.compiler.source=1.8
16 |
--------------------------------------------------------------------------------
/cap16/gestor/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/cap16/gestor/.settings/org.sonarlint.eclipse.core.prefs:
--------------------------------------------------------------------------------
1 | autoEnabled=false
2 | eclipse.preferences.version=1
3 |
--------------------------------------------------------------------------------
/cap16/gestor/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | cap16.orm
6 | gestor
7 | 0.0.1-SNAPSHOT
8 | jar
9 |
10 | sooper
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 |
20 | mysql
21 | mysql-connector-java
22 | 8.0.28
23 |
24 |
25 |
26 | org.hibernate
27 | hibernate-agroal
28 | 5.4.16.Final
29 | pom
30 |
31 |
32 |
33 | junit
34 | junit
35 | 3.8.1
36 | test
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/META-INF/persistence.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | org.hibernate.jpa.HibernatePersistenceProvider
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/Albaran.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.FetchType;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import javax.persistence.ManyToOne;
11 | import javax.persistence.Table;
12 |
13 | @Entity
14 | @Table(name = "albaran")
15 | public class Albaran {
16 | private static final String PREFIJO = "ALB-";
17 |
18 | @Id
19 | @GeneratedValue(strategy = GenerationType.IDENTITY)
20 | private int id;
21 | private String referencia;
22 | private LocalDateTime fechaEmision;
23 | private LocalDateTime fechaRecepcion;
24 |
25 | @ManyToOne(fetch = FetchType.LAZY)
26 | private Pedido pedido;
27 |
28 | public Albaran() {
29 |
30 | }
31 |
32 | public Albaran(String refPedido) {
33 | referencia = PREFIJO + refPedido;
34 | fechaEmision = LocalDateTime.now();
35 | }
36 |
37 | public int getId() {
38 | return id;
39 | }
40 |
41 | public void setId(int id) {
42 | this.id = id;
43 | }
44 |
45 | public String getReferencia() {
46 | return referencia;
47 | }
48 |
49 | public void setReferencia(String referencia) {
50 | this.referencia = referencia;
51 | }
52 |
53 | public LocalDateTime getFechaEmision() {
54 | return fechaEmision;
55 | }
56 |
57 | public void setFechaEmision(LocalDateTime fechaEmision) {
58 | this.fechaEmision = fechaEmision;
59 | }
60 |
61 | public LocalDateTime getFechaRecepcion() {
62 | return fechaRecepcion;
63 | }
64 |
65 | public void setFechaRecepcion(LocalDateTime fechaRecepcion) {
66 | this.fechaRecepcion = fechaRecepcion;
67 | }
68 |
69 | public Pedido getPedido() {
70 | return pedido;
71 | }
72 |
73 | public void setPedido(Pedido pedido) {
74 | this.pedido = pedido;
75 | }
76 |
77 | @Override
78 | public String toString() {
79 | return "Albaran [id=" + id + ", referencia=" + referencia + ", fechaEmision=" + fechaEmision
80 | + ", fechaRecepcion=" + fechaRecepcion + "]";
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/App.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
2 |
3 | import java.time.LocalDateTime;
4 | import java.time.temporal.ChronoUnit;
5 | import java.util.List;
6 |
7 | import cap16.orm.gestor.dao.PedidoDao;
8 |
9 | public class App
10 | {
11 | public static void main( String[] args )
12 | {
13 | PedidoDao pedidoDao = new PedidoDao();
14 |
15 | Pedido pedido = new Pedido("001", LocalDateTime.now());
16 | pedidoDao.save(pedido);
17 |
18 | Pedido pedido2 = new Pedido("pedFut", LocalDateTime.now().plus(2, ChronoUnit.DAYS));
19 | pedidoDao.save(pedido2);
20 |
21 | Pedido pedido3 = new Pedido("pedPas", LocalDateTime.now().minus(1, ChronoUnit.WEEKS));
22 | pedidoDao.save(pedido3);
23 |
24 | List pedidos = pedidoDao.getAll();
25 | System.out.println("*** Pedidos: " + pedidos);
26 |
27 | try {
28 | Pedido masReciente = pedidoDao.pedidoMasReciente();
29 | System.out.println("*** Pedido más reciente: " + masReciente);
30 | } catch (NoResultException nre) {
31 | System.out.println("No tienes ningún pedido reciente.");
32 | }
33 |
34 | List pedidosSemanaPasada = pedidoDao.pedidosSemanaPasada();
35 | System.out.println("*** Pedidos de la semana pasada: " + pedidosSemanaPasada);
36 | }
37 | }
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/Factura.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.GenerationType;
6 | import javax.persistence.Id;
7 | import javax.persistence.OneToOne;
8 |
9 | @Entity
10 | public class Factura {
11 |
12 | @Id
13 | @GeneratedValue(strategy = GenerationType.IDENTITY)
14 | private int id;
15 | private String numero;
16 |
17 | @OneToOne(mappedBy = "factura")
18 | private Pedido pedido;
19 |
20 | public Factura() {
21 |
22 | }
23 |
24 | public Factura(Pedido pedido) {
25 | this.numero = PREFIJO + pedido.getReferencia();
26 | this.pedido = pedido;
27 | }
28 |
29 | public int getId() {
30 | return id;
31 | }
32 |
33 | public void setId(int id) {
34 | this.id = id;
35 | }
36 |
37 | public String getNumero() {
38 | return numero;
39 | }
40 |
41 | public void setNumero(String numero) {
42 | this.numero = numero;
43 | }
44 |
45 | public Pedido getPedido() {
46 | return pedido;
47 | }
48 |
49 | public void setPedido(Pedido pedido) {
50 | this.pedido = pedido;
51 | }
52 |
53 | @Override
54 | public String toString() {
55 | return "Factura [id=" + id + ", numero=" + numero + "]";
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/GestorPedidos.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import cap16.orm.gestor.dao.PedidoDao;
6 |
7 | public class GestorPedidos {
8 |
9 | public static void main(String[] args) {
10 | PedidoDao pedidoDao = new PedidoDao();
11 |
12 | Producto libro = new Producto("libJava", "Manual Imprescindible Java");
13 | Producto cuaderno = new Producto("cuaRojo", "Cuaderno rojo");
14 | Producto lapiz = new Producto("lapHB", "Lápiz HB");
15 |
16 | Pedido vueltaAlCole = new Pedido("153947", LocalDateTime.now());
17 | vueltaAlCole.addProducto(libro);
18 | vueltaAlCole.addProducto(cuaderno);
19 | vueltaAlCole.addProducto(lapiz);
20 |
21 | pedidoDao.save(vueltaAlCole);
22 |
23 | Albaran albaran = vueltaAlCole.generaAlbaran();
24 | Factura factura = vueltaAlCole.generaFactura();
25 |
26 | System.out.println("Pedido:\n" + vueltaAlCole);
27 |
28 | pedidoDao.update(vueltaAlCole);
29 | System.out.println("Pedido actualizado:\n" + vueltaAlCole);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/Pedido.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.ArrayList;
5 | import java.util.HashSet;
6 | import java.util.List;
7 | import java.util.Set;
8 |
9 | import javax.persistence.CascadeType;
10 | import javax.persistence.Column;
11 | import javax.persistence.Entity;
12 | import javax.persistence.GeneratedValue;
13 | import javax.persistence.GenerationType;
14 | import javax.persistence.Id;
15 | import javax.persistence.JoinColumn;
16 | import javax.persistence.ManyToMany;
17 | import javax.persistence.OneToMany;
18 | import javax.persistence.OneToOne;
19 | import javax.persistence.Table;
20 |
21 | @Entity
22 | @Table(name = "pedido")
23 | public class Pedido {
24 | @Column(name = "id")
25 | @Id
26 | @GeneratedValue(strategy = GenerationType.IDENTITY)
27 | private int id;
28 | @Column(name = "referencia")
29 | private String referencia;
30 | @Column(name = "fecha")
31 | private LocalDateTime fecha;
32 |
33 | @OneToMany(mappedBy = "pedido", cascade = CascadeType.ALL)
34 | private List albaranes = new ArrayList<>();
35 |
36 | @OneToOne(cascade = CascadeType.ALL)
37 | @JoinColumn
38 | private Factura factura;
39 |
40 | @ManyToMany(mappedBy = "pedidos", cascade = CascadeType.ALL)
41 | private Set productos = new HashSet<>();
42 |
43 | public Pedido() {
44 | }
45 |
46 | public Pedido(String referencia, LocalDateTime fecha) {
47 | this.referencia = referencia;
48 | this.fecha = fecha;
49 | }
50 |
51 | public int getId() {
52 | return id;
53 | }
54 |
55 | public void setId(int id) {
56 | this.id = id;
57 | }
58 |
59 | public String getReferencia() {
60 | return referencia;
61 | }
62 |
63 | public void setReferencia(String referencia) {
64 | this.referencia = referencia;
65 | }
66 |
67 | public LocalDateTime getFecha() {
68 | return fecha;
69 | }
70 |
71 | public void setFecha(LocalDateTime fecha)
72 | {
73 | }
74 |
75 | public List getAlbaranes() {
76 | return albaranes;
77 | }
78 |
79 | public void setAlbaranes(List albaranes) {
80 | this.albaranes = albaranes;
81 | }
82 |
83 | public Albaran generaAlbaran() {
84 | Albaran albaran = new Albaran(this);
85 | albaranes.add(albaran);
86 | return albaran;
87 | }
88 |
89 | public Factura getFactura() {
90 | return factura;
91 | }
92 |
93 | public void setFactura(Factura factura) {
94 | this.factura = factura;
95 | }
96 |
97 | public Factura generaFactura() {
98 | factura = new Factura(this);
99 | return factura;
100 | }
101 |
102 | public Set getProductos() {
103 | return productos;
104 | }
105 |
106 | public void addProducto(Producto producto) {
107 | productos.add(producto);
108 | if (!producto.getPedidos().contains(this)) {
109 | producto.addPedido(this);
110 | }
111 | }
112 |
113 | @Override
114 | public String toString() {
115 | return "Pedido [id=" + id + ", referencia=" + referencia + ", fecha=" + fecha + "]";
116 | }
117 | }
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/Producto.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
2 |
3 | import java.util.Set;
4 |
5 | import javax.persistence.Column;
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import javax.persistence.ManyToMany;
11 |
12 | @Entity
13 | public class Producto {
14 | @Id
15 | @GeneratedValue(strategy = GenerationType.IDENTITY)
16 | private int id;
17 |
18 | @Column(unique = true)
19 | private String referencia;
20 |
21 | private String descripcion;
22 |
23 | @ManyToMany
24 | private Set pedidos;
25 |
26 | public Producto() {
27 | }
28 |
29 | public Producto(String referencia, String descripcion) {
30 | this.referencia = referencia;
31 | this.descripcion = descripcion;
32 | }
33 |
34 | public int getId() {
35 | return id;
36 | }
37 |
38 | public void setId(int id) {
39 | this.id = id;
40 | }
41 |
42 | public String getReferencia() {
43 | return referencia;
44 | }
45 |
46 | public void setReferencia(String referencia) {
47 | this.referencia = referencia;
48 | }
49 |
50 | public String getDescripcion() {
51 | return descripcion;
52 | }
53 |
54 | public void setDescripcion(String descripcion) {
55 | this.descripcion = descripcion;
56 | }
57 |
58 | public Set getPedidos() {
59 | return pedidos;
60 | }
61 |
62 | public void addPedido(Pedido pedido) {
63 | pedidos.add(pedido);
64 | if (!pedido.getProductos().contains(this)) {
65 | pedido.addProducto(this);
66 | }
67 | }
68 |
69 | @Override
70 | public String toString() {
71 | return "Producto [id=" + id + ", referencia=" + referencia + ", descripcion=" + descripcion + "]";
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/SinQueries.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
2 |
3 | import cap16.orm.gestor.dao.PedidoDao;
4 |
5 | public class SinQueries {
6 | public static void main(String[] args) {
7 | PedidoDao pedidoDao = new PedidoDao();
8 | Pedido pedido = pedidoDao.pedidoMasRecienteCriteria();
9 | System.out.println("*** Factura: " + pedido.getFactura());
10 | System.out.println("*** Albaranes: " + pedido.getAlbaranes());
11 | System.out.println("*** Productos: " + pedido.getProductos());
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/dao/AbstractDao.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor.dao;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.function.Consumer;
6 |
7 | import javax.persistence.EntityManager;
8 | import javax.persistence.EntityTransaction;
9 | import javax.persistence.Query;
10 |
11 | import cap16.orm.gestor.utiles.EntityManagerUtil;
12 |
13 | public abstract class AbstractDao implements Dao {
14 |
15 | private EntityManager entityManager = EntityManagerUtil.getEntityManager();
16 | private Class clazz;
17 |
18 | public EntityManager getEntityManager() {
19 | return entityManager;
20 | }
21 |
22 | public Optional get(long id) {
23 | return Optional.ofNullable(entityManager.find(clazz, id));
24 | }
25 |
26 | public List getAll() {
27 | String qlString = "FROM " + clazz.getName();
28 | Query query = entityManager.createQuery(qlString);
29 | return query.getResultList();
30 | }
31 |
32 | public void save(T t) {
33 | executeInsideTransaction(entityManager -> entityManager.persist(t));
34 | }
35 |
36 | public void update(T t) {
37 | executeInsideTransaction(entityManager -> entityManager.merge(t));
38 | }
39 |
40 | public void delete(T t) {
41 | executeInsideTransaction(entityManager -> entityManager.merge(t));
42 | }
43 |
44 | public void setClazz(Class clazz) {
45 | this.clazz = clazz;
46 | }
47 |
48 | private void executeInsideTransaction(Consumer action) {
49 | EntityTransaction tx = entityManager.getTransaction();
50 | try {
51 | tx.begin();
52 | action.accept(entityManager);
53 | tx.commit();
54 | } catch (RuntimeException e) {
55 | tx.rollback();
56 | throw e;
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/dao/AlbaranDao.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor.dao;
2 |
3 | import cap16.orm.gestor.Albaran;
4 |
5 | public class AlbaranDao extends AbstractDao {
6 | public AlbaranDao() {
7 | setClazz(Albaran.class);
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/dao/Dao.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor.dao;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | public interface Dao {
7 | Optional get(long id);
8 | List getAll();
9 | void save(T t);
10 | void update(T t);
11 | void delete(T t);
12 | }
13 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/dao/FacturaDao.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor.dao;
2 |
3 | import cap16.orm.gestor.Factura;
4 |
5 | public class FacturaDao extends AbstractDao {
6 | public FacturaDao() {
7 | setClazz(Factura.class);
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/dao/PedidoDao.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor.dao;
2 |
3 | import java.time.DayOfWeek;
4 | import java.time.LocalDate;
5 | import java.util.List;
6 |
7 | import javax.persistence.Query;
8 | import javax.persistence.criteria.CriteriaBuilder;
9 | import javax.persistence.criteria.CriteriaQuery;
10 | import javax.persistence.criteria.Root;
11 |
12 | import cap16.orm.gestor.Pedido;
13 |
14 | public class PedidoDao extends AbstractDao {
15 |
16 | public PedidoDao() {
17 | setClazz(Pedido.class);
18 | }
19 |
20 | public Pedido pedidoMasReciente() {
21 | String qlString = "FROM " + Pedido.class.getName() + " WHERE fecha < now() order by fecha desc";
22 | Query query = getEntityManager().createQuery(qlString).setMaxResults(1);
23 | return (Pedido) query.getSingleResult();
24 | }
25 |
26 | public Pedido pedidoMasRecienteCriteria() {
27 | CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
28 | CriteriaQuery criteriaQuery = cb.createQuery(Pedido.class);
29 | Root root = criteriaQuery.from(Pedido.class);
30 | criteriaQuery.select(root).where(cb.lessThan(root.get("fecha"), LocalDateTime.now()));
31 | criteriaQuery.orderBy(cb.desc(root.get("fecha")));
32 | Query query = getEntityManager().createQuery(criteriaQuery).setMaxResults(1);
33 | return (Pedido) query.getSingleResult();
34 | }
35 |
36 | public List pedidosSemanaPasada() {
37 | String qlString = "FROM " + Pedido.class.getName() + " WHERE fecha between ?1 and ?2";
38 | Query query = getEntityManager().createQuery(qlString);
39 | LocalDate esteLunes = getEsteLunes();
40 | LocalDate lunesAnterior = esteLunes.minusWeeks(1);
41 | query.setParameter(1, lunesAnterior.atStartOfDay());
42 | query.setParameter(2, esteLunes.atStartOfDay());
43 | return query.getResultList();
44 | }
45 |
46 | private static LocalDate getEsteLunes() {
47 | LocalDate now = LocalDate.now();
48 | DayOfWeek diaSemana = now.getDayOfWeek();
49 | return now.minusDays(diaSemana.getValue() - 1);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/dao/ProductoDao.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor.dao;
2 |
3 | public class ProductoDao extends AbstractDao {
4 |
5 | public ProductoDao() {
6 | setClazz(Producto.class);
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/cap16/gestor/src/main/java/cap16/orm/gestor/utiles/EntityManagerUtil.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor.utiles;
2 |
3 | import javax.persistence.EntityManager;
4 | import javax.persistence.EntityManagerFactory;
5 | import javax.persistence.Persistence;
6 |
7 | public class EntityManagerUtil {
8 | public static EntityManager getEntityManager() {
9 | EntityManagerFactory factory = Persistence.createEntityManagerFactory("gestor");
10 | EntityManager manager = factory.createEntityManager();
11 | return manager;
12 | }
13 |
14 | public static void main(String[] args) {
15 | EntityManager manager = EntityManagerUtil.getEntityManager();
16 | System.out.println("EntityManager class ==> " + manager.getClass().getCanonicalName());
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/cap16/gestor/src/test/java/cap16/orm/gestor/AppTest.java:
--------------------------------------------------------------------------------
1 | package cap16.orm.gestor;
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 |
--------------------------------------------------------------------------------
/cap17/lambdas/Calculadora.java:
--------------------------------------------------------------------------------
1 | package lambdas;
2 |
3 | public class Calculadora {
4 | static final AritmeticaEntera PRODUCTO = (a, b) -> a * b;
5 |
6 | interface AritmeticaEntera {
7 | int operacion(int a, int b);
8 | }
9 |
10 | public static int operacionBinaria(int x, int y, AritmeticaEntera ae) {
11 | return ae.operacion(x, y);
12 | }
13 |
14 | static class Suma implements AritmeticaEntera {
15 | @Override
16 | public int operacion(int a, int b) {
17 | return a + b;
18 | }
19 | }
20 |
21 | public static void main(String... args) {
22 | System.out.println("6 + 2 = " + operacionBinaria(6, 2, new Suma()));
23 | System.out.println("6 - 2 = " + operacionBinaria(6, 2, (a, b) -> a - b));
24 | System.out.println("6 * 2 = " + operacionBinaria(6, 2, PRODUCTO));
25 | System.out.println("6 / 2 = " + operacionBinaria(6, 2, (a, b) -> a / b));
26 | System.out.println("6 ^ 2 = " + operacionBinaria(6, 2, (a, b) -> (int) Math.pow(a, b)));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/cap17/lambdas/CuentasVarias.java:
--------------------------------------------------------------------------------
1 | package lambdas;
2 |
3 | import java.util.Arrays;
4 |
5 | public class CuentasVarias {
6 | public static void main(String... args) {
7 | System.out.print("Parámetros recibidos: ");
8 | Arrays.stream(args).forEach(arg -> System.out.print(arg + " "));
9 | System.out.println();
10 |
11 | long contador = Arrays.stream(args)
12 | .mapToInt(e -> Integer.valueOf(e))
13 | .filter(n -> n % 2 == 0).count();
14 | System.out.println("Hay " + contador + " parámetros pares");
15 |
16 | int suma = Arrays.stream(args).mapToInt(Integer::valueOf).sum();
17 | System.out.println("Suma: " + suma);
18 |
19 | int sumaCuadrados = Arrays.stream(args).mapToInt(Integer::valueOf).map(n -> n * n).sum();
20 | System.out.println("Suma de los cuadrados: " + sumaCuadrados);
21 |
22 | int sumaCuadradosPares = Arrays.stream(args).mapToInt(Integer::valueOf)
23 | .filter(n -> n % 2 == 0).map(n -> n * n).sum();
24 | System.out.println("Suma de los cuadrados pares: " + sumaCuadradosPares);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/cap17/lambdas/FiltrandoTextos.java:
--------------------------------------------------------------------------------
1 | package lambdas;
2 |
3 | import java.util.function.Predicate;
4 |
5 | public class FiltrandoTextos {
6 |
7 | public static void main(String[] args) {
8 | System.out.print("Cadenas largas: ");
9 | procesar(args, s -> s.length() > 5);
10 |
11 | System.out.print("Letras: ");
12 | procesar(args, s -> s.length() == 1);
13 |
14 | System.out.print("Sin a: ");
15 | procesar(args, s -> s.indexOf('a') == -1);
16 | }
17 |
18 | public static void procesar(String[] textos, Predicate predicado) {
19 | for (String n : textos) {
20 | if (predicado.test(n)) {
21 | System.out.print(n + " ");
22 | }
23 | }
24 | System.out.println();
25 | }
26 | }
--------------------------------------------------------------------------------
/cap17/lambdas/FiltrandoTextosStreams.java:
--------------------------------------------------------------------------------
1 | package lambdas;
2 |
3 | import java.util.Arrays;
4 |
5 | public class FiltrandoTextosStreams {
6 |
7 | public static void main(String[] args) {
8 | System.out.print("Cadenas largas: ");
9 | Arrays.stream(args).filter(s -> s.length() > 5).forEach(arg -> System.out.print(arg + " "));
10 | System.out.println();
11 |
12 | System.out.print("Letras: ");
13 | Arrays.stream(args).filter(s -> s.length() == 1).forEach(arg -> System.out.print(arg + " "));
14 | System.out.println();
15 |
16 | System.out.print("Sin a: ");
17 | Arrays.stream(args).filter(s -> s.indexOf('a') == -1).forEach(arg -> System.out.print(arg + " "));
18 | System.out.println();
19 | }
20 | }
--------------------------------------------------------------------------------
/cap18/otrareunionmas/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | otrareunionmas
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
13 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
14 | org.eclipse.jdt.core.compiler.release=disabled
15 | org.eclipse.jdt.core.compiler.source=1.8
16 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | cap18
6 | otrareunionmas
7 | 0.0.1-SNAPSHOT
8 | jar
9 |
10 | otrareunionmas
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 |
20 | org.apache.logging.log4j
21 | log4j-core
22 | 2.17.1
23 |
24 |
25 |
26 |
27 | mysql
28 | mysql-connector-java
29 | 8.0.28
30 |
31 |
32 |
33 | org.hibernate
34 | hibernate-agroal
35 | 5.4.16.Final
36 | pom
37 |
38 |
39 |
40 | junit
41 | junit
42 | 3.8.1
43 | test
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/META-INF/persistence.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | org.hibernate.jpa.HibernatePersistenceProvider
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/CartelSala.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas;
2 |
3 | import java.text.MessageFormat;
4 | import java.time.LocalDate;
5 | import java.time.format.DateTimeFormatter;
6 | import java.util.List;
7 | import java.util.Optional;
8 |
9 | import cap18.otrareunionmas.dao.ReunionDao;
10 | import cap18.otrareunionmas.dao.SalaDao;
11 | import cap18.otrareunionmas.dominio.Reunion;
12 | import cap18.otrareunionmas.dominio.Sala;
13 |
14 | public class CartelSala {
15 |
16 | private static final DateTimeFormatter FORMATO_HORA = DateTimeFormatter.ofPattern("HH:mm");
17 |
18 | public static void main(String[] args) {
19 | if (args.length == 0) {
20 | System.err.println("Faltan parámetros. Indica id de sala, y opcionalmente la fecha deseada (AAAA-MM-DD).");
21 | return;
22 | }
23 | String salaId = args[0];
24 | LocalDate fecha;
25 | if (args.length >= 2) {
26 | fecha = LocalDate.parse(args[1]);
27 | } else {
28 | fecha = LocalDate.now();
29 | }
30 |
31 | SalaDao salaDao = new SalaDao();
32 | Optional optional = salaDao.get(salaId);
33 | if (optional.isPresent()) {
34 | Sala sala = optional.get();
35 | ReunionDao reunionDao = new ReunionDao();
36 | List reuniones = reunionDao.getBySalaAndFecha(sala, fecha);
37 | imprimirCabecera(sala, fecha);
38 | imprimirReuniones(reuniones);
39 | } else {
40 | System.err.println(MessageFormat.format("La sala con id {0} no existe", salaId));
41 | }
42 | }
43 |
44 | private static void imprimirCabecera(Sala sala, LocalDate fecha) {
45 | System.out.println(MessageFormat.format("* SALA: {0} ({1})", sala.getDescripcion(), sala.getId()));
46 | System.out.println(MessageFormat.format("* FECHA: {0}", fecha));
47 | }
48 |
49 | private static void imprimirReuniones(List reuniones) {
50 | System.out.println("Reuniones previstas:");
51 | for (Reunion reunion : reuniones) {
52 | System.out.println(MessageFormat.format("{0}:\t{1}", reunion.getFecha().format(FORMATO_HORA), reunion.getAsunto()));
53 | }
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/GeneracionDatos.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas;
2 |
3 | import java.time.LocalDateTime;
4 | import java.time.temporal.ChronoUnit;
5 |
6 | import cap18.otrareunionmas.dao.ActaDao;
7 | import cap18.otrareunionmas.dao.ReunionDao;
8 | import cap18.otrareunionmas.dao.SalaDao;
9 | import cap18.otrareunionmas.dominio.Acta;
10 | import cap18.otrareunionmas.dominio.Persona;
11 | import cap18.otrareunionmas.dominio.Reunion;
12 | import cap18.otrareunionmas.dominio.Sala;
13 |
14 | public class GeneracionDatos
15 | {
16 | private static final int HORA_INI = 10;
17 |
18 | public static void main( String[] args )
19 | {
20 | System.out.println( "Otra reunión más - Generación de datos" );
21 | // DAOs
22 | ReunionDao reunionDao = new ReunionDao();
23 | ActaDao actaDao = new ActaDao();
24 | SalaDao salaDao = new SalaDao();
25 |
26 | // Creación de objetos
27 | Sala s099 = new Sala("S099", "Trastero", 1);
28 | Sala s101 = new Sala("S101", "Reunión primera planta", 10);
29 | Sala s109 = new Sala("S109", "Entrevistas primera planta", 3);
30 | Sala s203 = new Sala("S203", "Sala grande", 25);
31 |
32 | salaDao.save(s099);
33 | salaDao.save(s101);
34 | salaDao.save(s109);
35 | salaDao.save(s203);
36 |
37 | Persona marta = new Persona("E001", "Marta", "García López");
38 | Persona pedro = new Persona("E002", "Pedro", "Gómez Fernández");
39 | Persona santi = new Persona("E003", "Santi", "Pérez Pérez");
40 | Persona luisa = new Persona("E004", "Luisa", "Gutiérrez González");
41 |
42 | Reunion r0 = new Reunion(LocalDateTime.now(), "Reunión de Test");
43 | Reunion r1 = new Reunion(LocalDateTime.now().plus(2, ChronoUnit.HOURS), "Otra Reunión de Test");
44 | Reunion r2 = new Reunion(LocalDateTime.now().plus(2, ChronoUnit.DAYS), "Reunión de pasado mañana");
45 | Reunion r3 = new Reunion(LocalDateTime.now().plus(1, ChronoUnit.DAYS), "Reunión de mañana");
46 | Reunion r4 = new Reunion(LocalDateTime.now().minus(1, ChronoUnit.DAYS), "Reunión de ayer");
47 |
48 | // reuniones de hoy en sala 101
49 | LocalDateTime hoy = LocalDateTime.now().withHour(10);
50 | for (int i = 0; i < 5; i ++) {
51 | Reunion r = new Reunion(hoy.plusHours(i), "Reunión de las " + (HORA_INI + i));
52 | r.setSala(s101);
53 | reunionDao.save(r);
54 | }
55 |
56 | r0.addParticipante(marta);
57 | r0.setSala(s099);
58 | reunionDao.save(r0);
59 | Acta a0 = new Acta("Marta se reúne sola, solo para descansar un rato", r0);
60 | actaDao.save(a0);
61 | reunionDao.update(r0);
62 |
63 | r1.addParticipante(marta);
64 | r1.addParticipante(pedro);
65 | r1.addParticipante(santi);
66 | r1.addParticipante(luisa);
67 | r1.setSala(s101);
68 | reunionDao.save(r1);
69 |
70 | r2.addParticipante(pedro);
71 | r2.addParticipante(santi);
72 | r2.setSala(s109);
73 | reunionDao.save(r2);
74 |
75 | r3.addParticipante(marta);
76 | r3.addParticipante(luisa);
77 | r3.setSala(s109);
78 | reunionDao.save(r3);
79 |
80 | r4.addParticipante(marta);
81 | r4.addParticipante(pedro);
82 | r4.addParticipante(santi);
83 | r4.addParticipante(luisa);
84 | r4.setSala(s203);
85 | reunionDao.save(r4);
86 |
87 | Acta a4 = new Acta("Preparación del lanzamiento de la aplicación \"Otra Reunión Más\".", r4);
88 | actaDao.save(a4);
89 | reunionDao.update(r4);
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/InformeReunion.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas;
2 |
3 | import java.text.MessageFormat;
4 | import java.time.format.DateTimeFormatter;
5 | import java.util.Optional;
6 | import java.util.Scanner;
7 | import java.util.Set;
8 |
9 | import cap18.otrareunionmas.dao.ReunionDao;
10 | import cap18.otrareunionmas.dominio.Acta;
11 | import cap18.otrareunionmas.dominio.Persona;
12 | import cap18.otrareunionmas.dominio.Reunion;
13 |
14 | public class InformeReunion {
15 | private static final DateTimeFormatter FORMATO_FECHA = DateTimeFormatter.ofPattern("'el' EEEE, dd 'de' MMMM 'de' yyyy 'a las' HH:mm");
16 | private static final String ID_FORMAT = ",number,#";
17 |
18 | public static void main(String[] args) {
19 | try (Scanner s = new Scanner(System.in)) {
20 | System.out.println("Indica el id de la reunión: ");
21 | int reunionId = s.nextInt();
22 | ReunionDao reunionDao = new ReunionDao();
23 | Optional optional = reunionDao.get(reunionId);
24 | if (optional.isPresent()) {
25 | Reunion r = optional.get();
26 | imprimirReunion(r);
27 | } else {
28 | System.err.println(MessageFormat.format("La reunión con id {0" + ID_FORMAT + "} no existe", reunionId));
29 | }
30 | }
31 | }
32 |
33 | private static void imprimirReunion(Reunion r) {
34 | System.out.println(MessageFormat.format("Informe de la reunión con asunto \"{0}\" (id {1" + ID_FORMAT + "})", r.getAsunto(), r.getId()));
35 | System.out.println(MessageFormat.format("\tcelebrada el {0}\n\ten la sala {1} (id {2})",
36 | r.getFecha().format(FORMATO_FECHA), r.getSala().getDescripcion(), r.getSala().getId()));
37 | imprimirParticipantes(r);
38 | imprimirActa(r);
39 | }
40 |
41 | private static void imprimirParticipantes(Reunion r) {
42 | System.out.println("Participantes:");
43 | Set participantes = r.getParticipantes();
44 | if (participantes.isEmpty()) {
45 | System.err.println("No hay participantes");
46 | }
47 | for (Persona persona : participantes) {
48 | System.out.println(MessageFormat.format("\t{2}\t{1}, {0}",
49 | persona.getNombre(), persona.getApellidos().toUpperCase(), persona.getNumeroEmpleado()));
50 | }
51 | }
52 |
53 | private static void imprimirActa(Reunion r) {
54 | Acta a = r.getActa();
55 | System.out.println("Acta:");
56 | if (a == null) {
57 | System.err.println("No hay acta");
58 | } else {
59 | System.out.println("\t" + a.getContenido());
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/InformeReuniones.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas;
2 |
3 | import java.text.MessageFormat;
4 | import java.time.format.DateTimeFormatter;
5 | import java.util.Comparator;
6 | import java.util.HashMap;
7 | import java.util.List;
8 | import java.util.Map;
9 | import java.util.Set;
10 |
11 | import cap18.otrareunionmas.dao.ActaDao;
12 | import cap18.otrareunionmas.dominio.Acta;
13 | import cap18.otrareunionmas.dominio.Persona;
14 | import cap18.otrareunionmas.dominio.Reunion;
15 |
16 | public class InformeReuniones {
17 | private static final DateTimeFormatter FORMATO_FECHA = DateTimeFormatter.ofPattern("'el' EEEE, dd 'de' MMMM 'de' yyyy 'a las' HH:mm");
18 | private static final String ID_FORMAT = ",number,#";
19 | private static final int MIN_PART = 3;
20 |
21 | public static void main(String[] args) {
22 | ActaDao actaDao = new ActaDao();
23 | List actas = actaDao.getAll();
24 | Map informes = new HashMap<>(actas.size());
25 | actas.stream().filter(
26 | acta -> acta.getReunion().getParticipantes().size() >= MIN_PART
27 | ).forEach(
28 | acta -> informes.put(acta.getReunion(), informeReunion(acta.getReunion()))
29 | );
30 | imprimirInformes(informes);
31 | }
32 |
33 | private static void imprimirInformes(Map informes) {
34 | informes.entrySet().stream().sorted(
35 | Comparator.comparing(informe -> informe.getKey().getFecha())
36 | ).forEach(
37 | informe -> {
38 | System.out.println("== Reunión:\n" + informe.getKey().getAsunto());
39 | System.out.println("== Informe:\n" + informe.getValue());
40 | }
41 | );
42 | }
43 |
44 | private static String informeReunion(Reunion r) {
45 | StringBuilder sb = new StringBuilder(MessageFormat.format(
46 | "Informe de la reunión con asunto \"{0}\" (id {1" + ID_FORMAT + "})\n",
47 | r.getAsunto(), r.getId()));
48 | sb.append(MessageFormat.format("\tcelebrada {0}\n\ten la sala {1} (id {2})\n",
49 | r.getFecha().format(FORMATO_FECHA), r.getSala().getDescripcion(), r.getSala().getId()));
50 | sb.append(informeParticipantes(r));
51 | sb.append(informeActa(r));
52 | return sb.toString();
53 | }
54 |
55 | private static String informeParticipantes(Reunion r) {
56 | StringBuilder sb = new StringBuilder("Participantes:\n");
57 | Set participantes = r.getParticipantes();
58 | if (participantes.isEmpty()) {
59 | sb.append("No hay participantes\n");
60 | }
61 | participantes.stream().sorted(Comparator.comparing(Persona::getNumeroEmpleado)).forEach(
62 | persona ->
63 | sb.append(MessageFormat.format("\t{2}\t{1}, {0}\n",
64 | persona.getNombre(),
65 | persona.getApellidos().toUpperCase(),
66 | persona.getNumeroEmpleado()))
67 | );
68 | return sb.toString();
69 | }
70 |
71 | private static String informeActa(Reunion r) {
72 | Acta a = r.getActa();
73 | StringBuilder sb = new StringBuilder("Acta:\n");
74 | if (a == null) {
75 | sb.append("No hay acta\n");
76 | } else {
77 | sb.append("\t" + a.getContenido() + "\n");
78 | }
79 | return sb.toString();
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dao/AbstractDao.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dao;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.function.Consumer;
6 |
7 | import javax.persistence.EntityManager;
8 | import javax.persistence.EntityTransaction;
9 | import javax.persistence.Query;
10 |
11 | import cap18.otrareunionmas.utiles.EntityManagerUtil;
12 |
13 | public abstract class AbstractDao implements Dao {
14 |
15 | private EntityManager entityManager = EntityManagerUtil.getEntityManager();
16 | private Class clazz;
17 |
18 | public EntityManager getEntityManager() {
19 | return entityManager;
20 | }
21 |
22 | public Optional get(int id) {
23 | return Optional.ofNullable(entityManager.find(clazz, id));
24 | }
25 |
26 | public Optional get(Object id) {
27 | return Optional.ofNullable(entityManager.find(clazz, id));
28 | }
29 |
30 | public List getAll() {
31 | String qlString = "FROM " + clazz.getName();
32 | Query query = entityManager.createQuery(qlString);
33 | return query.getResultList();
34 | }
35 |
36 | public void save(T t) {
37 | executeInsideTransaction(entityManager -> entityManager.persist(t));
38 | }
39 |
40 | public void update(T t) {
41 | executeInsideTransaction(entityManager -> entityManager.merge(t));
42 | }
43 |
44 | public void delete(T t) {
45 | executeInsideTransaction(entityManager -> entityManager.merge(t));
46 | }
47 |
48 | public void setClazz(Class clazz) {
49 | this.clazz = clazz;
50 | }
51 |
52 | private void executeInsideTransaction(Consumer action) {
53 | EntityTransaction tx = entityManager.getTransaction();
54 | try {
55 | tx.begin();
56 | action.accept(entityManager);
57 | tx.commit();
58 | } catch (RuntimeException e) {
59 | tx.rollback();
60 | throw e;
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dao/ActaDao.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dao;
2 |
3 | import cap18.otrareunionmas.dominio.Acta;
4 |
5 | public class ActaDao extends AbstractDao {
6 | public ActaDao() {
7 | setClazz(Acta.class);
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dao/Dao.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dao;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | public interface Dao {
7 | Optional get(int id);
8 | Optional get(Object id);
9 | List getAll();
10 | void save(T t);
11 | void update(T t);
12 | void delete(T t);
13 | }
14 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dao/PersonaDao.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dao;
2 |
3 | import cap18.otrareunionmas.dominio.Persona;
4 |
5 | public class PersonaDao extends AbstractDao {
6 |
7 | public PersonaDao() {
8 | setClazz(Persona.class);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dao/ReunionDao.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dao;
2 |
3 | import java.time.LocalDate;
4 | import java.util.List;
5 |
6 | import javax.persistence.Query;
7 | import javax.persistence.criteria.CriteriaBuilder;
8 | import javax.persistence.criteria.CriteriaQuery;
9 | import javax.persistence.criteria.Predicate;
10 | import javax.persistence.criteria.Root;
11 |
12 | import cap18.otrareunionmas.dominio.Reunion;
13 | import cap18.otrareunionmas.dominio.Sala;
14 |
15 | public class ReunionDao extends AbstractDao {
16 |
17 | public ReunionDao() {
18 | setClazz(Reunion.class);
19 | }
20 |
21 | public List getBySalaAndFecha(Sala sala, LocalDate fecha) {
22 | CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
23 | CriteriaQuery criteriaQuery = cb.createQuery(Reunion.class);
24 | Root root = criteriaQuery.from(Reunion.class);
25 |
26 | Predicate predSala = cb.equal(root.get("sala"), sala);
27 | Predicate predFecha = cb.between(root.get("fecha"), fecha.atStartOfDay(), fecha.plusDays(1).atStartOfDay());
28 |
29 | criteriaQuery.select(root).where(cb.and(predSala, predFecha));
30 | criteriaQuery.orderBy(cb.asc(root.get("fecha")));
31 | Query query = getEntityManager().createQuery(criteriaQuery);
32 | return query.getResultList();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dao/SalaDao.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dao;
2 |
3 | import cap18.otrareunionmas.dominio.Sala;
4 |
5 | public class SalaDao extends AbstractDao {
6 |
7 | public SalaDao() {
8 | setClazz(Sala.class);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dominio/Acta.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dominio;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.GenerationType;
6 | import javax.persistence.Id;
7 | import javax.persistence.JoinColumn;
8 | import javax.persistence.OneToOne;
9 |
10 | @Entity
11 | //@Table(name = "acta")
12 | public class Acta {
13 |
14 | @Id
15 | @GeneratedValue(strategy = GenerationType.IDENTITY)
16 | private int id;
17 |
18 | private String contenido;
19 |
20 | @OneToOne
21 | @JoinColumn
22 | private Reunion reunion;
23 |
24 | public Acta() {
25 | }
26 |
27 | public Acta(String contenido, Reunion reunion) {
28 | this.contenido = contenido;
29 | this.reunion = reunion;
30 | reunion.setActa(this);
31 | }
32 |
33 | public int getId() {
34 | return id;
35 | }
36 |
37 | public void setId(int id) {
38 | this.id = id;
39 | }
40 |
41 | public String getContenido() {
42 | return contenido;
43 | }
44 |
45 | public void setContenido(String contenido) {
46 | this.contenido = contenido;
47 | }
48 |
49 | public Reunion getReunion() {
50 | return reunion;
51 | }
52 |
53 | public void setReunion(Reunion reunion) {
54 | this.reunion = reunion;
55 | }
56 |
57 | @Override
58 | public String toString() {
59 | return "Acta [id=" + id + ", contenido=" + contenido + "]";
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dominio/Persona.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dominio;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.ManyToMany;
12 |
13 | @Entity
14 | public class Persona {
15 |
16 | @Id
17 | @GeneratedValue(strategy = GenerationType.IDENTITY)
18 | private int id;
19 |
20 | @Column(unique = true)
21 | private String numeroEmpleado;
22 |
23 | private String nombre;
24 | private String apellidos;
25 |
26 | @ManyToMany
27 | private Set reuniones;
28 |
29 | public Persona() {
30 | reuniones = new HashSet();
31 | }
32 |
33 | public Persona(String numeroEmpleado, String nombre, String apellidos) {
34 | this();
35 | this.numeroEmpleado = numeroEmpleado;
36 | this.nombre = nombre;
37 | this.apellidos = apellidos;
38 | }
39 |
40 | public int getId() {
41 | return id;
42 | }
43 |
44 | public void setId(int id) {
45 | this.id = id;
46 | }
47 |
48 | public String getNumeroEmpleado() {
49 | return numeroEmpleado;
50 | }
51 |
52 | public void setNumeroEmpleado(String numeroEmpleado) {
53 | this.numeroEmpleado = numeroEmpleado;
54 | }
55 |
56 | public String getNombre() {
57 | return nombre;
58 | }
59 |
60 | public void setNombre(String nombre) {
61 | this.nombre = nombre;
62 | }
63 |
64 | public String getApellidos() {
65 | return apellidos;
66 | }
67 |
68 | public void setApellidos(String apellidos) {
69 | this.apellidos = apellidos;
70 | }
71 |
72 | public Set getReuniones() {
73 | return reuniones;
74 | }
75 |
76 | public void addReunion(Reunion reunion) {
77 | reuniones.add(reunion);
78 | if (!reunion.getParticipantes().contains(this)) {
79 | reunion.addParticipante(this);
80 | }
81 | }
82 |
83 | @Override
84 | public String toString() {
85 | return "Persona [id=" + id + ", numeroEmpleado=" + numeroEmpleado + ", nombre=" + nombre + ", apellidos="
86 | + apellidos + "]";
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dominio/Reunion.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dominio;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | import javax.persistence.CascadeType;
8 | import javax.persistence.Entity;
9 | import javax.persistence.FetchType;
10 | import javax.persistence.GeneratedValue;
11 | import javax.persistence.GenerationType;
12 | import javax.persistence.Id;
13 | import javax.persistence.ManyToMany;
14 | import javax.persistence.ManyToOne;
15 | import javax.persistence.OneToOne;
16 | import javax.persistence.Table;
17 |
18 | @Entity
19 | //@Table(name = "reunion")
20 | public class Reunion {
21 |
22 | @Id
23 | @GeneratedValue(strategy = GenerationType.IDENTITY)
24 | // @Column(name = "id")
25 | private int id;
26 |
27 | // @Column(name = "fecha")
28 | private LocalDateTime fecha;
29 |
30 | // @Column(name = "asunto")
31 | private String asunto;
32 |
33 | @ManyToOne(fetch = FetchType.LAZY)
34 | private Sala sala;
35 |
36 | @OneToOne(mappedBy = "reunion")
37 | private Acta acta;
38 |
39 | @ManyToMany(mappedBy = "reuniones", cascade = CascadeType.ALL)
40 | private Set participantes;
41 |
42 | public Reunion() {
43 | participantes = new HashSet();
44 | }
45 |
46 | public Reunion(LocalDateTime fecha, String asunto) {
47 | this();
48 | this.fecha = fecha;
49 | this.asunto = asunto;
50 | }
51 |
52 | public Reunion(Reunion r) {
53 | this.fecha = r.fecha;
54 | this.asunto = r.asunto;
55 | }
56 |
57 | public int getId() {
58 | return id;
59 | }
60 |
61 | public void setId(int id) {
62 | this.id = id;
63 | }
64 |
65 | public LocalDateTime getFecha() {
66 | return fecha;
67 | }
68 |
69 | public void setFecha(LocalDateTime fecha) {
70 | this.fecha = fecha;
71 | }
72 |
73 | public String getAsunto() {
74 | return asunto;
75 | }
76 |
77 | public void setAsunto(String asunto) {
78 | this.asunto = asunto;
79 | }
80 |
81 | public Sala getSala() {
82 | return sala;
83 | }
84 |
85 | public void setSala(Sala sala) {
86 | this.sala = sala;
87 | }
88 |
89 | public Acta getActa() {
90 | return acta;
91 | }
92 |
93 | public void setActa(Acta acta) {
94 | this.acta = acta;
95 | }
96 |
97 | public Set getParticipantes() {
98 | return participantes;
99 | }
100 |
101 | public void addParticipante(Persona participante) {
102 | participantes.add(participante);
103 | if (!participante.getReuniones().contains(this)) {
104 | participante.addReunion(this);
105 | }
106 | }
107 |
108 | @Override
109 | public String toString() {
110 | return "Reunion [id=" + id + ", fecha=" + fecha + ", asunto=" + asunto + "]";
111 | }
112 |
113 | }
114 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/dominio/Sala.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.dominio;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.Column;
6 | import javax.persistence.Entity;
7 | import javax.persistence.Id;
8 | import javax.persistence.OneToMany;
9 | import javax.persistence.Table;
10 |
11 | @Entity
12 | //@Table(name = "sala")
13 | public class Sala {
14 | @Id
15 | @Column(length = 20)
16 | private String id;
17 |
18 | private String descripcion;
19 |
20 | private int capacidad;
21 |
22 | @OneToMany(mappedBy = "sala")
23 | private List reuniones;
24 |
25 | public Sala() {
26 | }
27 |
28 | public Sala(String id, String descripcion, int capacidad) {
29 | this.id = id;
30 | this.descripcion = descripcion;
31 | this.capacidad = capacidad;
32 | }
33 |
34 | public String getId() {
35 | return id;
36 | }
37 |
38 | public void setId(String id) {
39 | this.id = id;
40 | }
41 |
42 | public String getDescripcion() {
43 | return descripcion;
44 | }
45 |
46 | public void setDescripcion(String descripcion) {
47 | this.descripcion = descripcion;
48 | }
49 |
50 | public int getCapacidad() {
51 | return capacidad;
52 | }
53 |
54 | public void setCapacidad(int capacidad) {
55 | this.capacidad = capacidad;
56 | }
57 |
58 | public List getReuniones() {
59 | return reuniones;
60 | }
61 |
62 | public void setReuniones(List reuniones) {
63 | this.reuniones = reuniones;
64 | }
65 |
66 | @Override
67 | public String toString() {
68 | return "Sala [id=" + id + ", descripcion=" + descripcion + ", capacidad=" + capacidad + "]";
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/main/java/cap18/otrareunionmas/utiles/EntityManagerUtil.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas.utiles;
2 |
3 | import javax.persistence.EntityManager;
4 | import javax.persistence.EntityManagerFactory;
5 | import javax.persistence.Persistence;
6 |
7 | public class EntityManagerUtil {
8 | public static EntityManager getEntityManager() {
9 | EntityManagerFactory factory = Persistence.createEntityManagerFactory("OtraReunionMas");
10 | EntityManager manager = factory.createEntityManager();
11 | return manager;
12 | }
13 |
14 | public static void main(String[] args) {
15 | EntityManager manager = EntityManagerUtil.getEntityManager();
16 | System.out.println("EntityManager class ==> " + manager.getClass().getCanonicalName());
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/cap18/otrareunionmas/src/test/java/cap18/otrareunionmas/AppTest.java:
--------------------------------------------------------------------------------
1 | package cap18.otrareunionmas;
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 |
--------------------------------------------------------------------------------