├── .gitignore ├── README.md ├── ejemplos ├── Ej1Sintaxis │ ├── .project │ └── src │ │ └── primerEjemplo │ │ └── Principal.java ├── Ej2Herencia │ ├── .gitignore │ ├── .project │ └── src │ │ ├── entidades │ │ ├── Alumno.java │ │ └── Persona.java │ │ └── ui │ │ └── Principal.java ├── Ej3Colecciones │ ├── .gitignore │ ├── .project │ └── src │ │ ├── entities │ │ ├── Person.java │ │ └── PersonLexicographicComparator.java │ │ └── ui │ │ ├── UsoArrayList1.java │ │ ├── UsoLinkedList1.java │ │ ├── UsoLinkedList2.java │ │ └── UsoLinkedList3.java ├── Ej4JDBC │ ├── .gitignore │ ├── .project │ ├── lib │ │ └── mysql-connector-java-8.0.20.jar │ └── src │ │ ├── entities │ │ ├── Documento.java │ │ └── Persona.java │ │ ├── steps.md │ │ └── ui │ │ └── Principal.java ├── Ej5AccesoADatos │ ├── .gitignore │ ├── .project │ ├── db │ │ ├── dbJava.sql │ │ └── userJava.sql │ ├── lib │ │ └── mysql-connector-java-8.0.20.jar │ └── src │ │ ├── data │ │ ├── DataPersona.java │ │ ├── DataRol.java │ │ └── DbConnector.java │ │ ├── entities │ │ ├── Documento.java │ │ ├── Persona.java │ │ └── Rol.java │ │ ├── logic │ │ └── Login.java │ │ ├── steps.md │ │ └── ui │ │ ├── Menu.java │ │ └── Principal.java ├── Ej6WebIntro │ ├── .gitignore │ ├── .project │ ├── WebContent │ │ ├── META-INF │ │ │ └── MANIFEST.MF │ │ ├── WEB-INF │ │ │ ├── UserManagement.jsp │ │ │ └── lib │ │ │ │ └── mysql-connector-java-8.0.20.jar │ │ ├── index.html │ │ └── style │ │ │ ├── bootstrap-solid.html │ │ │ ├── bootstrap.css │ │ │ └── signin.css │ ├── db │ │ ├── dbJava.sql │ │ └── userJava.sql │ └── src │ │ ├── data │ │ ├── DataPersona.java │ │ ├── DataRol.java │ │ └── DbConnector.java │ │ ├── entities │ │ ├── Documento.java │ │ ├── Persona.java │ │ └── Rol.java │ │ ├── logic │ │ └── Login.java │ │ ├── servlet │ │ └── Signin.java │ │ └── steps.md ├── Ej6WebIntro2022 │ ├── .gitignore │ ├── .project │ └── src │ │ └── main │ │ ├── db │ │ ├── dbJava.sql │ │ ├── steps.md │ │ └── userJava.sql │ │ ├── java │ │ ├── data │ │ │ ├── DataPersona.java │ │ │ ├── DataRol.java │ │ │ └── DbConnector.java │ │ ├── entities │ │ │ ├── Documento.java │ │ │ ├── Persona.java │ │ │ └── Rol.java │ │ ├── logic │ │ │ └── Login.java │ │ └── servlet │ │ │ ├── Signin.java │ │ │ └── UploadServlet.java │ │ └── webapp │ │ ├── META-INF │ │ └── MANIFEST.MF │ │ ├── WEB-INF │ │ ├── UserManagement.jsp │ │ ├── lib │ │ │ └── mysql-connector-java-8.0.29.jar │ │ └── web.xml │ │ ├── image.html │ │ ├── index.html │ │ ├── response.jsp │ │ └── style │ │ ├── bootstrap-solid.html │ │ ├── bootstrap.css │ │ └── signin.css ├── Ejercicio05 │ ├── .gitignore │ ├── .project │ └── src │ │ ├── entidades │ │ ├── Administrativo.java │ │ ├── Empleado.java │ │ └── Vendedor.java │ │ └── ui │ │ └── Ppal.java ├── Ejercicio6JDBCB │ ├── .gitignore │ ├── .project │ ├── lib │ │ └── mysql-connector-java-8.0.25.jar │ └── src │ │ ├── data │ │ └── DbHandler.java │ │ ├── entities │ │ └── Product.java │ │ └── ui │ │ ├── Menu.java │ │ └── Principal.java ├── Ejercicio6JDBCTM │ ├── .gitignore │ ├── .project │ ├── lib │ │ └── mysql-connector-java-8.0.25.jar │ └── src │ │ ├── data │ │ └── DbHandler.java │ │ ├── entities │ │ └── Product.java │ │ └── ui │ │ ├── Menu.java │ │ └── Principal.java ├── Ejercicio6TNJDBC │ ├── .gitignore │ ├── .project │ ├── lib │ │ └── mysql-connector-java-8.0.25.jar │ └── src │ │ ├── data │ │ └── DbProduct.java │ │ ├── entities │ │ └── Product.java │ │ └── ui │ │ ├── Menu.java │ │ └── Principal.java ├── Ejercicio6TTJDBC │ ├── .gitignore │ ├── .project │ ├── lib │ │ └── mysql-connector-java-8.0.25.jar │ └── src │ │ ├── data │ │ └── DbProduct.java │ │ ├── entities │ │ └── Product.java │ │ └── ui │ │ ├── Menu.java │ │ └── Principal.java ├── RemoteSystemsTempFiles │ └── .project └── Servers2 │ ├── .project │ └── apache-tomcat-10.0.13 at localhost-config │ ├── catalina.policy │ ├── catalina.properties │ ├── context.xml │ ├── server.xml │ ├── tomcat-users.xml │ └── web.xml ├── enunciados ├── README.md └── img │ ├── EsquemaCapas.png │ └── diagramaClases01.png └── tp └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Directories # 2 | /build/ 3 | /bin/ 4 | target/ 5 | ejemplos/Servers/ 6 | 7 | # OS Files # 8 | .DS_Store 9 | 10 | *.class 11 | 12 | # Package Files # 13 | *.jar 14 | *.war 15 | *.ear 16 | *.db 17 | 18 | # Whitelist connector/j # 19 | !/ejemplos/**/lib/*.jar 20 | 21 | ###################### 22 | # Windows 23 | ###################### 24 | 25 | # Windows image file caches 26 | Thumbs.db 27 | 28 | # Folder config file 29 | Desktop.ini 30 | 31 | ###################### 32 | # OSX 33 | ###################### 34 | 35 | .DS_Store 36 | .svn 37 | 38 | # Thumbnails 39 | ._* 40 | 41 | # Files that might appear on external disk 42 | .Spotlight-V100 43 | .Trashes 44 | 45 | 46 | ###################### 47 | # Eclipse 48 | ###################### 49 | 50 | *.pydevproject 51 | .metadata 52 | bin/** 53 | tmp/** 54 | tmp/**/* 55 | *.tmp 56 | *.bak 57 | *.swp 58 | *~.nib 59 | local.properties 60 | .classpath 61 | .settings/ 62 | .loadpath 63 | /src/main/resources/rebel.xml 64 | # External tool builders 65 | .externalToolBuilders/ 66 | .recommenders 67 | 68 | # Locally stored "Eclipse launch configurations" 69 | *.launch 70 | 71 | # CDT-specific 72 | .cproject 73 | 74 | # PDT-specific 75 | .buildpath 76 | 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java 2 | Este repositorio corresponde a la cátedra de Java UTN FRRo. 3 | 4 | Aquí podrán encontrar los ejemplos dictados en clase, ejercicios realizados en clase e información relacionada referente a cada tema y material útil relacionado. 5 | 6 | ## Grupo de Telegram 7 | Para notificaciones de último momento pueden utilizar el grupo de Telegram al cual se pueden sumar a través de los siguientes links 8 | * [Turno mañana](https://kutt.it/java2021tmchat). 9 | * [Turno tarde y noche](https://kutt.it/java2021ttnchat). 10 | 11 | 12 | Se recomienda el uso de [usernames](https://telegram.org/faq#usernames-and-t-me) para quienes quieran mantener su número telefónico privado. 13 | 14 | ## Trabajo práctico 15 | El detalle de las condiciones, requerimientos, criterio de evaluación y entregas del TP pueden verlo en este [link](./tp/README.md) 16 | 17 | ## Condición Alumnos 18 | Aquí se agregará un link a la planilla de seguimiento de la condición de cada alumno. 19 | 20 | ## Sistema Final 21 | Las condiciones del sistema final de la materia pueden encontrarse en [este link](https://goo.gl/BifevO). 22 | 23 | ## Links a tutoriales 24 | El archivo [recursos.md](https://github.com/utnfrrojava/java/blob/master/material/recursos.md) contiene links a muchos tutoriales tanto de java como de desarrollo web. 25 | 26 | ## Material de clases 27 | Los ejemplos y ejercicios de clase se encuentran en la carpeta [ejemplos](./ejemplos/). 28 | 29 | Ambas carpetas son workspace de eclipse pero fueron excluidos los archivos de eclipse para que fuera sencillo utilizarlo desde otros IDEs o versiones de eclipse. 30 | -------------------------------------------------------------------------------- /ejemplos/Ej1Sintaxis/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ej1Sintaxis 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 | -------------------------------------------------------------------------------- /ejemplos/Ej1Sintaxis/src/primerEjemplo/Principal.java: -------------------------------------------------------------------------------- 1 | package primerEjemplo; 2 | 3 | import java.util.Scanner; 4 | 5 | import javax.swing.JOptionPane; 6 | 7 | public class Principal { 8 | 9 | public static void main(String[] args) { 10 | 11 | System.out.println("Primer Ejemplo"); 12 | int n1; 13 | int n2=3; 14 | Integer n3; 15 | String texto; 16 | String texto2="bienvenido"; 17 | n1=2; 18 | 19 | Scanner lector = new Scanner(System.in); 20 | 21 | //variablesEIfs(n1, n2, texto2, lector); 22 | iterar(lector); 23 | 24 | 25 | lector.close(); 26 | 27 | //String despedida=JOptionPane.showInputDialog("Ingrese saludo final"); 28 | 29 | //JOptionPane.showMessageDialog(null, despedida); 30 | 31 | } 32 | 33 | private static void iterar(Scanner lector) { 34 | String[] palabras = new String[3]; 35 | //0,1,2 36 | 37 | for (int i = 0; i < palabras.length; i++) { 38 | System.out.println("Ingrese la palabra "+(i+1)); 39 | palabras[i]=lector.nextLine(); 40 | } 41 | System.out.println(); 42 | System.out.println("iterar con for"); 43 | for (int i = 0; i < palabras.length; i++) { 44 | System.out.println("palabras["+i+"]: "+palabras[i]); 45 | } 46 | 47 | System.out.println(); 48 | System.out.println("iterar con for orden inverso"); 49 | for (int i = palabras.length-1; i >=0; i--) { 50 | System.out.println("palabras["+i+"]: "+palabras[i]); 51 | } 52 | 53 | System.out.println(); 54 | System.out.println("iterar con foreach"); 55 | for (String palabra : palabras) { 56 | System.out.println(palabra); 57 | } 58 | 59 | } 60 | 61 | private static void variablesEIfs(int n1, int n2, String texto2, Scanner lector) { 62 | Integer n3; 63 | String texto; 64 | System.out.print("Ingrese un texto: "); 65 | texto=lector.nextLine(); 66 | System.out.print("Ingrese un nro: "); 67 | n3=Integer.parseInt(lector.nextLine()); 68 | 69 | System.out.println(); 70 | System.out.println("texto: "+texto); 71 | System.out.println("nro: "+n3); 72 | 73 | System.out.println(); 74 | if (n3==n2+n1) { 75 | System.out.println("Nros Iguales"); 76 | } else { 77 | System.out.println("Nros Distintos"); 78 | } 79 | 80 | System.out.println(); 81 | System.out.println("Comparar con =="); 82 | if (texto==texto2) { 83 | System.out.println("textos iguales"); 84 | } else { 85 | System.out.println("textos distintos"); 86 | } 87 | 88 | System.out.println(); 89 | System.out.println("Comparar con equals"); 90 | if (texto.equals(texto2)) { 91 | System.out.println("textos iguales"); 92 | } else { 93 | System.out.println("textos distintos"); 94 | } 95 | 96 | System.out.println(); 97 | System.out.println("Comparar con equalsIgnoreCase"); 98 | if (texto.equalsIgnoreCase(texto2)) { 99 | System.out.println("textos iguales"); 100 | } else { 101 | System.out.println("textos distintos"); 102 | } 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /ejemplos/Ej2Herencia/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ej2Herencia/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ej2Herencia 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 | -------------------------------------------------------------------------------- /ejemplos/Ej2Herencia/src/entidades/Alumno.java: -------------------------------------------------------------------------------- 1 | package entidades; 2 | 3 | public class Alumno extends Persona { 4 | 5 | private int legajo; 6 | 7 | public int getLegajo() { 8 | return legajo; 9 | } 10 | 11 | public void setLegajo(int legajo) { 12 | this.legajo = legajo; 13 | } 14 | 15 | public Alumno() { 16 | this.setLegajo(123456); 17 | } 18 | 19 | public Alumno(int legajo, int dni, String apellido, String nombre) { 20 | super(dni, apellido, nombre); 21 | this.setLegajo(legajo); 22 | } 23 | 24 | @Override 25 | public String getDetalle(boolean mostrarDatosSensibles) { 26 | return super.getDetalle(mostrarDatosSensibles)+" - Legajo: "+this.getLegajo(); 27 | } 28 | 29 | @Override 30 | public String getDefClase() { 31 | return "Alumno"; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /ejemplos/Ej2Herencia/src/entidades/Persona.java: -------------------------------------------------------------------------------- 1 | package entidades; 2 | 3 | public class Persona { 4 | private int dni; 5 | private String apellido; 6 | private String nombre; 7 | public int getDni() { 8 | return dni; 9 | } 10 | public void setDni(int dni) { 11 | this.dni = dni; 12 | } 13 | public String getApellido() { 14 | return apellido; 15 | } 16 | public void setApellido(String apellido) { 17 | this.apellido = apellido; 18 | } 19 | public String getNombre() { 20 | return nombre; 21 | } 22 | public void setNombre(String nombre) { 23 | this.nombre = nombre; 24 | } 25 | 26 | public String getDefClase() { 27 | return "Persona"; 28 | } 29 | 30 | public Persona() { 31 | this(0,"Sabe","Nadie"); 32 | } 33 | 34 | public Persona(int dni, String apellido, String nombre) { 35 | this.setDni(dni); 36 | this.setApellido(apellido); 37 | this.setNombre(nombre); 38 | } 39 | 40 | public String getDetalle() { 41 | return this.getDetalle(false); 42 | } 43 | 44 | public String getDetalle(boolean mostrarDatosSensibles) { 45 | String detalle=this.getDefClase()+" - "; 46 | if(mostrarDatosSensibles) { 47 | detalle+=this.getDni()+": "; 48 | } 49 | detalle+=this.getApellido()+", "+this.getNombre(); 50 | 51 | return detalle; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /ejemplos/Ej2Herencia/src/ui/Principal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import entidades.*; 4 | 5 | public class Principal { 6 | 7 | public static void main(String[] args) { 8 | 9 | Persona p1 = new Persona(); 10 | 11 | System.out.println("p1 sin param:: "+p1.getDetalle(true)); 12 | 13 | p1.setDni(11111111); 14 | p1.setApellido("Perez"); 15 | p1.setNombre("Juan"); 16 | 17 | System.out.println("p1 después de set:: "+p1.getDetalle(true)); 18 | 19 | Persona p2 = new Persona(22222222,"Doe","John"); 20 | System.out.println("p2:: "+p2.getDetalle()); 21 | 22 | Alumno a1 = new Alumno(); 23 | 24 | System.out.println("a1:: "+a1.getDetalle(true)); 25 | 26 | Alumno a2= new Alumno(123, 33333333,"Alumno", "Ejemplar"); 27 | 28 | System.out.println("a2:: "+a2.getDetalle()); 29 | 30 | Persona a3 = new Alumno(); 31 | 32 | a3.setDni(44444444); 33 | a3.setApellido("Algo"); 34 | a3.setNombre("Extraño"); 35 | ((Alumno)a3).setLegajo(456); 36 | 37 | System.out.println("a3:: "+a3.getDetalle(true)); 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ej3Colecciones 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 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/src/entities/Person.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Person implements Comparable { 4 | 5 | int dni; 6 | String nombre; 7 | String apellido; 8 | 9 | public int getDni() { 10 | return dni; 11 | } 12 | public void setDni(int dni) { 13 | this.dni = dni; 14 | } 15 | public String getNombre() { 16 | return nombre; 17 | } 18 | public void setNombre(String nombre) { 19 | this.nombre = nombre; 20 | } 21 | public String getApellido() { 22 | return apellido; 23 | } 24 | public void setApellido(String apellido) { 25 | this.apellido = apellido; 26 | } 27 | 28 | public Person(int dni, String nombre, String apellido) { 29 | this.setDni(dni); 30 | this.setNombre(nombre); 31 | this.setApellido(apellido); 32 | } 33 | 34 | 35 | @Override 36 | public String toString() { 37 | return "\nPerson [dni=" + dni + ", nombre=" + nombre + ", apellido=" + apellido + "]"; 38 | } 39 | 40 | 41 | 42 | @Override 43 | public boolean equals(Object obj) { 44 | if (this == obj) { 45 | return true; 46 | } 47 | if (obj == null) { 48 | return false; 49 | } 50 | if (!(obj instanceof Person)) { 51 | return false; 52 | } 53 | Person other = (Person) obj; 54 | if (dni != other.dni) { 55 | return false; 56 | } 57 | return true; 58 | } 59 | 60 | 61 | @Override 62 | public int hashCode() { 63 | final int prime = 31; 64 | int result = 1; 65 | result = prime * result + dni; 66 | return result; 67 | } 68 | 69 | 70 | 71 | @Override 72 | public int compareTo(Person s) { 73 | int res=this.getDni()-s.getDni(); 74 | if (res == 0) { 75 | res=this.getApellido().compareTo(s.getApellido()); 76 | if (res==0) { 77 | res=this.getNombre().compareTo(s.getNombre()); 78 | } 79 | } 80 | return res; 81 | } 82 | 83 | 84 | } 85 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/src/entities/PersonLexicographicComparator.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.util.Comparator; 4 | 5 | public class PersonLexicographicComparator implements Comparator { 6 | 7 | @Override 8 | public int compare(Person p1, Person p2) { 9 | int res=p1.getApellido().compareToIgnoreCase(p2.getApellido()); 10 | if (res==0) { 11 | res=p1.getNombre().compareToIgnoreCase(p2.getNombre()); 12 | if (res==0) { 13 | res=p1.getDni()-p2.getDni(); 14 | } 15 | } 16 | return res; 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/src/ui/UsoArrayList1.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | public class UsoArrayList1 { 7 | 8 | public static void main(String[] args) { 9 | // Creación 10 | ArrayList mamals = new ArrayList<>(); 11 | 12 | // Agregar elementos al final 13 | mamals.add("Dog"); 14 | mamals.add("Horse"); 15 | 16 | // Agregar elementos en una ubicación 17 | System.out.println("Lista inicial"); 18 | System.out.println(mamals); 19 | System.out.println();System.out.println(); 20 | 21 | 22 | System.out.println("Original: "+mamals); 23 | mamals.add(1,"Cat"); 24 | mamals.add(3,"Lion"); 25 | System.out.println("Actual: "+mamals); 26 | System.out.println();System.out.println(); 27 | 28 | // mamals.add(5,"Gorila"); 29 | // Se puede usar el add para agregar elementos en medio 30 | // Se puede indicar también la posición siguiente a la última 31 | // Pero si se excede la posición máxima se causa una excepción 32 | 33 | 34 | 35 | 36 | // Recuperar elementos 37 | System.out.println("Primer elemento"); 38 | System.out.println(mamals.get(0)); 39 | // Las colecciones comienzan en 0 40 | System.out.println();System.out.println(); 41 | 42 | // System.out.println(mamals.get(3)); 43 | // si el índice exede el máximo del ArrayList genera una excepción 44 | 45 | 46 | // Recuperar el tamaño de un ArrayList 47 | System.out.println("Tamaño del ArrayList"); 48 | System.out.println(mamals.size()); 49 | System.out.println();System.out.println(); 50 | 51 | System.out.println("Reemplazando elemento"); 52 | 53 | 54 | // Reemplazar elementos 55 | System.out.println("Original: "+mamals); 56 | mamals.set(2,"Zebra"); 57 | System.out.println("Actual: "+mamals); 58 | System.out.println();System.out.println(); 59 | 60 | //mamals.set(5,"Gorila"); 61 | // Setear un elemento en una posición que no existe genera una excepción 62 | 63 | 64 | // Remover elemenos 65 | System.out.println("Remover elemento por índice"); 66 | System.out.println("Original: "+mamals); 67 | String cat = mamals.remove(1); 68 | System.out.println("Actual: "+mamals); 69 | System.out.println("Removido: "+cat); 70 | System.out.println();System.out.println(); 71 | 72 | // mamals.remove(5); 73 | // Remover un elemento de una posición inexistente genera una excepción 74 | 75 | 76 | System.out.println("Remover elemento por objeto"); 77 | System.out.println("Original: "+mamals); 78 | boolean lionRemoved= mamals.remove("Lion"); 79 | boolean gorilaRemoved= mamals.remove("Gorila"); 80 | System.out.println("Actual: "+mamals); 81 | System.out.println("¿Lion fue removido?: "+lionRemoved); 82 | System.out.println("¿Gorila fue removido?: "+gorilaRemoved); 83 | System.out.println();System.out.println(); 84 | 85 | // Remover un elemento inexistente devuelve false, no genera una excepción 86 | // Remove por objeto utiliza el método equals de la clase 87 | 88 | 89 | // Revisar si un elemento se encuentra en la colección 90 | System.out.println("¿El ArrayList contiene Zebra?: "+ mamals.contains("Zebra")); 91 | System.out.println();System.out.println(); 92 | 93 | // Obtener el índice de un elemento 94 | System.out.println("¿El índice de Dog?: "+ mamals.indexOf("Dog")); 95 | System.out.println("¿El índice de Cow?: "+ mamals.indexOf("Cow")); 96 | System.out.println();System.out.println(); 97 | 98 | 99 | // Agregar multiples elementos 100 | ArrayList animals = new ArrayList<>(); 101 | animals.add("Crocodile"); 102 | animals.addAll(mamals); 103 | 104 | System.out.println("Agregar varios elementos"); 105 | System.out.println(animals); 106 | System.out.println();System.out.println(); 107 | 108 | 109 | // Remover varios elementos 110 | System.out.println("Remover todos los elementos de otro ArrayList"); 111 | animals.removeAll(mamals); 112 | System.out.println(animals); 113 | System.out.println();System.out.println(); 114 | 115 | 116 | // Remover todos los elementos 117 | animals.clear(); 118 | System.out.println("Vaciar un ArrayList"); 119 | System.out.println(animals); 120 | System.out.println();System.out.println(); 121 | 122 | 123 | 124 | // Iterar con for 125 | System.out.println("Iterar con for"); 126 | for(int i = 0; i < mamals.size(); i++) { 127 | System.out.print(mamals.get(i)); 128 | System.out.print(", "); 129 | } 130 | System.out.println();System.out.println(); 131 | 132 | 133 | 134 | // Iterar con foreach 135 | System.out.println("Iterar con foreach"); 136 | for(String animal : mamals) { 137 | System.out.print(animal); 138 | System.out.print(", "); 139 | } 140 | System.out.println();System.out.println(); 141 | 142 | 143 | // Ordenar elementos 144 | mamals.add("Cow"); 145 | mamals.add("Cat"); 146 | System.out.println("Ordenar elementos"); 147 | System.out.println("Original: "+mamals); 148 | Collections.sort(mamals); 149 | System.out.println("Actual: "+mamals); 150 | System.out.println();System.out.println(); 151 | // sort se basa en el método compareTo de la clase. 152 | 153 | } 154 | 155 | } 156 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/src/ui/UsoLinkedList1.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Collections; 5 | 6 | public class UsoLinkedList1 { 7 | 8 | public static void main(String[] args) { 9 | // Creación 10 | LinkedList mamals = new LinkedList<>(); 11 | 12 | // Agregar elementos al final 13 | mamals.add("Dog"); 14 | mamals.add("Horse"); 15 | 16 | // Agregar elementos en una ubicación 17 | System.out.println("Lista inicial"); 18 | System.out.println(mamals); 19 | System.out.println();System.out.println(); 20 | 21 | 22 | System.out.println("Original: "+mamals); 23 | mamals.add(1,"Cat"); 24 | mamals.add(3,"Lion"); 25 | System.out.println("Actual: "+mamals); 26 | System.out.println();System.out.println(); 27 | 28 | // mamals.add(5,"Gorila"); 29 | // Se puede usar el add para agregar elementos en medio 30 | // Se puede indicar también la posición siguiente a la última 31 | // Pero si se excede la posición máxima se causa una excepción 32 | 33 | 34 | 35 | 36 | // Recuperar elementos 37 | System.out.println("Primer elemento"); 38 | System.out.println(mamals.get(0)); 39 | // Las colecciones comienzan en 0 40 | System.out.println();System.out.println(); 41 | 42 | // System.out.println(mamals.get(3)); 43 | // si el índice exede el máximo del LinkedList genera una excepción 44 | 45 | 46 | // Recuperar el tamaño de un LinkedList 47 | System.out.println("Tamaño del LinkedList"); 48 | System.out.println(mamals.size()); 49 | System.out.println();System.out.println(); 50 | 51 | System.out.println("Reemplazando elemento"); 52 | 53 | 54 | // Reemplazar elementos 55 | System.out.println("Original: "+mamals); 56 | mamals.set(2,"Zebra"); 57 | System.out.println("Actual: "+mamals); 58 | System.out.println();System.out.println(); 59 | 60 | //mamals.set(5,"Gorila"); 61 | // Setear un elemento en una posición que no existe genera una excepción 62 | 63 | 64 | // Remover elemenos 65 | System.out.println("Remover elemento por índice"); 66 | System.out.println("Original: "+mamals); 67 | String cat = mamals.remove(1); 68 | System.out.println("Actual: "+mamals); 69 | System.out.println("Removido: "+cat); 70 | System.out.println();System.out.println(); 71 | 72 | // mamals.remove(5); 73 | // Remover un elemento de una posición inexistente genera una excepción 74 | 75 | 76 | System.out.println("Remover elemento por objeto"); 77 | System.out.println("Original: "+mamals); 78 | boolean lionRemoved= mamals.remove("Lion"); 79 | boolean gorilaRemoved= mamals.remove("Gorila"); 80 | System.out.println("Actual: "+mamals); 81 | System.out.println("¿Lion fue removido?: "+lionRemoved); 82 | System.out.println("¿Gorila fue removido?: "+gorilaRemoved); 83 | System.out.println();System.out.println(); 84 | 85 | // Remover un elemento inexistente devuelve false, no genera una excepción 86 | // Remove por objeto utiliza el método equals de la clase 87 | 88 | 89 | // Revisar si un elemento se encuentra en la colección 90 | System.out.println("¿El LinkedList contiene Zebra?: "+ mamals.contains("Zebra")); 91 | System.out.println();System.out.println(); 92 | 93 | // Obtener el índice de un elemento 94 | System.out.println("¿El índice de Dog?: "+ mamals.indexOf("Dog")); 95 | System.out.println("¿El índice de Cow?: "+ mamals.indexOf("Cow")); 96 | System.out.println();System.out.println(); 97 | 98 | 99 | // Agregar multiples elementos 100 | LinkedList animals = new LinkedList<>(); 101 | animals.add("Crocodile"); 102 | animals.addAll(mamals); 103 | 104 | System.out.println("Agregar varios elementos"); 105 | System.out.println(animals); 106 | System.out.println();System.out.println(); 107 | 108 | 109 | // Remover varios elementos 110 | System.out.println("Remover todos los elementos de otro LinkedList"); 111 | animals.removeAll(mamals); 112 | System.out.println(animals); 113 | System.out.println();System.out.println(); 114 | 115 | 116 | // Remover todos los elementos 117 | animals.clear(); 118 | System.out.println("Vaciar un LinkedList"); 119 | System.out.println(animals); 120 | System.out.println();System.out.println(); 121 | 122 | 123 | 124 | // Iterar con for 125 | System.out.println("Iterar con for"); 126 | for(int i = 0; i < mamals.size(); i++) { 127 | System.out.print(mamals.get(i)); 128 | System.out.print(", "); 129 | } 130 | System.out.println();System.out.println(); 131 | 132 | 133 | 134 | // Iterar con foreach 135 | System.out.println("Iterar con foreach"); 136 | for(String animal : mamals) { 137 | System.out.print(animal); 138 | System.out.print(", "); 139 | } 140 | System.out.println();System.out.println(); 141 | 142 | 143 | // Ordenar elementos 144 | mamals.add("Cow"); 145 | mamals.add("Cat"); 146 | System.out.println("Ordenar elementos"); 147 | System.out.println("Original: "+mamals); 148 | Collections.sort(mamals); 149 | System.out.println("Actual: "+mamals); 150 | System.out.println();System.out.println(); 151 | // sort se basa en el método compareTo de la clase. 152 | 153 | } 154 | 155 | } 156 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/src/ui/UsoLinkedList2.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class UsoLinkedList2 { 6 | 7 | public static void main(String[] args) { 8 | // Creación 9 | LinkedList mamals = new LinkedList<>(); 10 | 11 | // Agregar elementos 12 | mamals.add("Dog"); 13 | mamals.add("Horse"); 14 | mamals.addFirst("Cat"); 15 | mamals.addLast("Lion"); 16 | 17 | System.out.println("Lista inicial"); 18 | System.out.println(mamals); 19 | System.out.println();System.out.println(); 20 | 21 | 22 | // Recuperar elementos sin alterar la colección 23 | System.out.println("Recuperar elementos"); 24 | System.out.println("get(2): "+mamals.get(2)); 25 | System.out.println("getFirst(): "+mamals.getFirst()); 26 | System.out.println("getLast(): "+mamals.getLast()); 27 | System.out.println("peek(): "+mamals.peek()); 28 | System.out.println("peekFirst(): "+mamals.peekFirst()); 29 | System.out.println("peekLast(): "+mamals.peekLast()); 30 | System.out.println();System.out.println(); 31 | 32 | 33 | System.out.println("Lista"); 34 | System.out.println(mamals); 35 | System.out.println();System.out.println(); 36 | 37 | 38 | // RemoverElementos 39 | System.out.println("Remover elementos"); 40 | //se puede utilizar remove por índice y por objeto al igual que en un ArrayList 41 | 42 | System.out.println("Original: "+mamals); 43 | String primerElemento = mamals.removeFirst(); 44 | String ultimoElemento = mamals.removeLast(); 45 | System.out.println("Actual: "+mamals); 46 | System.out.println("Primero: "+primerElemento+" - Ultimo: "+ultimoElemento); 47 | System.out.println();System.out.println(); 48 | 49 | 50 | 51 | //Otras formas de agregar y remover elementos compatibles con queues y otros lenguajes 52 | 53 | System.out.println("Original: "+mamals); 54 | mamals.push("Tiger"); //agrega al principio 55 | mamals.offer("Gorila"); //agrega al final, pero existen offerFirst y offerLast 56 | System.out.println("Luego de agregar: "+mamals); 57 | 58 | String primero = mamals.poll(); //remueve el primero 59 | String nuevoPrimero = mamals.pop(); //remueve el primero 60 | System.out.println("Primero: "+primero+" - Segundo: "+nuevoPrimero); 61 | System.out.println("Actual: "+mamals); 62 | System.out.println();System.out.println(); 63 | 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /ejemplos/Ej3Colecciones/src/ui/UsoLinkedList3.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.util.Collections; 4 | import java.util.LinkedList; 5 | import entities.*; 6 | 7 | public class UsoLinkedList3 { 8 | 9 | public static void main(String[] args) { 10 | 11 | LinkedList persons = new LinkedList<>(); 12 | 13 | Person p=new Person(11111111,"John","Doe"); 14 | Person p1=new Person(22222222,"Juan","Perez"); 15 | 16 | persons.add(p); 17 | persons.push(p1); 18 | persons.add(new Person(33333333, "Fulano", "de Tal")); 19 | 20 | 21 | System.out.println("Uso de toString"); 22 | System.out.println(persons); 23 | 24 | System.out.println();System.out.println(); 25 | 26 | System.out.println("persons.get(1): "+persons.get(1)); 27 | System.out.println();System.out.println(); 28 | 29 | 30 | 31 | Person pCopy=new Person(11111111,"Johny","Doe"); 32 | 33 | System.out.println("Uso de equals"); 34 | System.out.println("Contains pCopy: "+persons.contains(pCopy)); 35 | System.out.println();System.out.println(); 36 | 37 | System.out.println("Uso de equals"); 38 | System.out.println("Contains p: "+persons.contains(p)); 39 | System.out.println();System.out.println(); 40 | 41 | 42 | 43 | persons.add(pCopy); 44 | System.out.println("Uso de Comparable y compareTo"); 45 | System.out.println("Unsorted:"); 46 | System.out.println(persons); 47 | System.out.println();System.out.println(); 48 | Collections.sort(persons); 49 | System.out.println("Sorted:"); 50 | System.out.println(persons); 51 | 52 | 53 | 54 | System.out.println("Uso de Comparators"); 55 | System.out.println("Sorted by compareTo:"); 56 | System.out.println(persons); 57 | System.out.println();System.out.println(); 58 | Collections.sort(persons,new PersonLexicographicComparator()); 59 | System.out.println("Sorted by comparator:"); 60 | System.out.println(persons); 61 | 62 | /**/ 63 | 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /ejemplos/Ej4JDBC/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ej4JDBC/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ej4JDBC 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 | -------------------------------------------------------------------------------- /ejemplos/Ej4JDBC/lib/mysql-connector-java-8.0.20.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ej4JDBC/lib/mysql-connector-java-8.0.20.jar -------------------------------------------------------------------------------- /ejemplos/Ej4JDBC/src/entities/Documento.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Documento { 4 | 5 | private String tipo; 6 | private int nro; 7 | 8 | public String getTipo() { 9 | return tipo; 10 | } 11 | public void setTipo(String tipo) { 12 | this.tipo = tipo; 13 | } 14 | public int getNro() { 15 | return nro; 16 | } 17 | public void setNro(int nro) { 18 | this.nro = nro; 19 | } 20 | @Override 21 | public String toString() { 22 | return "Documento [tipo=" + tipo + ", nro=" + nro + "]"; 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /ejemplos/Ej4JDBC/src/entities/Persona.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Persona { 4 | 5 | private int id; 6 | private String nombre; 7 | private String apellido; 8 | private boolean habilitado; 9 | private Documento documento; 10 | 11 | public int getId() { 12 | return id; 13 | } 14 | public void setId(int id) { 15 | this.id = id; 16 | } 17 | public String getNombre() { 18 | return nombre; 19 | } 20 | public void setNombre(String nombre) { 21 | this.nombre = nombre; 22 | } 23 | public String getApellido() { 24 | return apellido; 25 | } 26 | public void setApellido(String apellido) { 27 | this.apellido = apellido; 28 | } 29 | public boolean isHabilitado() { 30 | return habilitado; 31 | } 32 | public void setHabilitado(boolean habilitado) { 33 | this.habilitado = habilitado; 34 | } 35 | public Documento getDocumento() { 36 | return documento; 37 | } 38 | public void setDocumento(Documento documento) { 39 | this.documento = documento; 40 | } 41 | @Override 42 | public String toString() { 43 | return "\nPersona [id=" + id + ", nombre=" + nombre + ", apellido=" + apellido + ", habilitado=" + habilitado 44 | + ", documento=" + documento + "]"; 45 | } 46 | 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /ejemplos/Ej4JDBC/src/steps.md: -------------------------------------------------------------------------------- 1 | # JDBC - Pasos para setear y configurar jdbc 2 | 3 | ## Pasos para preparar la base de datos 4 | * Descargar e instalar mysql o uno de sus forks (mysql 8 o 5.7, mariadb 10.3, percona server 8 o 5.7) 5 | * Crear la base de datos javaTest con un manager o usando el siguiente código 6 | 7 | ```sql 8 | CREATE DATABASE /*!32312 IF NOT EXISTS*/ `javaTest` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; 9 | 10 | USE `javaTest`; 11 | 12 | DROP TABLE IF EXISTS `persona`; 13 | 14 | CREATE TABLE `persona` ( 15 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 16 | `tipo_doc` varchar(255) NOT NULL, 17 | `nro_doc` int NOT NULL, 18 | `nombre` varchar(255) NOT NULL, 19 | `apellido` varchar(255) NOT NULL, 20 | `estaHabilitado` tinyint(1) NOT NULL, 21 | PRIMARY KEY (`id`) 22 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 23 | 24 | INSERT INTO `persona` VALUES (1,'dni',11111111,'John','Doe',1),(2,'dni',22222222,'Juan','Perez',0); 25 | ``` 26 | 27 | * Crear el usuario para conectarse 28 | 29 | ```sql 30 | create user java@'%' identified by 'himitsu'; 31 | 32 | grant select, insert, update, delete on javaTest.* to java@'%'; 33 | ``` 34 | 35 | ### En casos de falla 36 | En caso que fallara la creación de la db o el usuario puede eliminarlps con el siguiente código y volver a intentarlo. 37 | 38 | ```sql 39 | DROP DATABASE `javaTest`; 40 | DROP USEr java@'%'; 41 | ``` 42 | 43 | ## Pasos para setear el conector 44 | 1. Descargar Connector/J platform independent y extraer el contenido. 45 | 2. Crear el directorio lib dentro del proyecto al mismo nivel de src, eligiendo la opción source folder. Atención no usar folder, usar source folder. 46 | 3. Copiar mysql-connector-java-8.0.20.jar dentro de lib/ 47 | 4. Botón derecho sobre el mysql-connector-java-8.0.20.jar hacer click en Build Path -> Add to build path 48 | 5. Si usa git, agregar el .jar del conector como excepción al .gitignore, (adaptarlo al directorio) por ejemplo en este proyecto 49 | ``` 50 | # Whitelist connector/j # 51 | !/ejemplos/Ej4JDBC/lib/*.jar 52 | ``` 53 | -------------------------------------------------------------------------------- /ejemplos/Ej4JDBC/src/ui/Principal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import entities.*; 4 | import java.sql.*; 5 | import java.util.LinkedList; 6 | 7 | public class Principal { 8 | 9 | public static void main(String[] args) { 10 | 11 | // registrar el conector 12 | try { 13 | Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); 14 | } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { 15 | e.printStackTrace(); 16 | } 17 | 18 | recuperarTodos(); 19 | 20 | recuperarPorParametro(); 21 | 22 | insertarNuevo(); 23 | } 24 | 25 | private static void recuperarTodos() { 26 | Connection conn = null; 27 | LinkedList personas = new LinkedList<>(); 28 | try { 29 | // crear una conexión 30 | conn = 31 | DriverManager.getConnection("jdbc:mysql://localhost/javaTest","java","himitsu"); 32 | //DriverManager.getConnection("jdbc:mysql://localhost/javaTest?user=java&password=himitsu"); 33 | 34 | // ejecutar la query 35 | Statement stmt = conn.createStatement(); 36 | ResultSet rs= stmt.executeQuery("select * from persona"); 37 | 38 | // mapear de resultset a objeto 39 | while(rs.next()) { 40 | Persona p=new Persona(); 41 | Documento d=new Documento(); 42 | p.setDocumento(d); 43 | 44 | p.setId(rs.getInt("id")); 45 | d.setNro(rs.getInt("nro_doc")); 46 | d.setTipo(rs.getString("tipo_doc")); 47 | p.setNombre(rs.getString("nombre")); 48 | p.setApellido(rs.getString("apellido")); 49 | p.setHabilitado(rs.getBoolean("estaHabilitado")); 50 | 51 | personas.add(p); 52 | 53 | } 54 | //cerrar recursos 55 | if(rs!=null){rs.close();} 56 | if(stmt!=null){stmt.close();} 57 | 58 | conn.close(); 59 | 60 | // mostrar info 61 | System.out.println("Listado Completo"); 62 | System.out.println(personas); 63 | System.out.println();System.out.println(); 64 | 65 | } catch (SQLException ex) { 66 | // Manejo de errores 67 | System.out.println("SQLException: " + ex.getMessage()); 68 | System.out.println("SQLState: " + ex.getSQLState()); 69 | System.out.println("VendorError: " + ex.getErrorCode()); 70 | } 71 | } 72 | 73 | private static void recuperarPorParametro() { 74 | Connection conn = null; 75 | 76 | try { 77 | // crear una conexión 78 | conn = 79 | DriverManager.getConnection("jdbc:mysql://localhost/javaTest","java","himitsu"); 80 | 81 | // definir la query 82 | PreparedStatement stmt = conn.prepareStatement("select * from persona where id=?"); 83 | 84 | // setear el/los parámetros 85 | stmt.setInt(1, 2); 86 | 87 | Persona p=new Persona(); 88 | Documento d=new Documento(); 89 | p.setDocumento(d); 90 | 91 | // ejecutar query y obtener resultados 92 | ResultSet rs= stmt.executeQuery(); 93 | 94 | // mapear de resultset a objeto 95 | if(rs.next()) { 96 | p.setId(rs.getInt("id")); 97 | d.setNro(rs.getInt("nro_doc")); 98 | d.setTipo(rs.getString("tipo_doc")); 99 | p.setNombre(rs.getString("nombre")); 100 | p.setApellido(rs.getString("apellido")); 101 | p.setHabilitado(rs.getBoolean("estaHabilitado")); 102 | 103 | } 104 | //cerrar recursos 105 | if(rs!=null){rs.close();} 106 | if(stmt!=null){stmt.close();} 107 | 108 | conn.close(); 109 | 110 | // mostrar objeto 111 | System.out.println("Buscar por id"); 112 | System.out.println(p); 113 | System.out.println();System.out.println(); 114 | 115 | } catch (SQLException ex) { 116 | // Manejo de errores 117 | System.out.println("SQLException: " + ex.getMessage()); 118 | System.out.println("SQLState: " + ex.getSQLState()); 119 | System.out.println("VendorError: " + ex.getErrorCode()); 120 | } 121 | } 122 | 123 | private static void insertarNuevo() { 124 | Connection conn = null; 125 | Persona pIns= new Persona(); 126 | Documento documento= new Documento(); 127 | 128 | documento.setTipo("dni"); 129 | documento.setNro(33333333); 130 | pIns.setDocumento(documento); 131 | 132 | pIns.setNombre("Someone"); 133 | pIns.setApellido("Else"); 134 | pIns.setHabilitado(true); 135 | 136 | try { 137 | // crear una conexión 138 | conn = 139 | DriverManager.getConnection("jdbc:mysql://localhost/javaTest","java","himitsu"); 140 | 141 | // definir la query 142 | PreparedStatement pstmt = conn.prepareStatement( 143 | "insert into persona(tipo_doc,nro_doc,nombre,apellido,estaHabilitado) values (?,?,?,?,?)" 144 | ,PreparedStatement.RETURN_GENERATED_KEYS 145 | ); 146 | 147 | 148 | pstmt.setString(1, pIns.getDocumento().getTipo()); 149 | pstmt.setInt(2, pIns.getDocumento().getNro()); 150 | pstmt.setString(3, pIns.getNombre()); 151 | pstmt.setString(4, pIns.getApellido()); 152 | pstmt.setBoolean(5, pIns.isHabilitado()); 153 | 154 | pstmt.executeUpdate(); 155 | 156 | ResultSet keyResultSet=pstmt.getGeneratedKeys(); 157 | 158 | if(keyResultSet!=null && keyResultSet.next()) { 159 | int id=keyResultSet.getInt(1); 160 | System.out.println("ID: "+id); 161 | pIns.setId(id); 162 | } 163 | 164 | 165 | if(keyResultSet!=null){keyResultSet.close();} 166 | if(pstmt!=null){pstmt.close();} 167 | 168 | conn.close(); 169 | 170 | // mostrar objeto 171 | System.out.println("Nueva Persona"); 172 | System.out.println(pIns); 173 | System.out.println();System.out.println(); 174 | 175 | } catch (SQLException ex) { 176 | // Manejo de errores 177 | System.out.println("SQLException: " + ex.getMessage()); 178 | System.out.println("SQLState: " + ex.getSQLState()); 179 | System.out.println("VendorError: " + ex.getErrorCode()); 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ej5AccesoADatos 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 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/db/dbJava.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.15 Distrib 10.0.38-MariaDB, for debian-linux-gnu (x86_64) 2 | -- 3 | -- Host: localhost Database: java 4 | -- ------------------------------------------------------ 5 | -- Server version 10.0.38-MariaDB-0ubuntu0.16.04.1 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8mb4 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Current Database: `java` 20 | -- 21 | 22 | CREATE DATABASE /*!32312 IF NOT EXISTS*/ `java` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; 23 | 24 | USE `java`; 25 | 26 | -- 27 | -- Table structure for table `persona` 28 | -- 29 | 30 | DROP TABLE IF EXISTS `persona`; 31 | /*!40101 SET @saved_cs_client = @@character_set_client */; 32 | /*!40101 SET character_set_client = utf8 */; 33 | CREATE TABLE `persona` ( 34 | `id` int(11) NOT NULL AUTO_INCREMENT, 35 | `tipo_doc` varchar(10) NOT NULL, 36 | `nro_doc` varchar(45) NOT NULL, 37 | `nombre` varchar(255) NOT NULL, 38 | `apellido` varchar(255) NOT NULL, 39 | `email` varchar(255) DEFAULT NULL, 40 | `tel` varchar(255) DEFAULT NULL, 41 | `habilitado` tinyint(1) NOT NULL, 42 | `password` varchar(255) NOT NULL, 43 | PRIMARY KEY (`id`) 44 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4; 45 | /*!40101 SET character_set_client = @saved_cs_client */; 46 | 47 | -- 48 | -- Dumping data for table `persona` 49 | -- 50 | 51 | LOCK TABLES `persona` WRITE; 52 | /*!40000 ALTER TABLE `persona` DISABLE KEYS */; 53 | INSERT INTO `persona` VALUES (1,'dni','10101010','Juan','Perez','jp@gmail.com','4101010',1,'jperez'),(2,'dni','12121212','John','Doe','contacto@jd','4121212',0,'jdoe'),(3,'dni','13131313','Nadie','Sabe','ns@ns.com','4131313',1,'nsabe'),(4,'cuit','14141414141','Identidad','Desconocida','unknown@gmail.com','4141414',0,'idesconocida'),(5,'cuit','15151515151','Alguien','Más','am@gmail.com','4151515',1,'amas'),(6,'dni','16161616','Otra','Persona','op@gmail.com','4161616',0,'opersona'); 54 | /*!40000 ALTER TABLE `persona` ENABLE KEYS */; 55 | UNLOCK TABLES; 56 | 57 | -- 58 | -- Table structure for table `rol` 59 | -- 60 | 61 | DROP TABLE IF EXISTS `rol`; 62 | /*!40101 SET @saved_cs_client = @@character_set_client */; 63 | /*!40101 SET character_set_client = utf8 */; 64 | CREATE TABLE `rol` ( 65 | `id` int(11) NOT NULL AUTO_INCREMENT, 66 | `descripcion` varchar(255) NOT NULL, 67 | PRIMARY KEY (`id`) 68 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4; 69 | /*!40101 SET character_set_client = @saved_cs_client */; 70 | 71 | -- 72 | -- Dumping data for table `rol` 73 | -- 74 | 75 | LOCK TABLES `rol` WRITE; 76 | /*!40000 ALTER TABLE `rol` DISABLE KEYS */; 77 | INSERT INTO `rol` VALUES (1,'admin'),(2,'user'); 78 | /*!40000 ALTER TABLE `rol` ENABLE KEYS */; 79 | UNLOCK TABLES; 80 | 81 | -- 82 | -- Table structure for table `rol_persona` 83 | -- 84 | 85 | DROP TABLE IF EXISTS `rol_persona`; 86 | /*!40101 SET @saved_cs_client = @@character_set_client */; 87 | /*!40101 SET character_set_client = utf8 */; 88 | CREATE TABLE `rol_persona` ( 89 | `id_persona` int(11) NOT NULL, 90 | `id_rol` int(11) NOT NULL, 91 | PRIMARY KEY (`id_persona`,`id_rol`), 92 | KEY `rol_persona_rol_fk` (`id_rol`), 93 | CONSTRAINT `rol_persona_persona_fk` FOREIGN KEY (`id_persona`) REFERENCES `persona` (`id`), 94 | CONSTRAINT `rol_persona_rol_fk` FOREIGN KEY (`id_rol`) REFERENCES `rol` (`id`) 95 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 96 | /*!40101 SET character_set_client = @saved_cs_client */; 97 | 98 | -- 99 | -- Dumping data for table `rol_persona` 100 | -- 101 | 102 | LOCK TABLES `rol_persona` WRITE; 103 | /*!40000 ALTER TABLE `rol_persona` DISABLE KEYS */; 104 | INSERT INTO `rol_persona` VALUES (1,1),(2,2),(3,1),(3,2),(4,2),(5,2),(6,2); 105 | /*!40000 ALTER TABLE `rol_persona` ENABLE KEYS */; 106 | UNLOCK TABLES; 107 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 108 | 109 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 110 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 111 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 112 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 113 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 114 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 115 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 116 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/db/userJava.sql: -------------------------------------------------------------------------------- 1 | -- 2 | -- User java 3 | -- 4 | 5 | create user 'java'@'%' identified by 'himitsu'; 6 | GRANT SELECT, INSERT, UPDATE, DELETE ON `java`.* TO 'java'@'%'; 7 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/lib/mysql-connector-java-8.0.20.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ej5AccesoADatos/lib/mysql-connector-java-8.0.20.jar -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/data/DataPersona.java: -------------------------------------------------------------------------------- 1 | package data; 2 | //orig 3 | import entities.*; 4 | 5 | import java.sql.*; 6 | import java.util.LinkedList; 7 | 8 | public class DataPersona { 9 | 10 | public LinkedList getAll(){ 11 | DataRol dr=new DataRol(); 12 | Statement stmt=null; 13 | ResultSet rs=null; 14 | LinkedList pers= new LinkedList<>(); 15 | 16 | try { 17 | stmt= DbConnector.getInstancia().getConn().createStatement(); 18 | rs= stmt.executeQuery("select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona"); 19 | //intencionalmente no se recupera la password 20 | if(rs!=null) { 21 | while(rs.next()) { 22 | Persona p=new Persona(); 23 | p.setDocumento(new Documento()); 24 | p.setId(rs.getInt("id")); 25 | p.setNombre(rs.getString("nombre")); 26 | p.setApellido(rs.getString("apellido")); 27 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 28 | p.getDocumento().setNro(rs.getString("nro_doc")); 29 | p.setEmail(rs.getString("email")); 30 | p.setTel(rs.getString("tel")); 31 | 32 | p.setHabilitado(rs.getBoolean("habilitado")); 33 | 34 | dr.setRoles(p); 35 | 36 | pers.add(p); 37 | } 38 | } 39 | 40 | } catch (SQLException e) { 41 | e.printStackTrace(); 42 | 43 | } finally { 44 | try { 45 | if(rs!=null) {rs.close();} 46 | if(stmt!=null) {stmt.close();} 47 | DbConnector.getInstancia().releaseConn(); 48 | } catch (SQLException e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | 53 | 54 | return pers; 55 | } 56 | 57 | public Persona getByUser(Persona per) { 58 | DataRol dr=new DataRol(); 59 | Persona p=null; 60 | PreparedStatement stmt=null; 61 | ResultSet rs=null; 62 | try { 63 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 64 | "select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona where email=? and password=?" 65 | ); 66 | stmt.setString(1, per.getEmail()); 67 | stmt.setString(2, per.getPassword()); 68 | rs=stmt.executeQuery(); 69 | if(rs!=null && rs.next()) { 70 | p=new Persona(); 71 | p.setDocumento(new Documento()); 72 | p.setId(rs.getInt("id")); 73 | p.setNombre(rs.getString("nombre")); 74 | p.setApellido(rs.getString("apellido")); 75 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 76 | p.getDocumento().setNro(rs.getString("nro_doc")); 77 | p.setEmail(rs.getString("email")); 78 | p.setTel(rs.getString("tel")); 79 | p.setHabilitado(rs.getBoolean("habilitado")); 80 | // 81 | dr.setRoles(p); 82 | } 83 | } catch (SQLException e) { 84 | e.printStackTrace(); 85 | }finally { 86 | try { 87 | if(rs!=null) {rs.close();} 88 | if(stmt!=null) {stmt.close();} 89 | DbConnector.getInstancia().releaseConn(); 90 | } catch (SQLException e) { 91 | e.printStackTrace(); 92 | } 93 | } 94 | 95 | return p; 96 | } 97 | 98 | public Persona getByDocumento(Persona per) { 99 | DataRol dr=new DataRol(); 100 | Persona p=null; 101 | PreparedStatement stmt=null; 102 | ResultSet rs=null; 103 | try { 104 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 105 | "select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona where tipo_doc=? and nro_doc=?" 106 | ); 107 | stmt.setString(1, per.getDocumento().getTipo()); 108 | stmt.setString(2, per.getDocumento().getNro()); 109 | rs=stmt.executeQuery(); 110 | if(rs!=null && rs.next()) { 111 | p=new Persona(); 112 | p.setDocumento(new Documento()); 113 | p.setId(rs.getInt("id")); 114 | p.setNombre(rs.getString("nombre")); 115 | p.setApellido(rs.getString("apellido")); 116 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 117 | p.getDocumento().setNro(rs.getString("nro_doc")); 118 | p.setEmail(rs.getString("email")); 119 | p.setTel(rs.getString("tel")); 120 | p.setHabilitado(rs.getBoolean("habilitado")); 121 | // 122 | dr.setRoles(p); 123 | } 124 | } catch (SQLException e) { 125 | e.printStackTrace(); 126 | }finally { 127 | try { 128 | if(rs!=null) {rs.close();} 129 | if(stmt!=null) {stmt.close();} 130 | DbConnector.getInstancia().releaseConn(); 131 | } catch (SQLException e) { 132 | e.printStackTrace(); 133 | } 134 | } 135 | 136 | return p; 137 | } 138 | 139 | public void add(Persona p) { 140 | PreparedStatement stmt= null; 141 | ResultSet keyResultSet=null; 142 | try { 143 | stmt=DbConnector.getInstancia().getConn(). 144 | prepareStatement( 145 | "insert into persona(nombre, apellido, tipo_doc, nro_doc, email, password, tel, habilitado) values(?,?,?,?,?,?,?,?)", 146 | PreparedStatement.RETURN_GENERATED_KEYS 147 | ); 148 | stmt.setString(1, p.getNombre()); 149 | stmt.setString(2, p.getApellido()); 150 | stmt.setString(3, p.getDocumento().getTipo()); 151 | stmt.setString(4, p.getDocumento().getNro()); 152 | stmt.setString(5, p.getEmail()); 153 | stmt.setString(6, p.getPassword()); 154 | stmt.setString(7, p.getTel()); 155 | stmt.setBoolean(8, p.isHabilitado()); 156 | stmt.executeUpdate(); 157 | 158 | keyResultSet=stmt.getGeneratedKeys(); 159 | if(keyResultSet!=null && keyResultSet.next()){ 160 | p.setId(keyResultSet.getInt(1)); 161 | } 162 | 163 | 164 | } catch (SQLException e) { 165 | e.printStackTrace(); 166 | } finally { 167 | try { 168 | if(keyResultSet!=null)keyResultSet.close(); 169 | if(stmt!=null)stmt.close(); 170 | DbConnector.getInstancia().releaseConn(); 171 | } catch (SQLException e) { 172 | e.printStackTrace(); 173 | } 174 | } 175 | } 176 | 177 | 178 | } 179 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/data/DataRol.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.ResultSet; 5 | import java.sql.SQLException; 6 | import java.sql.Statement; 7 | import java.util.LinkedList; 8 | import entities.*; 9 | 10 | public class DataRol { 11 | 12 | public LinkedList getAll(){ 13 | Statement stmt=null; 14 | ResultSet rs=null; 15 | LinkedList roles= new LinkedList<>(); 16 | 17 | try { 18 | stmt= DbConnector.getInstancia().getConn().createStatement(); 19 | rs= stmt.executeQuery("select * from rol"); 20 | if(rs!=null) { 21 | while(rs.next()) { 22 | Rol r=new Rol(); 23 | r.setId(rs.getInt("id")); 24 | r.setDescripcion(rs.getString("descripcion")); 25 | roles.add(r); 26 | } 27 | } 28 | 29 | } catch (SQLException e) { 30 | e.printStackTrace(); 31 | 32 | } finally { 33 | try { 34 | if(rs!=null) {rs.close();} 35 | if(stmt!=null) {stmt.close();} 36 | DbConnector.getInstancia().releaseConn(); 37 | } catch (SQLException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | 42 | 43 | return roles; 44 | } 45 | 46 | public Rol getById(Rol rolToSearch) { 47 | Rol r=null; 48 | PreparedStatement stmt=null; 49 | ResultSet rs=null; 50 | try { 51 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 52 | "select * from rol where id=?" 53 | ); 54 | stmt.setInt(1, rolToSearch.getId()); 55 | rs=stmt.executeQuery(); 56 | if(rs!=null && rs.next()) { 57 | r=new Rol(); 58 | r.setId(rs.getInt("id")); 59 | r.setDescripcion(rs.getString("descripcion")); 60 | } 61 | } catch (SQLException e) { 62 | e.printStackTrace(); 63 | }finally { 64 | try { 65 | if(rs!=null) {rs.close();} 66 | if(stmt!=null) {stmt.close();} 67 | DbConnector.getInstancia().releaseConn(); 68 | } catch (SQLException e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | 73 | return r; 74 | } 75 | 76 | public Rol getByDesc(Rol rolToSearch) { 77 | Rol r=null; 78 | PreparedStatement stmt=null; 79 | ResultSet rs=null; 80 | try { 81 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 82 | "select * from rol where descripcion=?" 83 | ); 84 | stmt.setString(1, rolToSearch.getDescripcion()); 85 | rs=stmt.executeQuery(); 86 | if(rs!=null && rs.next()) { 87 | r=new Rol(); 88 | r.setId(rs.getInt("id")); 89 | r.setDescripcion(rs.getString("descripcion")); 90 | } 91 | } catch (SQLException e) { 92 | e.printStackTrace(); 93 | }finally { 94 | try { 95 | if(rs!=null) {rs.close();} 96 | if(stmt!=null) {stmt.close();} 97 | DbConnector.getInstancia().releaseConn(); 98 | } catch (SQLException e) { 99 | e.printStackTrace(); 100 | } 101 | } 102 | 103 | return r; 104 | } 105 | 106 | public void setRoles(Persona per) { 107 | PreparedStatement stmt=null; 108 | ResultSet rs=null; 109 | try { 110 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 111 | "select rol.* " 112 | + "from rol " 113 | + "inner join rol_persona " 114 | + "on rol.id=rol_persona.id_rol " 115 | + "where id_persona=?" 116 | ); 117 | stmt.setInt(1, per.getId()); 118 | rs= stmt.executeQuery(); 119 | if(rs!=null) { 120 | while(rs.next()) { 121 | Rol r=new Rol(); 122 | r.setId(rs.getInt("id")); 123 | r.setDescripcion(rs.getString("descripcion")); 124 | per.addRol(r);; 125 | } 126 | } 127 | 128 | } catch (SQLException e) { 129 | e.printStackTrace(); 130 | }finally { 131 | try { 132 | if(rs!=null) {rs.close();} 133 | if(stmt!=null) {stmt.close();} 134 | DbConnector.getInstancia().releaseConn(); 135 | } catch (SQLException e) { 136 | e.printStackTrace(); 137 | } 138 | } 139 | } 140 | 141 | public void add(Rol rol) { 142 | PreparedStatement stmt= null; 143 | ResultSet keyResultSet=null; 144 | try { 145 | stmt=DbConnector.getInstancia().getConn(). 146 | prepareStatement( 147 | "insert into rol(descripcion) values(?)", 148 | PreparedStatement.RETURN_GENERATED_KEYS 149 | ); 150 | stmt.setString(1, rol.getDescripcion()); 151 | stmt.executeUpdate(); 152 | 153 | keyResultSet=stmt.getGeneratedKeys(); 154 | if(keyResultSet!=null && keyResultSet.next()){ 155 | rol.setId(keyResultSet.getInt(1)); 156 | } 157 | 158 | 159 | } catch (SQLException e) { 160 | e.printStackTrace(); 161 | } finally { 162 | try { 163 | if(keyResultSet!=null)keyResultSet.close(); 164 | if(stmt!=null)stmt.close(); 165 | DbConnector.getInstancia().releaseConn(); 166 | } catch (SQLException e) { 167 | e.printStackTrace(); 168 | } 169 | } 170 | 171 | } 172 | 173 | public void update(Rol rol) { 174 | PreparedStatement stmt= null; 175 | try { 176 | stmt=DbConnector.getInstancia().getConn(). 177 | prepareStatement( 178 | "update rol set descripcion=? where id=?"); 179 | stmt.setString(1, rol.getDescripcion()); 180 | stmt.setInt(2, rol.getId()); 181 | stmt.executeUpdate(); 182 | } catch (SQLException e) { 183 | e.printStackTrace(); 184 | } finally { 185 | try { 186 | if(stmt!=null)stmt.close(); 187 | DbConnector.getInstancia().releaseConn(); 188 | } catch (SQLException e) { 189 | e.printStackTrace(); 190 | } 191 | } 192 | } 193 | 194 | public void remove(Rol rol) { 195 | PreparedStatement stmt= null; 196 | try { 197 | stmt=DbConnector.getInstancia().getConn(). 198 | prepareStatement( 199 | "delete from rol where id=?"); 200 | stmt.setInt(1, rol.getId()); 201 | stmt.executeUpdate(); 202 | } catch (SQLException e) { 203 | e.printStackTrace(); 204 | } finally { 205 | try { 206 | if(stmt!=null)stmt.close(); 207 | DbConnector.getInstancia().releaseConn(); 208 | } catch (SQLException e) { 209 | e.printStackTrace(); 210 | } 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/data/DbConnector.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.*; 4 | 5 | public class DbConnector { 6 | 7 | private static DbConnector instancia; 8 | 9 | private String driver="com.mysql.cj.jdbc.Driver"; 10 | private String host="localhost"; 11 | private String port="3306"; 12 | private String user="java"; 13 | private String password="himitsu"; 14 | private String db="java"; 15 | private int conectados=0; 16 | private Connection conn=null; 17 | 18 | private DbConnector() { 19 | try { 20 | Class.forName(driver); 21 | } catch (ClassNotFoundException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | 26 | public static DbConnector getInstancia() { 27 | if (instancia == null) { 28 | instancia = new DbConnector(); 29 | } 30 | return instancia; 31 | } 32 | 33 | public Connection getConn() { 34 | try { 35 | if(conn==null || conn.isClosed()) { 36 | conn=DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+db, user, password); 37 | conectados=0; 38 | } 39 | } catch (SQLException e) { 40 | e.printStackTrace(); 41 | } 42 | conectados++; 43 | return conn; 44 | } 45 | 46 | public void releaseConn() { 47 | conectados--; 48 | try { 49 | if (conectados<=0) { 50 | conn.close(); 51 | } 52 | } catch (SQLException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/entities/Documento.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Documento { 4 | private String tipo; 5 | private String nro; 6 | public String getTipo() { 7 | return tipo; 8 | } 9 | public void setTipo(String tipo) { 10 | this.tipo = tipo; 11 | } 12 | public String getNro() { 13 | return nro; 14 | } 15 | public void setNro(String nro) { 16 | this.nro = nro; 17 | } 18 | @Override 19 | public String toString() { 20 | return "Documento [tipo=" + tipo + ", nro=" + nro + "]"; 21 | } 22 | 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/entities/Persona.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Persona { 6 | private int id; 7 | private Documento documento; 8 | private String nombre; 9 | private String apellido; 10 | private String email; 11 | private String password; 12 | private String tel; 13 | private boolean habilitado; 14 | private HashMap roles; 15 | 16 | public int getId() { 17 | return id; 18 | } 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | public Documento getDocumento() { 23 | return documento; 24 | } 25 | public void setDocumento(Documento documento) { 26 | this.documento = documento; 27 | } 28 | public String getNombre() { 29 | return nombre; 30 | } 31 | public void setNombre(String nombre) { 32 | this.nombre = nombre; 33 | } 34 | public String getApellido() { 35 | return apellido; 36 | } 37 | public void setApellido(String apellido) { 38 | this.apellido = apellido; 39 | } 40 | public String getEmail() { 41 | return email; 42 | } 43 | public void setEmail(String email) { 44 | this.email = email; 45 | } 46 | public String getPassword() { 47 | return password; 48 | } 49 | public void setPassword(String password) { 50 | this.password = password; 51 | } 52 | public String getTel() { 53 | return tel; 54 | } 55 | public void setTel(String tel) { 56 | this.tel = tel; 57 | } 58 | public boolean isHabilitado() { 59 | return habilitado; 60 | } 61 | public void setHabilitado(boolean habilitado) { 62 | this.habilitado = habilitado; 63 | } 64 | 65 | public Persona() { 66 | this.roles=new HashMap<>(); 67 | } 68 | 69 | public void addRol(Rol rolToBeAdded) { 70 | this.roles.put(rolToBeAdded.getId(), rolToBeAdded); 71 | } 72 | 73 | public void removeRol(Rol rolToBeRemoved) { 74 | this.roles.remove(rolToBeRemoved.getId()); 75 | } 76 | 77 | public boolean hasRol(Rol rolToCheck) { 78 | return this.roles.containsKey(rolToCheck.getId()); 79 | } 80 | 81 | @Override 82 | public String toString() { 83 | return "\nPersona [id=" + id + ", documento=" + documento + ", nombre=" + nombre + ", apellido=" + apellido 84 | + ", email=" + email + ", tel=" + tel + ", habilitado=" + habilitado + ", roles=" + roles + "]"; 85 | } 86 | 87 | 88 | 89 | } 90 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/entities/Rol.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Rol { 4 | private int id; 5 | private String descripcion; 6 | public int getId() { 7 | return id; 8 | } 9 | public void setId(int id) { 10 | this.id = id; 11 | } 12 | public String getDescripcion() { 13 | return descripcion; 14 | } 15 | public void setDescripcion(String descripcion) { 16 | this.descripcion = descripcion; 17 | } 18 | @Override 19 | public String toString() { 20 | return "Rol [id=" + id + ", descripcion=" + descripcion + "]"; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/logic/Login.java: -------------------------------------------------------------------------------- 1 | package logic; 2 | 3 | import java.util.LinkedList; 4 | 5 | import data.*; 6 | import entities.*; 7 | 8 | public class Login { 9 | private DataPersona dp; 10 | 11 | public Login() { 12 | dp=new DataPersona(); 13 | } 14 | 15 | public Persona validate(Persona p) { 16 | /* para hacer más seguro el manejo de passwords este sería un lugar 17 | * adecuado para generar un hash de la password utilizando un cifrado 18 | * asimétrico como sha256 y utilizar el hash en lugar de la password en plano 19 | */ 20 | return dp.getByUser(p); 21 | } 22 | 23 | public LinkedList getAll(){ 24 | return dp.getAll(); 25 | } 26 | 27 | public Persona getByDocumento(Persona per) { 28 | return dp.getByDocumento(per); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/steps.md: -------------------------------------------------------------------------------- 1 | # JDBC - Pasos para setear y configurar jdbc 2 | 3 | ## Pasos para preparar la base de datos 4 | * Descargar e instalar mysql o uno de sus forks (mysql 8 o 5.7, mariadb 10.3, percona server 8 o 5.7) 5 | * Crear la base de datos java con usando el código del archivo db/dbJava.sql del proyecto. 6 | * Crear el usuario java para conectarse usando el código del archivo db/userJava.sql del proyecto. 7 | 8 | ### En casos de falla 9 | En caso que fallara la creación de la db o el usuario puede eliminarlps con el siguiente código y volver a intentarlo. 10 | 11 | ```sql 12 | DROP DATABASE IF EXISTS `java`; 13 | DROP USER IF EXISTS java@'%'; 14 | ``` 15 | 16 | ## Pasos para setear el conector 17 | 1. Descargar Connector/J platform independent y extraer el contenido. 18 | 2. Crear el directorio lib dentro del proyecto al mismo nivel de src, eligiendo la opción source folder. Atención no usar folder, usar source folder. 19 | 3. Copiar mysql-connector-java-8.0.20.jar dentro de lib/ 20 | 4. Botón derecho sobre el mysql-connector-java-8.0.20.jar hacer click en Build Path -> Add to build path 21 | 5. Si usa git, agregar el .jar del conector como excepción al .gitignore, (adaptarlo al directorio) por ejemplo en este proyecto 22 | ``` 23 | # Whitelist connector/j # 24 | !/ejemplos/*/lib/*.jar 25 | ``` 26 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/ui/Menu.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | 4 | import java.util.Scanner; 5 | 6 | import entities.*; 7 | import logic.Login; 8 | 9 | public class Menu { 10 | Scanner s=null; 11 | Login ctrlLogin = new Login(); 12 | 13 | public void start() { 14 | s = new Scanner(System.in); 15 | Persona p=login(); 16 | System.out.println("Bienvenido "+p.getNombre()+" "+p.getApellido()); 17 | System.out.println(); 18 | 19 | String command; 20 | do { 21 | command=getCommand(); 22 | executeCommand(command); 23 | System.out.println(); 24 | 25 | }while(!command.equalsIgnoreCase("exit")); 26 | 27 | s.close(); 28 | } 29 | 30 | private void executeCommand(String command) { 31 | switch (command) { 32 | case "list": 33 | System.out.println(ctrlLogin.getAll()); 34 | break; 35 | case "find": 36 | System.out.println(find()); 37 | break; 38 | case "seach": 39 | 40 | break; 41 | case "new": 42 | 43 | break; 44 | case "edit": 45 | 46 | break; 47 | case "delete": 48 | 49 | break; 50 | default: 51 | break; 52 | } 53 | } 54 | 55 | private String getCommand() { 56 | System.out.println("Ingrese el comando según la opción que desee realizar"); 57 | System.out.println("list\t\tlistar todos"); 58 | System.out.println("find\t\tbuscar por tipo y nro de documento"); //solo debe devolver 1 59 | System.out.println("search\t\tlistar por apellido"); //puede devolver varios 60 | System.out.println("new\t\tcrea una nueva persona y asigna un rol existente"); 61 | System.out.println("edit\t\tbusca por tipo y nro de documento y actualiza todos los datos"); 62 | System.out.println("delete\t\tborra por tipo y nro de documento"); 63 | System.out.println(); 64 | System.out.print("comando: "); 65 | return s.nextLine(); 66 | } 67 | 68 | public Persona login() { 69 | Persona p=new Persona(); 70 | 71 | System.out.print("Email: "); 72 | p.setEmail(s.nextLine()); 73 | 74 | System.out.print("password: "); 75 | p.setPassword(s.nextLine()); 76 | 77 | p=ctrlLogin.validate(p); 78 | 79 | return p; 80 | 81 | } 82 | 83 | private Persona find() { 84 | System.out.println(); 85 | Persona p=new Persona(); 86 | Documento d=new Documento(); 87 | p.setDocumento(d); 88 | System.out.print("Tipo doc: "); 89 | d.setTipo(s.nextLine()); 90 | 91 | System.out.print("Nro doc: "); 92 | d.setNro(s.nextLine()); 93 | 94 | return ctrlLogin.getByDocumento(p); 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /ejemplos/Ej5AccesoADatos/src/ui/Principal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Principal { 6 | 7 | public static void main(String[] args) { 8 | Menu m=new Menu(); 9 | m.start(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ej6WebIntro 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.wst.common.project.facet.core.builder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.validation.validationbuilder 20 | 21 | 22 | 23 | 24 | 25 | org.eclipse.jem.workbench.JavaEMFNature 26 | org.eclipse.wst.common.modulecore.ModuleCoreNature 27 | org.eclipse.wst.common.project.facet.core.nature 28 | org.eclipse.jdt.core.javanature 29 | org.eclipse.wst.jsdt.core.jsNature 30 | 31 | 32 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/WebContent/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/WebContent/WEB-INF/UserManagement.jsp: -------------------------------------------------------------------------------- 1 | <%@page import="java.util.LinkedList"%> 2 | <%@page import="entities.Persona"%> 3 | <%@ page language="java" contentType="text/html; charset=UTF-8" 4 | pageEncoding="UTF-8"%> 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | Java Web Intro 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | <% 25 | Persona p = (Persona)session.getAttribute("usuario"); 26 | LinkedList lp = (LinkedList)request.getAttribute("listaPersonas"); 27 | %> 28 | 29 | 30 | 31 |
32 |
33 |

Personas

34 |
35 |
36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | <% for (Persona per : lp) { %> 51 | 52 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 65 | 66 | <% } %> 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/WebContent/WEB-INF/lib/mysql-connector-java-8.0.20.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ej6WebIntro/WebContent/WEB-INF/lib/mysql-connector-java-8.0.20.jar -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/WebContent/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Java Web Intro 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |

Please sign in

23 | 24 | 25 | 26 | 27 | 28 |

© 2017-2018

29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/WebContent/style/signin.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | height: 100%; 4 | } 5 | 6 | body { 7 | display: -ms-flexbox; 8 | display: flex; 9 | -ms-flex-align: center; 10 | align-items: center; 11 | padding-top: 40px; 12 | padding-bottom: 40px; 13 | background-color: #f5f5f5; 14 | } 15 | 16 | .form-signin { 17 | width: 100%; 18 | max-width: 330px; 19 | padding: 15px; 20 | margin: auto; 21 | } 22 | .form-signin .checkbox { 23 | font-weight: 400; 24 | } 25 | .form-signin .form-control { 26 | position: relative; 27 | box-sizing: border-box; 28 | height: auto; 29 | padding: 10px; 30 | font-size: 16px; 31 | } 32 | .form-signin .form-control:focus { 33 | z-index: 2; 34 | } 35 | .form-signin input[type="email"] { 36 | margin-bottom: -1px; 37 | border-bottom-right-radius: 0; 38 | border-bottom-left-radius: 0; 39 | } 40 | .form-signin input[type="password"] { 41 | margin-bottom: 10px; 42 | border-top-left-radius: 0; 43 | border-top-right-radius: 0; 44 | } 45 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/db/dbJava.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.15 Distrib 10.0.38-MariaDB, for debian-linux-gnu (x86_64) 2 | -- 3 | -- Host: localhost Database: java 4 | -- ------------------------------------------------------ 5 | -- Server version 10.0.38-MariaDB-0ubuntu0.16.04.1 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8mb4 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Current Database: `java` 20 | -- 21 | 22 | CREATE DATABASE /*!32312 IF NOT EXISTS*/ `java` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; 23 | 24 | USE `java`; 25 | 26 | -- 27 | -- Table structure for table `persona` 28 | -- 29 | 30 | DROP TABLE IF EXISTS `persona`; 31 | /*!40101 SET @saved_cs_client = @@character_set_client */; 32 | /*!40101 SET character_set_client = utf8 */; 33 | CREATE TABLE `persona` ( 34 | `id` int(11) NOT NULL AUTO_INCREMENT, 35 | `tipo_doc` varchar(10) NOT NULL, 36 | `nro_doc` varchar(45) NOT NULL, 37 | `nombre` varchar(255) NOT NULL, 38 | `apellido` varchar(255) NOT NULL, 39 | `email` varchar(255) DEFAULT NULL, 40 | `tel` varchar(255) DEFAULT NULL, 41 | `habilitado` tinyint(1) NOT NULL, 42 | `password` varchar(255) NOT NULL, 43 | PRIMARY KEY (`id`) 44 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4; 45 | /*!40101 SET character_set_client = @saved_cs_client */; 46 | 47 | -- 48 | -- Dumping data for table `persona` 49 | -- 50 | 51 | LOCK TABLES `persona` WRITE; 52 | /*!40000 ALTER TABLE `persona` DISABLE KEYS */; 53 | INSERT INTO `persona` VALUES (1,'dni','10101010','Juan','Perez','jp@gmail.com','4101010',1,'jperez'),(2,'dni','12121212','John','Doe','contacto@jd','4121212',0,'jdoe'),(3,'dni','13131313','Nadie','Sabe','ns@ns.com','4131313',1,'nsabe'),(4,'cuit','14141414141','Identidad','Desconocida','unknown@gmail.com','4141414',0,'idesconocida'),(5,'cuit','15151515151','Alguien','Más','am@gmail.com','4151515',1,'amas'),(6,'dni','16161616','Otra','Persona','op@gmail.com','4161616',0,'opersona'); 54 | /*!40000 ALTER TABLE `persona` ENABLE KEYS */; 55 | UNLOCK TABLES; 56 | 57 | -- 58 | -- Table structure for table `rol` 59 | -- 60 | 61 | DROP TABLE IF EXISTS `rol`; 62 | /*!40101 SET @saved_cs_client = @@character_set_client */; 63 | /*!40101 SET character_set_client = utf8 */; 64 | CREATE TABLE `rol` ( 65 | `id` int(11) NOT NULL AUTO_INCREMENT, 66 | `descripcion` varchar(255) NOT NULL, 67 | PRIMARY KEY (`id`) 68 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4; 69 | /*!40101 SET character_set_client = @saved_cs_client */; 70 | 71 | -- 72 | -- Dumping data for table `rol` 73 | -- 74 | 75 | LOCK TABLES `rol` WRITE; 76 | /*!40000 ALTER TABLE `rol` DISABLE KEYS */; 77 | INSERT INTO `rol` VALUES (1,'admin'),(2,'user'); 78 | /*!40000 ALTER TABLE `rol` ENABLE KEYS */; 79 | UNLOCK TABLES; 80 | 81 | -- 82 | -- Table structure for table `rol_persona` 83 | -- 84 | 85 | DROP TABLE IF EXISTS `rol_persona`; 86 | /*!40101 SET @saved_cs_client = @@character_set_client */; 87 | /*!40101 SET character_set_client = utf8 */; 88 | CREATE TABLE `rol_persona` ( 89 | `id_persona` int(11) NOT NULL, 90 | `id_rol` int(11) NOT NULL, 91 | PRIMARY KEY (`id_persona`,`id_rol`), 92 | KEY `rol_persona_rol_fk` (`id_rol`), 93 | CONSTRAINT `rol_persona_persona_fk` FOREIGN KEY (`id_persona`) REFERENCES `persona` (`id`), 94 | CONSTRAINT `rol_persona_rol_fk` FOREIGN KEY (`id_rol`) REFERENCES `rol` (`id`) 95 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 96 | /*!40101 SET character_set_client = @saved_cs_client */; 97 | 98 | -- 99 | -- Dumping data for table `rol_persona` 100 | -- 101 | 102 | LOCK TABLES `rol_persona` WRITE; 103 | /*!40000 ALTER TABLE `rol_persona` DISABLE KEYS */; 104 | INSERT INTO `rol_persona` VALUES (1,1),(2,2),(3,1),(3,2),(4,2),(5,2),(6,2); 105 | /*!40000 ALTER TABLE `rol_persona` ENABLE KEYS */; 106 | UNLOCK TABLES; 107 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 108 | 109 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 110 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 111 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 112 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 113 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 114 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 115 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 116 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/db/userJava.sql: -------------------------------------------------------------------------------- 1 | -- 2 | -- User java 3 | -- 4 | 5 | create user 'java'@'localhost' identified by 'himitsu'; 6 | GRANT SELECT, INSERT, UPDATE, DELETE ON `java`.* TO 'java'@'localhost'; 7 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/data/DataPersona.java: -------------------------------------------------------------------------------- 1 | package data; 2 | //orig 3 | import entities.*; 4 | 5 | import java.sql.*; 6 | import java.util.LinkedList; 7 | 8 | public class DataPersona { 9 | 10 | public LinkedList getAll(){ 11 | DataRol dr=new DataRol(); 12 | Statement stmt=null; 13 | ResultSet rs=null; 14 | LinkedList pers= new LinkedList<>(); 15 | 16 | try { 17 | stmt= DbConnector.getInstancia().getConn().createStatement(); 18 | rs= stmt.executeQuery("select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona"); 19 | //intencionalmente no se recupera la password 20 | if(rs!=null) { 21 | while(rs.next()) { 22 | Persona p=new Persona(); 23 | p.setDocumento(new Documento()); 24 | p.setId(rs.getInt("id")); 25 | p.setNombre(rs.getString("nombre")); 26 | p.setApellido(rs.getString("apellido")); 27 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 28 | p.getDocumento().setNro(rs.getString("nro_doc")); 29 | p.setEmail(rs.getString("email")); 30 | p.setTel(rs.getString("tel")); 31 | 32 | p.setHabilitado(rs.getBoolean("habilitado")); 33 | 34 | dr.setRoles(p); 35 | 36 | pers.add(p); 37 | } 38 | } 39 | 40 | } catch (SQLException e) { 41 | e.printStackTrace(); 42 | 43 | } finally { 44 | try { 45 | if(rs!=null) {rs.close();} 46 | if(stmt!=null) {stmt.close();} 47 | DbConnector.getInstancia().releaseConn(); 48 | } catch (SQLException e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | 53 | 54 | return pers; 55 | } 56 | 57 | public Persona getByUser(Persona per) { 58 | DataRol dr=new DataRol(); 59 | Persona p=null; 60 | PreparedStatement stmt=null; 61 | ResultSet rs=null; 62 | try { 63 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 64 | "select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona where email=? and password=?" 65 | ); 66 | stmt.setString(1, per.getEmail()); 67 | stmt.setString(2, per.getPassword()); 68 | rs=stmt.executeQuery(); 69 | if(rs!=null && rs.next()) { 70 | p=new Persona(); 71 | p.setDocumento(new Documento()); 72 | p.setId(rs.getInt("id")); 73 | p.setNombre(rs.getString("nombre")); 74 | p.setApellido(rs.getString("apellido")); 75 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 76 | p.getDocumento().setNro(rs.getString("nro_doc")); 77 | p.setEmail(rs.getString("email")); 78 | p.setTel(rs.getString("tel")); 79 | p.setHabilitado(rs.getBoolean("habilitado")); 80 | // 81 | dr.setRoles(p); 82 | } 83 | } catch (SQLException e) { 84 | e.printStackTrace(); 85 | }finally { 86 | try { 87 | if(rs!=null) {rs.close();} 88 | if(stmt!=null) {stmt.close();} 89 | DbConnector.getInstancia().releaseConn(); 90 | } catch (SQLException e) { 91 | e.printStackTrace(); 92 | } 93 | } 94 | 95 | return p; 96 | } 97 | 98 | public Persona getByDocumento(Persona per) { 99 | DataRol dr=new DataRol(); 100 | Persona p=null; 101 | PreparedStatement stmt=null; 102 | ResultSet rs=null; 103 | try { 104 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 105 | "select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona where tipo_doc=? and nro_doc=?" 106 | ); 107 | stmt.setString(1, per.getDocumento().getTipo()); 108 | stmt.setString(2, per.getDocumento().getNro()); 109 | rs=stmt.executeQuery(); 110 | if(rs!=null && rs.next()) { 111 | p=new Persona(); 112 | p.setDocumento(new Documento()); 113 | p.setId(rs.getInt("id")); 114 | p.setNombre(rs.getString("nombre")); 115 | p.setApellido(rs.getString("apellido")); 116 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 117 | p.getDocumento().setNro(rs.getString("nro_doc")); 118 | p.setEmail(rs.getString("email")); 119 | p.setTel(rs.getString("tel")); 120 | p.setHabilitado(rs.getBoolean("habilitado")); 121 | // 122 | dr.setRoles(p); 123 | } 124 | } catch (SQLException e) { 125 | e.printStackTrace(); 126 | }finally { 127 | try { 128 | if(rs!=null) {rs.close();} 129 | if(stmt!=null) {stmt.close();} 130 | DbConnector.getInstancia().releaseConn(); 131 | } catch (SQLException e) { 132 | e.printStackTrace(); 133 | } 134 | } 135 | 136 | return p; 137 | } 138 | 139 | public void add(Persona p) { 140 | PreparedStatement stmt= null; 141 | ResultSet keyResultSet=null; 142 | try { 143 | stmt=DbConnector.getInstancia().getConn(). 144 | prepareStatement( 145 | "insert into persona(nombre, apellido, tipo_doc, nro_doc, email, password, tel, habilitado) values(?,?,?,?,?,?,?,?)", 146 | PreparedStatement.RETURN_GENERATED_KEYS 147 | ); 148 | stmt.setString(1, p.getNombre()); 149 | stmt.setString(2, p.getApellido()); 150 | stmt.setString(3, p.getDocumento().getTipo()); 151 | stmt.setString(4, p.getDocumento().getNro()); 152 | stmt.setString(5, p.getEmail()); 153 | stmt.setString(5, p.getPassword()); 154 | stmt.setString(6, p.getTel()); 155 | stmt.setBoolean(7, p.isHabilitado()); 156 | stmt.executeUpdate(); 157 | 158 | keyResultSet=stmt.getGeneratedKeys(); 159 | if(keyResultSet!=null && keyResultSet.next()){ 160 | p.setId(keyResultSet.getInt(1)); 161 | } 162 | 163 | DataRol dr = new DataRol(); 164 | dr.setRolesDePersona(p); 165 | 166 | 167 | } catch (SQLException e) { 168 | e.printStackTrace(); 169 | } finally { 170 | try { 171 | if(keyResultSet!=null)keyResultSet.close(); 172 | if(stmt!=null)stmt.close(); 173 | DbConnector.getInstancia().releaseConn(); 174 | } catch (SQLException e) { 175 | e.printStackTrace(); 176 | } 177 | } 178 | } 179 | 180 | 181 | } 182 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/data/DataRol.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.ResultSet; 5 | import java.sql.SQLException; 6 | import java.sql.Statement; 7 | import java.util.LinkedList; 8 | import entities.*; 9 | 10 | public class DataRol { 11 | 12 | public LinkedList getAll(){ 13 | Statement stmt=null; 14 | ResultSet rs=null; 15 | LinkedList roles= new LinkedList<>(); 16 | 17 | try { 18 | stmt= DbConnector.getInstancia().getConn().createStatement(); 19 | rs= stmt.executeQuery("select * from rol"); 20 | if(rs!=null) { 21 | while(rs.next()) { 22 | Rol r=new Rol(); 23 | r.setId(rs.getInt("id")); 24 | r.setDescripcion(rs.getString("descripcion")); 25 | roles.add(r); 26 | } 27 | } 28 | 29 | } catch (SQLException e) { 30 | e.printStackTrace(); 31 | 32 | } finally { 33 | try { 34 | if(rs!=null) {rs.close();} 35 | if(stmt!=null) {stmt.close();} 36 | DbConnector.getInstancia().releaseConn(); 37 | } catch (SQLException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | 42 | 43 | return roles; 44 | } 45 | 46 | public Rol getById(Rol rolToSearch) { 47 | Rol r=null; 48 | PreparedStatement stmt=null; 49 | ResultSet rs=null; 50 | try { 51 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 52 | "select * from rol where id=?" 53 | ); 54 | stmt.setInt(1, rolToSearch.getId()); 55 | rs=stmt.executeQuery(); 56 | if(rs!=null && rs.next()) { 57 | r=new Rol(); 58 | r.setId(rs.getInt("id")); 59 | r.setDescripcion(rs.getString("descripcion")); 60 | } 61 | } catch (SQLException e) { 62 | e.printStackTrace(); 63 | }finally { 64 | try { 65 | if(rs!=null) {rs.close();} 66 | if(stmt!=null) {stmt.close();} 67 | DbConnector.getInstancia().releaseConn(); 68 | } catch (SQLException e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | 73 | return r; 74 | } 75 | 76 | public Rol getByDesc(Rol rolToSearch) { 77 | Rol r=null; 78 | PreparedStatement stmt=null; 79 | ResultSet rs=null; 80 | try { 81 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 82 | "select * from rol where descripcion=?" 83 | ); 84 | stmt.setString(1, rolToSearch.getDescripcion()); 85 | rs=stmt.executeQuery(); 86 | if(rs!=null && rs.next()) { 87 | r=new Rol(); 88 | r.setId(rs.getInt("id")); 89 | r.setDescripcion(rs.getString("descripcion")); 90 | } 91 | } catch (SQLException e) { 92 | e.printStackTrace(); 93 | }finally { 94 | try { 95 | if(rs!=null) {rs.close();} 96 | if(stmt!=null) {stmt.close();} 97 | DbConnector.getInstancia().releaseConn(); 98 | } catch (SQLException e) { 99 | e.printStackTrace(); 100 | } 101 | } 102 | 103 | return r; 104 | } 105 | 106 | public void setRoles(Persona per) { 107 | PreparedStatement stmt=null; 108 | ResultSet rs=null; 109 | try { 110 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 111 | "select rol.* " 112 | + "from rol " 113 | + "inner join rol_persona " 114 | + "on rol.id=rol_persona.id_rol " 115 | + "where id_persona=?" 116 | ); 117 | stmt.setInt(1, per.getId()); 118 | rs= stmt.executeQuery(); 119 | if(rs!=null) { 120 | while(rs.next()) { 121 | Rol r=new Rol(); 122 | r.setId(rs.getInt("id")); 123 | r.setDescripcion(rs.getString("descripcion")); 124 | per.addRol(r); 125 | } 126 | } 127 | 128 | } catch (SQLException e) { 129 | e.printStackTrace(); 130 | }finally { 131 | try { 132 | if(rs!=null) {rs.close();} 133 | if(stmt!=null) {stmt.close();} 134 | DbConnector.getInstancia().releaseConn(); 135 | } catch (SQLException e) { 136 | e.printStackTrace(); 137 | } 138 | } 139 | } 140 | 141 | public void add(Rol rol) { 142 | PreparedStatement stmt= null; 143 | ResultSet keyResultSet=null; 144 | try { 145 | stmt=DbConnector.getInstancia().getConn(). 146 | prepareStatement( 147 | "insert into rol(descripcion) values(?)", 148 | PreparedStatement.RETURN_GENERATED_KEYS 149 | ); 150 | stmt.setString(1, rol.getDescripcion()); 151 | stmt.executeUpdate(); 152 | 153 | keyResultSet=stmt.getGeneratedKeys(); 154 | if(keyResultSet!=null && keyResultSet.next()){ 155 | rol.setId(keyResultSet.getInt(1)); 156 | } 157 | 158 | 159 | } catch (SQLException e) { 160 | e.printStackTrace(); 161 | } finally { 162 | try { 163 | if(keyResultSet!=null)keyResultSet.close(); 164 | if(stmt!=null)stmt.close(); 165 | DbConnector.getInstancia().releaseConn(); 166 | } catch (SQLException e) { 167 | e.printStackTrace(); 168 | } 169 | } 170 | 171 | } 172 | 173 | public void update(Rol rol) { 174 | PreparedStatement stmt= null; 175 | try { 176 | stmt=DbConnector.getInstancia().getConn(). 177 | prepareStatement( 178 | "update rol set descripcion=? where id=?"); 179 | stmt.setString(1, rol.getDescripcion()); 180 | stmt.setInt(2, rol.getId()); 181 | stmt.executeUpdate(); 182 | } catch (SQLException e) { 183 | e.printStackTrace(); 184 | } finally { 185 | try { 186 | if(stmt!=null)stmt.close(); 187 | DbConnector.getInstancia().releaseConn(); 188 | } catch (SQLException e) { 189 | e.printStackTrace(); 190 | } 191 | } 192 | } 193 | 194 | public void remove(Rol rol) { 195 | PreparedStatement stmt= null; 196 | try { 197 | stmt=DbConnector.getInstancia().getConn(). 198 | prepareStatement( 199 | "delete from rol where id=?"); 200 | stmt.setInt(1, rol.getId()); 201 | stmt.executeUpdate(); 202 | } catch (SQLException e) { 203 | e.printStackTrace(); 204 | } finally { 205 | try { 206 | if(stmt!=null)stmt.close(); 207 | DbConnector.getInstancia().releaseConn(); 208 | } catch (SQLException e) { 209 | e.printStackTrace(); 210 | } 211 | } 212 | } 213 | 214 | public void setRolesDePersona(Persona p) { 215 | 216 | PreparedStatement stmt= null; 217 | try { 218 | stmt=DbConnector.getInstancia().getConn(). 219 | prepareStatement( 220 | "insert into rol_persona values(?,?);"); 221 | stmt.setInt(1,p.getId()); 222 | for(Rol r:p.getAllRoles().values()) { 223 | stmt.setInt(2, r.getId()); 224 | stmt.executeUpdate(); 225 | } 226 | 227 | } catch (SQLException e) { 228 | e.printStackTrace(); 229 | } finally { 230 | try { 231 | if(stmt!=null)stmt.close(); 232 | DbConnector.getInstancia().releaseConn(); 233 | } catch (SQLException e) { 234 | e.printStackTrace(); 235 | } 236 | } 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/data/DbConnector.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.*; 4 | 5 | public class DbConnector { 6 | 7 | private static DbConnector instancia; 8 | 9 | private String driver="com.mysql.cj.jdbc.Driver"; 10 | private String host="localhost"; 11 | private String port="3306"; 12 | private String user="java"; 13 | private String password="himitsu"; 14 | private String db="java"; 15 | private int conectados=0; 16 | private Connection conn=null; 17 | 18 | private DbConnector() { 19 | try { 20 | Class.forName(driver); 21 | } catch (ClassNotFoundException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | 26 | public static DbConnector getInstancia() { 27 | if (instancia == null) { 28 | instancia = new DbConnector(); 29 | } 30 | return instancia; 31 | } 32 | 33 | public Connection getConn() { 34 | try { 35 | if(conn==null || conn.isClosed()) { 36 | conn=DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+db, user, password); 37 | conectados=0; 38 | } 39 | } catch (SQLException e) { 40 | e.printStackTrace(); 41 | } 42 | conectados++; 43 | return conn; 44 | } 45 | 46 | public void releaseConn() { 47 | conectados--; 48 | try { 49 | if (conectados<=0) { 50 | conn.close(); 51 | } 52 | } catch (SQLException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/entities/Documento.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Documento { 4 | private String tipo; 5 | private String nro; 6 | public String getTipo() { 7 | return tipo; 8 | } 9 | public void setTipo(String tipo) { 10 | this.tipo = tipo; 11 | } 12 | public String getNro() { 13 | return nro; 14 | } 15 | public void setNro(String nro) { 16 | this.nro = nro; 17 | } 18 | @Override 19 | public String toString() { 20 | return "Documento [tipo=" + tipo + ", nro=" + nro + "]"; 21 | } 22 | 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/entities/Persona.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Persona { 6 | private int id; 7 | private Documento documento; 8 | private String nombre; 9 | private String apellido; 10 | private String email; 11 | private String password; 12 | private String tel; 13 | private boolean habilitado; 14 | private HashMap roles; 15 | 16 | public int getId() { 17 | return id; 18 | } 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | public Documento getDocumento() { 23 | return documento; 24 | } 25 | public void setDocumento(Documento documento) { 26 | this.documento = documento; 27 | } 28 | public String getNombre() { 29 | return nombre; 30 | } 31 | public void setNombre(String nombre) { 32 | this.nombre = nombre; 33 | } 34 | public String getApellido() { 35 | return apellido; 36 | } 37 | public void setApellido(String apellido) { 38 | this.apellido = apellido; 39 | } 40 | public String getEmail() { 41 | return email; 42 | } 43 | public void setEmail(String email) { 44 | this.email = email; 45 | } 46 | public String getPassword() { 47 | return password; 48 | } 49 | public void setPassword(String password) { 50 | this.password = password; 51 | } 52 | public String getTel() { 53 | return tel; 54 | } 55 | public void setTel(String tel) { 56 | this.tel = tel; 57 | } 58 | public boolean isHabilitado() { 59 | return habilitado; 60 | } 61 | public void setHabilitado(boolean habilitado) { 62 | this.habilitado = habilitado; 63 | } 64 | 65 | public Persona() { 66 | this.roles=new HashMap<>(); 67 | } 68 | 69 | public void addRol(Rol rolToBeAdded) { 70 | this.roles.put(rolToBeAdded.getId(), rolToBeAdded); 71 | } 72 | 73 | public void removeRol(Rol rolToBeRemoved) { 74 | this.roles.remove(rolToBeRemoved.getId()); 75 | } 76 | 77 | public boolean hasRol(Rol rolToCheck) { 78 | return this.roles.containsKey(rolToCheck.getId()); 79 | } 80 | 81 | public HashMap getAllRoles(){ 82 | return this.roles; 83 | } 84 | 85 | @Override 86 | public String toString() { 87 | return "\nPersona [id=" + id + ", documento=" + documento + ", nombre=" + nombre + ", apellido=" + apellido 88 | + ", email=" + email + ", tel=" + tel + ", habilitado=" + habilitado + ", roles=" + roles + "]"; 89 | } 90 | 91 | 92 | 93 | } 94 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/entities/Rol.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Rol { 4 | private int id; 5 | private String descripcion; 6 | public int getId() { 7 | return id; 8 | } 9 | public void setId(int id) { 10 | this.id = id; 11 | } 12 | public String getDescripcion() { 13 | return descripcion; 14 | } 15 | public void setDescripcion(String descripcion) { 16 | this.descripcion = descripcion; 17 | } 18 | @Override 19 | public String toString() { 20 | return "Rol [id=" + id + ", descripcion=" + descripcion + "]"; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/logic/Login.java: -------------------------------------------------------------------------------- 1 | package logic; 2 | 3 | import java.util.LinkedList; 4 | 5 | import data.*; 6 | import entities.*; 7 | 8 | public class Login { 9 | private DataPersona dp; 10 | 11 | public Login() { 12 | dp=new DataPersona(); 13 | } 14 | 15 | public Persona validate(Persona p) { 16 | /* para hacer más seguro el manejo de passwords este sería un lugar 17 | * adecuado para generar un hash de la password utilizando un cifrado 18 | * asimétrico como sha256 y utilizar el hash en lugar de la password en plano 19 | */ 20 | return dp.getByUser(p); 21 | } 22 | 23 | public LinkedList getAll(){ 24 | return dp.getAll(); 25 | } 26 | 27 | public Persona getByDocumento(Persona per) { 28 | return dp.getByDocumento(per); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/servlet/Signin.java: -------------------------------------------------------------------------------- 1 | package servlet; 2 | 3 | import java.io.IOException; 4 | import java.util.LinkedList; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.annotation.WebServlet; 8 | import javax.servlet.http.HttpServlet; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | import entities.Persona; 13 | import logic.Login; 14 | 15 | /** 16 | * Servlet implementation class Signin 17 | */ 18 | @WebServlet({ "/signin", "/SIGNIN", "/Signin", "/SignIn", "/signIn" }) 19 | public class Signin extends HttpServlet { 20 | private static final long serialVersionUID = 1L; 21 | 22 | /** 23 | * @see HttpServlet#HttpServlet() 24 | */ 25 | public Signin() { 26 | super(); 27 | // TODO Auto-generated constructor stub 28 | } 29 | 30 | /** 31 | * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 32 | */ 33 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 34 | // TODO Auto-generated method stub 35 | response.getWriter().append("get at: ").append(request.getContextPath()); 36 | } 37 | 38 | /** 39 | * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 40 | */ 41 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 42 | Persona per = new Persona(); 43 | Login ctrl = new Login(); 44 | 45 | String email = request.getParameter("email"); 46 | String password = request.getParameter("password"); 47 | 48 | //validar email y password 49 | 50 | per.setEmail(email); 51 | per.setPassword(password); 52 | 53 | per=ctrl.validate(per); 54 | LinkedList personas = ctrl.getAll(); 55 | 56 | 57 | request.getSession().setAttribute("usuario", per); 58 | request.setAttribute("listaPersonas", personas); 59 | 60 | request.getRequestDispatcher("WEB-INF/UserManagement.jsp").forward(request, response); 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro/src/steps.md: -------------------------------------------------------------------------------- 1 | # JDBC - Pasos para setear y configurar jdbc 2 | 3 | ## Pasos para preparar la base de datos 4 | * Descargar e instalar mysql o uno de sus forks (mysql 8 o 5.7, mariadb 10.3, percona server 8 o 5.7) 5 | * Crear la base de datos java con usando el código del archivo db/dbJava.sql del proyecto. 6 | * Crear el usuario java para conectarse usando el código del archivo db/userJava.sql del proyecto. 7 | 8 | ### En casos de falla 9 | En caso que fallara la creación de la db o el usuario puede eliminarlps con el siguiente código y volver a intentarlo. 10 | 11 | ```sql 12 | DROP DATABASE `java`; 13 | DROP USEr java@localhost; 14 | ``` 15 | 16 | ## Pasos para setear el conector 17 | 1. Descargar Connector/J platform independent y extraer el contenido. 18 | 2. Crear el directorio lib dentro del proyecto al mismo nivel de src, eligiendo la opción source folder. Atención no usar folder, usar source folder. 19 | 3. Copiar mysql-connector-java-8.0.20.jar dentro de lib/ 20 | 4. Botón derecho sobre el mysql-connector-java-8.0.20.jar hacer click en Build Path -> Add to build path 21 | 5. Si usa git, agregar el .jar del conector como excepción al .gitignore, (adaptarlo al directorio) por ejemplo en este proyecto 22 | ``` 23 | # Whitelist connector/j # 24 | !/ejemplos/*/lib/*.jar 25 | ``` 26 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ej6WebIntro2022 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.wst.common.project.facet.core.builder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.validation.validationbuilder 20 | 21 | 22 | 23 | 24 | 25 | org.eclipse.jem.workbench.JavaEMFNature 26 | org.eclipse.wst.common.modulecore.ModuleCoreNature 27 | org.eclipse.wst.common.project.facet.core.nature 28 | org.eclipse.jdt.core.javanature 29 | org.eclipse.wst.jsdt.core.jsNature 30 | 31 | 32 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/db/dbJava.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.15 Distrib 10.0.38-MariaDB, for debian-linux-gnu (x86_64) 2 | -- 3 | -- Host: localhost Database: java 4 | -- ------------------------------------------------------ 5 | -- Server version 10.0.38-MariaDB-0ubuntu0.16.04.1 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8mb4 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Current Database: `java` 20 | -- 21 | 22 | CREATE DATABASE /*!32312 IF NOT EXISTS*/ `java` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; 23 | 24 | USE `java`; 25 | 26 | -- 27 | -- Table structure for table `persona` 28 | -- 29 | 30 | DROP TABLE IF EXISTS `persona`; 31 | /*!40101 SET @saved_cs_client = @@character_set_client */; 32 | /*!40101 SET character_set_client = utf8 */; 33 | CREATE TABLE `persona` ( 34 | `id` int(11) NOT NULL AUTO_INCREMENT, 35 | `tipo_doc` varchar(10) NOT NULL, 36 | `nro_doc` varchar(45) NOT NULL, 37 | `nombre` varchar(255) NOT NULL, 38 | `apellido` varchar(255) NOT NULL, 39 | `email` varchar(255) DEFAULT NULL, 40 | `tel` varchar(255) DEFAULT NULL, 41 | `habilitado` tinyint(1) NOT NULL, 42 | `password` varchar(255) NOT NULL, 43 | PRIMARY KEY (`id`) 44 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4; 45 | /*!40101 SET character_set_client = @saved_cs_client */; 46 | 47 | -- 48 | -- Dumping data for table `persona` 49 | -- 50 | 51 | LOCK TABLES `persona` WRITE; 52 | /*!40000 ALTER TABLE `persona` DISABLE KEYS */; 53 | INSERT INTO `persona` VALUES (1,'dni','10101010','Juan','Perez','jp@gmail.com','4101010',1,'jperez'),(2,'dni','12121212','John','Doe','contacto@jd','4121212',0,'jdoe'),(3,'dni','13131313','Nadie','Sabe','ns@ns.com','4131313',1,'nsabe'),(4,'cuit','14141414141','Identidad','Desconocida','unknown@gmail.com','4141414',0,'idesconocida'),(5,'cuit','15151515151','Alguien','Más','am@gmail.com','4151515',1,'amas'),(6,'dni','16161616','Otra','Persona','op@gmail.com','4161616',0,'opersona'); 54 | /*!40000 ALTER TABLE `persona` ENABLE KEYS */; 55 | UNLOCK TABLES; 56 | 57 | -- 58 | -- Table structure for table `rol` 59 | -- 60 | 61 | DROP TABLE IF EXISTS `rol`; 62 | /*!40101 SET @saved_cs_client = @@character_set_client */; 63 | /*!40101 SET character_set_client = utf8 */; 64 | CREATE TABLE `rol` ( 65 | `id` int(11) NOT NULL AUTO_INCREMENT, 66 | `descripcion` varchar(255) NOT NULL, 67 | PRIMARY KEY (`id`) 68 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4; 69 | /*!40101 SET character_set_client = @saved_cs_client */; 70 | 71 | -- 72 | -- Dumping data for table `rol` 73 | -- 74 | 75 | LOCK TABLES `rol` WRITE; 76 | /*!40000 ALTER TABLE `rol` DISABLE KEYS */; 77 | INSERT INTO `rol` VALUES (1,'admin'),(2,'user'); 78 | /*!40000 ALTER TABLE `rol` ENABLE KEYS */; 79 | UNLOCK TABLES; 80 | 81 | -- 82 | -- Table structure for table `rol_persona` 83 | -- 84 | 85 | DROP TABLE IF EXISTS `rol_persona`; 86 | /*!40101 SET @saved_cs_client = @@character_set_client */; 87 | /*!40101 SET character_set_client = utf8 */; 88 | CREATE TABLE `rol_persona` ( 89 | `id_persona` int(11) NOT NULL, 90 | `id_rol` int(11) NOT NULL, 91 | PRIMARY KEY (`id_persona`,`id_rol`), 92 | KEY `rol_persona_rol_fk` (`id_rol`), 93 | CONSTRAINT `rol_persona_persona_fk` FOREIGN KEY (`id_persona`) REFERENCES `persona` (`id`), 94 | CONSTRAINT `rol_persona_rol_fk` FOREIGN KEY (`id_rol`) REFERENCES `rol` (`id`) 95 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 96 | /*!40101 SET character_set_client = @saved_cs_client */; 97 | 98 | -- 99 | -- Dumping data for table `rol_persona` 100 | -- 101 | 102 | LOCK TABLES `rol_persona` WRITE; 103 | /*!40000 ALTER TABLE `rol_persona` DISABLE KEYS */; 104 | INSERT INTO `rol_persona` VALUES (1,1),(2,2),(3,1),(3,2),(4,2),(5,2),(6,2); 105 | /*!40000 ALTER TABLE `rol_persona` ENABLE KEYS */; 106 | UNLOCK TABLES; 107 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 108 | 109 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 110 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 111 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 112 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 113 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 114 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 115 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 116 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/db/steps.md: -------------------------------------------------------------------------------- 1 | # JDBC - Pasos para setear y configurar jdbc 2 | 3 | ## Pasos para preparar la base de datos 4 | * Descargar e instalar mysql o uno de sus forks (mysql 8, mariadb 10.5, percona server 8) 5 | * Crear la base de datos java con usando el código del archivo db/dbJava.sql del proyecto. 6 | * Crear el usuario java para conectarse usando el código del archivo db/userJava.sql del proyecto. 7 | 8 | ### En casos de falla 9 | En caso que fallara la creación de la db o el usuario puede eliminarlps con el siguiente código y volver a intentarlo. 10 | 11 | ```sql 12 | DROP DATABASE `java`; 13 | DROP USEr java@localhost; 14 | ``` 15 | 16 | ## Pasos para setear el conector 17 | 1. Descargar Connector/J platform independent y extraer el contenido. 18 | 2. Crear el directorio lib dentro del proyecto al mismo nivel de src, eligiendo la opción source folder. Atención no usar folder, usar source folder. 19 | 3. Copiar mysql-connector-java-8.0.20.jar dentro de lib/ 20 | 4. Botón derecho sobre el mysql-connector-java-8.0.20.jar hacer click en Build Path -> Add to build path 21 | 5. Si usa git, agregar el .jar del conector como excepción al .gitignore, (adaptarlo al directorio) por ejemplo en este proyecto 22 | ``` 23 | # Whitelist connector/j # 24 | !/ejemplos/*/lib/*.jar 25 | ``` 26 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/db/userJava.sql: -------------------------------------------------------------------------------- 1 | -- 2 | -- User java 3 | -- 4 | drop user if exists 'java'@'%'; 5 | create user 'java'@'%' identified by 'himitsu'; 6 | GRANT SELECT, INSERT, UPDATE, DELETE ON `java`.* TO 'java'@'%'; 7 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/data/DataPersona.java: -------------------------------------------------------------------------------- 1 | package data; 2 | //orig 3 | import entities.*; 4 | 5 | import java.sql.*; 6 | import java.util.LinkedList; 7 | 8 | public class DataPersona { 9 | 10 | public LinkedList getAll(){ 11 | DataRol dr=new DataRol(); 12 | Statement stmt=null; 13 | ResultSet rs=null; 14 | LinkedList pers= new LinkedList<>(); 15 | 16 | try { 17 | stmt= DbConnector.getInstancia().getConn().createStatement(); 18 | rs= stmt.executeQuery("select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona"); 19 | //intencionalmente no se recupera la password 20 | if(rs!=null) { 21 | while(rs.next()) { 22 | Persona p=new Persona(); 23 | p.setDocumento(new Documento()); 24 | p.setId(rs.getInt("id")); 25 | p.setNombre(rs.getString("nombre")); 26 | p.setApellido(rs.getString("apellido")); 27 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 28 | p.getDocumento().setNro(rs.getString("nro_doc")); 29 | p.setEmail(rs.getString("email")); 30 | p.setTel(rs.getString("tel")); 31 | 32 | p.setHabilitado(rs.getBoolean("habilitado")); 33 | 34 | dr.setRoles(p); 35 | 36 | pers.add(p); 37 | } 38 | } 39 | 40 | } catch (SQLException e) { 41 | e.printStackTrace(); 42 | 43 | } finally { 44 | try { 45 | if(rs!=null) {rs.close();} 46 | if(stmt!=null) {stmt.close();} 47 | DbConnector.getInstancia().releaseConn(); 48 | } catch (SQLException e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | 53 | 54 | return pers; 55 | } 56 | 57 | public Persona getByUser(Persona per) { 58 | DataRol dr=new DataRol(); 59 | Persona p=null; 60 | PreparedStatement stmt=null; 61 | ResultSet rs=null; 62 | try { 63 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 64 | "select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona where email=? and password=?" 65 | ); 66 | stmt.setString(1, per.getEmail()); 67 | stmt.setString(2, per.getPassword()); 68 | rs=stmt.executeQuery(); 69 | if(rs!=null && rs.next()) { 70 | p=new Persona(); 71 | p.setDocumento(new Documento()); 72 | p.setId(rs.getInt("id")); 73 | p.setNombre(rs.getString("nombre")); 74 | p.setApellido(rs.getString("apellido")); 75 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 76 | p.getDocumento().setNro(rs.getString("nro_doc")); 77 | p.setEmail(rs.getString("email")); 78 | p.setTel(rs.getString("tel")); 79 | p.setHabilitado(rs.getBoolean("habilitado")); 80 | // 81 | dr.setRoles(p); 82 | } 83 | } catch (SQLException e) { 84 | e.printStackTrace(); 85 | }finally { 86 | try { 87 | if(rs!=null) {rs.close();} 88 | if(stmt!=null) {stmt.close();} 89 | DbConnector.getInstancia().releaseConn(); 90 | } catch (SQLException e) { 91 | e.printStackTrace(); 92 | } 93 | } 94 | 95 | return p; 96 | } 97 | 98 | public Persona getByDocumento(Persona per) { 99 | DataRol dr=new DataRol(); 100 | Persona p=null; 101 | PreparedStatement stmt=null; 102 | ResultSet rs=null; 103 | try { 104 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 105 | "select id,nombre,apellido,tipo_doc,nro_doc,email,tel,habilitado from persona where tipo_doc=? and nro_doc=?" 106 | ); 107 | stmt.setString(1, per.getDocumento().getTipo()); 108 | stmt.setString(2, per.getDocumento().getNro()); 109 | rs=stmt.executeQuery(); 110 | if(rs!=null && rs.next()) { 111 | p=new Persona(); 112 | p.setDocumento(new Documento()); 113 | p.setId(rs.getInt("id")); 114 | p.setNombre(rs.getString("nombre")); 115 | p.setApellido(rs.getString("apellido")); 116 | p.getDocumento().setTipo(rs.getString("tipo_doc")); 117 | p.getDocumento().setNro(rs.getString("nro_doc")); 118 | p.setEmail(rs.getString("email")); 119 | p.setTel(rs.getString("tel")); 120 | p.setHabilitado(rs.getBoolean("habilitado")); 121 | // 122 | dr.setRoles(p); 123 | } 124 | } catch (SQLException e) { 125 | e.printStackTrace(); 126 | }finally { 127 | try { 128 | if(rs!=null) {rs.close();} 129 | if(stmt!=null) {stmt.close();} 130 | DbConnector.getInstancia().releaseConn(); 131 | } catch (SQLException e) { 132 | e.printStackTrace(); 133 | } 134 | } 135 | 136 | return p; 137 | } 138 | 139 | public void add(Persona p) { 140 | PreparedStatement stmt= null; 141 | ResultSet keyResultSet=null; 142 | try { 143 | stmt=DbConnector.getInstancia().getConn(). 144 | prepareStatement( 145 | "insert into persona(nombre, apellido, tipo_doc, nro_doc, email, password, tel, habilitado) values(?,?,?,?,?,?,?,?)", 146 | PreparedStatement.RETURN_GENERATED_KEYS 147 | ); 148 | stmt.setString(1, p.getNombre()); 149 | stmt.setString(2, p.getApellido()); 150 | stmt.setString(3, p.getDocumento().getTipo()); 151 | stmt.setString(4, p.getDocumento().getNro()); 152 | stmt.setString(5, p.getEmail()); 153 | stmt.setString(5, p.getPassword()); 154 | stmt.setString(6, p.getTel()); 155 | stmt.setBoolean(7, p.isHabilitado()); 156 | stmt.executeUpdate(); 157 | 158 | keyResultSet=stmt.getGeneratedKeys(); 159 | if(keyResultSet!=null && keyResultSet.next()){ 160 | p.setId(keyResultSet.getInt(1)); 161 | } 162 | 163 | DataRol dr = new DataRol(); 164 | dr.setRolesDePersona(p); 165 | 166 | 167 | } catch (SQLException e) { 168 | e.printStackTrace(); 169 | } finally { 170 | try { 171 | if(keyResultSet!=null)keyResultSet.close(); 172 | if(stmt!=null)stmt.close(); 173 | DbConnector.getInstancia().releaseConn(); 174 | } catch (SQLException e) { 175 | e.printStackTrace(); 176 | } 177 | } 178 | } 179 | 180 | 181 | } 182 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/data/DataRol.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.ResultSet; 5 | import java.sql.SQLException; 6 | import java.sql.Statement; 7 | import java.util.LinkedList; 8 | import entities.*; 9 | 10 | public class DataRol { 11 | 12 | public LinkedList getAll(){ 13 | Statement stmt=null; 14 | ResultSet rs=null; 15 | LinkedList roles= new LinkedList<>(); 16 | 17 | try { 18 | stmt= DbConnector.getInstancia().getConn().createStatement(); 19 | rs= stmt.executeQuery("select * from rol"); 20 | if(rs!=null) { 21 | while(rs.next()) { 22 | Rol r=new Rol(); 23 | r.setId(rs.getInt("id")); 24 | r.setDescripcion(rs.getString("descripcion")); 25 | roles.add(r); 26 | } 27 | } 28 | 29 | } catch (SQLException e) { 30 | e.printStackTrace(); 31 | 32 | } finally { 33 | try { 34 | if(rs!=null) {rs.close();} 35 | if(stmt!=null) {stmt.close();} 36 | DbConnector.getInstancia().releaseConn(); 37 | } catch (SQLException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | 42 | 43 | return roles; 44 | } 45 | 46 | public Rol getById(Rol rolToSearch) { 47 | Rol r=null; 48 | PreparedStatement stmt=null; 49 | ResultSet rs=null; 50 | try { 51 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 52 | "select * from rol where id=?" 53 | ); 54 | stmt.setInt(1, rolToSearch.getId()); 55 | rs=stmt.executeQuery(); 56 | if(rs!=null && rs.next()) { 57 | r=new Rol(); 58 | r.setId(rs.getInt("id")); 59 | r.setDescripcion(rs.getString("descripcion")); 60 | } 61 | } catch (SQLException e) { 62 | e.printStackTrace(); 63 | }finally { 64 | try { 65 | if(rs!=null) {rs.close();} 66 | if(stmt!=null) {stmt.close();} 67 | DbConnector.getInstancia().releaseConn(); 68 | } catch (SQLException e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | 73 | return r; 74 | } 75 | 76 | public Rol getByDesc(Rol rolToSearch) { 77 | Rol r=null; 78 | PreparedStatement stmt=null; 79 | ResultSet rs=null; 80 | try { 81 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 82 | "select * from rol where descripcion=?" 83 | ); 84 | stmt.setString(1, rolToSearch.getDescripcion()); 85 | rs=stmt.executeQuery(); 86 | if(rs!=null && rs.next()) { 87 | r=new Rol(); 88 | r.setId(rs.getInt("id")); 89 | r.setDescripcion(rs.getString("descripcion")); 90 | } 91 | } catch (SQLException e) { 92 | e.printStackTrace(); 93 | }finally { 94 | try { 95 | if(rs!=null) {rs.close();} 96 | if(stmt!=null) {stmt.close();} 97 | DbConnector.getInstancia().releaseConn(); 98 | } catch (SQLException e) { 99 | e.printStackTrace(); 100 | } 101 | } 102 | 103 | return r; 104 | } 105 | 106 | public void setRoles(Persona per) { 107 | PreparedStatement stmt=null; 108 | ResultSet rs=null; 109 | try { 110 | stmt=DbConnector.getInstancia().getConn().prepareStatement( 111 | "select rol.* " 112 | + "from rol " 113 | + "inner join rol_persona " 114 | + "on rol.id=rol_persona.id_rol " 115 | + "where id_persona=?" 116 | ); 117 | stmt.setInt(1, per.getId()); 118 | rs= stmt.executeQuery(); 119 | if(rs!=null) { 120 | while(rs.next()) { 121 | Rol r=new Rol(); 122 | r.setId(rs.getInt("id")); 123 | r.setDescripcion(rs.getString("descripcion")); 124 | per.addRol(r); 125 | } 126 | } 127 | 128 | } catch (SQLException e) { 129 | e.printStackTrace(); 130 | }finally { 131 | try { 132 | if(rs!=null) {rs.close();} 133 | if(stmt!=null) {stmt.close();} 134 | DbConnector.getInstancia().releaseConn(); 135 | } catch (SQLException e) { 136 | e.printStackTrace(); 137 | } 138 | } 139 | } 140 | 141 | public void add(Rol rol) { 142 | PreparedStatement stmt= null; 143 | ResultSet keyResultSet=null; 144 | try { 145 | stmt=DbConnector.getInstancia().getConn(). 146 | prepareStatement( 147 | "insert into rol(descripcion) values(?)", 148 | PreparedStatement.RETURN_GENERATED_KEYS 149 | ); 150 | stmt.setString(1, rol.getDescripcion()); 151 | stmt.executeUpdate(); 152 | 153 | keyResultSet=stmt.getGeneratedKeys(); 154 | if(keyResultSet!=null && keyResultSet.next()){ 155 | rol.setId(keyResultSet.getInt(1)); 156 | } 157 | 158 | 159 | } catch (SQLException e) { 160 | e.printStackTrace(); 161 | } finally { 162 | try { 163 | if(keyResultSet!=null)keyResultSet.close(); 164 | if(stmt!=null)stmt.close(); 165 | DbConnector.getInstancia().releaseConn(); 166 | } catch (SQLException e) { 167 | e.printStackTrace(); 168 | } 169 | } 170 | 171 | } 172 | 173 | public void update(Rol rol) { 174 | PreparedStatement stmt= null; 175 | try { 176 | stmt=DbConnector.getInstancia().getConn(). 177 | prepareStatement( 178 | "update rol set descripcion=? where id=?"); 179 | stmt.setString(1, rol.getDescripcion()); 180 | stmt.setInt(2, rol.getId()); 181 | stmt.executeUpdate(); 182 | } catch (SQLException e) { 183 | e.printStackTrace(); 184 | } finally { 185 | try { 186 | if(stmt!=null)stmt.close(); 187 | DbConnector.getInstancia().releaseConn(); 188 | } catch (SQLException e) { 189 | e.printStackTrace(); 190 | } 191 | } 192 | } 193 | 194 | public void remove(Rol rol) { 195 | PreparedStatement stmt= null; 196 | try { 197 | stmt=DbConnector.getInstancia().getConn(). 198 | prepareStatement( 199 | "delete from rol where id=?"); 200 | stmt.setInt(1, rol.getId()); 201 | stmt.executeUpdate(); 202 | } catch (SQLException e) { 203 | e.printStackTrace(); 204 | } finally { 205 | try { 206 | if(stmt!=null)stmt.close(); 207 | DbConnector.getInstancia().releaseConn(); 208 | } catch (SQLException e) { 209 | e.printStackTrace(); 210 | } 211 | } 212 | } 213 | 214 | public void setRolesDePersona(Persona p) { 215 | 216 | PreparedStatement stmt= null; 217 | try { 218 | stmt=DbConnector.getInstancia().getConn(). 219 | prepareStatement( 220 | "insert into rol_persona values(?,?);"); 221 | stmt.setInt(1,p.getId()); 222 | for(Rol r:p.getAllRoles().values()) { 223 | stmt.setInt(2, r.getId()); 224 | stmt.executeUpdate(); 225 | } 226 | 227 | } catch (SQLException e) { 228 | e.printStackTrace(); 229 | } finally { 230 | try { 231 | if(stmt!=null)stmt.close(); 232 | DbConnector.getInstancia().releaseConn(); 233 | } catch (SQLException e) { 234 | e.printStackTrace(); 235 | } 236 | } 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/data/DbConnector.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.*; 4 | 5 | public class DbConnector { 6 | 7 | private static DbConnector instancia; 8 | 9 | private String driver="com.mysql.cj.jdbc.Driver"; 10 | private String host="localhost"; 11 | private String port="3306"; 12 | private String user="java"; 13 | private String password="himitsu"; 14 | private String db="java"; 15 | private int conectados=0; 16 | private Connection conn=null; 17 | 18 | private DbConnector() { 19 | try { 20 | Class.forName(driver); 21 | } catch (ClassNotFoundException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | 26 | public static DbConnector getInstancia() { 27 | if (instancia == null) { 28 | instancia = new DbConnector(); 29 | } 30 | return instancia; 31 | } 32 | 33 | public Connection getConn() { 34 | try { 35 | if(conn==null || conn.isClosed()) { 36 | conn=DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+db, user, password); 37 | conectados=0; 38 | } 39 | } catch (SQLException e) { 40 | e.printStackTrace(); 41 | } 42 | conectados++; 43 | return conn; 44 | } 45 | 46 | public void releaseConn() { 47 | conectados--; 48 | try { 49 | if (conectados<=0) { 50 | conn.close(); 51 | } 52 | } catch (SQLException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/entities/Documento.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Documento { 4 | private String tipo; 5 | private String nro; 6 | public String getTipo() { 7 | return tipo; 8 | } 9 | public void setTipo(String tipo) { 10 | this.tipo = tipo; 11 | } 12 | public String getNro() { 13 | return nro; 14 | } 15 | public void setNro(String nro) { 16 | this.nro = nro; 17 | } 18 | @Override 19 | public String toString() { 20 | return "Documento [tipo=" + tipo + ", nro=" + nro + "]"; 21 | } 22 | 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/entities/Persona.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Persona { 6 | private int id; 7 | private Documento documento; 8 | private String nombre; 9 | private String apellido; 10 | private String email; 11 | private String password; 12 | private String tel; 13 | private boolean habilitado; 14 | private HashMap roles; 15 | 16 | public int getId() { 17 | return id; 18 | } 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | public Documento getDocumento() { 23 | return documento; 24 | } 25 | public void setDocumento(Documento documento) { 26 | this.documento = documento; 27 | } 28 | public String getNombre() { 29 | return nombre; 30 | } 31 | public void setNombre(String nombre) { 32 | this.nombre = nombre; 33 | } 34 | public String getApellido() { 35 | return apellido; 36 | } 37 | public void setApellido(String apellido) { 38 | this.apellido = apellido; 39 | } 40 | public String getEmail() { 41 | return email; 42 | } 43 | public void setEmail(String email) { 44 | this.email = email; 45 | } 46 | public String getPassword() { 47 | return password; 48 | } 49 | public void setPassword(String password) { 50 | this.password = password; 51 | } 52 | public String getTel() { 53 | return tel; 54 | } 55 | public void setTel(String tel) { 56 | this.tel = tel; 57 | } 58 | public boolean isHabilitado() { 59 | return habilitado; 60 | } 61 | public void setHabilitado(boolean habilitado) { 62 | this.habilitado = habilitado; 63 | } 64 | 65 | public Persona() { 66 | this.roles=new HashMap<>(); 67 | } 68 | 69 | public void addRol(Rol rolToBeAdded) { 70 | this.roles.put(rolToBeAdded.getId(), rolToBeAdded); 71 | } 72 | 73 | public void removeRol(Rol rolToBeRemoved) { 74 | this.roles.remove(rolToBeRemoved.getId()); 75 | } 76 | 77 | public boolean hasRol(Rol rolToCheck) { 78 | return this.roles.containsKey(rolToCheck.getId()); 79 | } 80 | 81 | public HashMap getAllRoles(){ 82 | return this.roles; 83 | } 84 | 85 | @Override 86 | public String toString() { 87 | return "\nPersona [id=" + id + ", documento=" + documento + ", nombre=" + nombre + ", apellido=" + apellido 88 | + ", email=" + email + ", tel=" + tel + ", habilitado=" + habilitado + ", roles=" + roles + "]"; 89 | } 90 | 91 | 92 | 93 | } 94 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/entities/Rol.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | public class Rol { 4 | private int id; 5 | private String descripcion; 6 | public int getId() { 7 | return id; 8 | } 9 | public void setId(int id) { 10 | this.id = id; 11 | } 12 | public String getDescripcion() { 13 | return descripcion; 14 | } 15 | public void setDescripcion(String descripcion) { 16 | this.descripcion = descripcion; 17 | } 18 | @Override 19 | public String toString() { 20 | return "Rol [id=" + id + ", descripcion=" + descripcion + "]"; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/logic/Login.java: -------------------------------------------------------------------------------- 1 | package logic; 2 | 3 | import java.util.LinkedList; 4 | 5 | import data.*; 6 | import entities.*; 7 | 8 | public class Login { 9 | private DataPersona dp; 10 | 11 | public Login() { 12 | dp=new DataPersona(); 13 | } 14 | 15 | public Persona validate(Persona p) { 16 | /* para hacer más seguro el manejo de passwords este sería un lugar 17 | * adecuado para generar un hash de la password utilizando un cifrado 18 | * asimétrico como sha256 y utilizar el hash en lugar de la password en plano 19 | */ 20 | return dp.getByUser(p); 21 | } 22 | 23 | public LinkedList getAll(){ 24 | return dp.getAll(); 25 | } 26 | 27 | public Persona getByDocumento(Persona per) { 28 | return dp.getByDocumento(per); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/servlet/Signin.java: -------------------------------------------------------------------------------- 1 | package servlet; 2 | 3 | import jakarta.servlet.ServletException; 4 | import jakarta.servlet.annotation.WebServlet; 5 | import jakarta.servlet.http.HttpServlet; 6 | import jakarta.servlet.http.HttpServletRequest; 7 | import jakarta.servlet.http.HttpServletResponse; 8 | import java.io.IOException; 9 | import java.util.LinkedList; 10 | 11 | import entities.Persona; 12 | import logic.Login; 13 | 14 | /** 15 | * Servlet implementation class Signin 16 | */ 17 | public class Signin extends HttpServlet { 18 | private static final long serialVersionUID = 1L; 19 | 20 | /** 21 | * @see HttpServlet#HttpServlet() 22 | */ 23 | public Signin() { 24 | super(); 25 | // TODO Auto-generated constructor stub 26 | } 27 | 28 | /** 29 | * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 30 | */ 31 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 | // TODO Auto-generated method stub 33 | response.getWriter().append("Served at: ").append(request.getContextPath()); 34 | } 35 | 36 | /** 37 | * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 38 | */ 39 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 40 | // TODO Auto-generated method stub 41 | Persona per = new Persona(); 42 | Login ctrl = new Login(); 43 | 44 | String email = request.getParameter("email"); 45 | String password = request.getParameter("password"); 46 | 47 | //validar email y password 48 | 49 | per.setEmail(email); 50 | per.setPassword(password); 51 | 52 | per=ctrl.validate(per); 53 | LinkedList personas = ctrl.getAll(); 54 | 55 | 56 | request.getSession().setAttribute("usuario", per); 57 | request.setAttribute("listaPersonas", personas); 58 | 59 | request.getRequestDispatcher("WEB-INF/UserManagement.jsp").forward(request, response); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/java/servlet/UploadServlet.java: -------------------------------------------------------------------------------- 1 | package servlet; 2 | 3 | import jakarta.servlet.ServletException; 4 | import jakarta.servlet.annotation.MultipartConfig; 5 | import jakarta.servlet.annotation.WebServlet; 6 | import jakarta.servlet.http.HttpServlet; 7 | import jakarta.servlet.http.HttpServletRequest; 8 | import jakarta.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | import java.io.File; 11 | import jakarta.servlet.http.Part; 12 | 13 | /** 14 | * Servlet implementation class UploadServlet 15 | */ 16 | @MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB 17 | maxFileSize=1024*1024*50, // 50 MB 18 | maxRequestSize=1024*1024*100) // 100 MB 19 | public class UploadServlet extends HttpServlet { 20 | private static final long serialVersionUID = 1L; 21 | 22 | private static final String UPLOAD_DIR = "uploads"; 23 | 24 | public UploadServlet() { 25 | super(); 26 | // TODO Auto-generated constructor stub 27 | } 28 | 29 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 30 | // TODO Auto-generated method stub 31 | response.getWriter().append("Served at: ").append(request.getContextPath()); 32 | } 33 | 34 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 | // gets absolute path of the web application 36 | String applicationPath = request.getServletContext().getRealPath(""); 37 | // constructs path of the directory to save uploaded file 38 | String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; 39 | 40 | File fileSaveDir = new File(uploadFilePath); 41 | if (!fileSaveDir.exists()) { 42 | fileSaveDir.mkdirs(); 43 | } 44 | System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath()); 45 | 46 | String fileName = null; 47 | //Get all the parts from request and write it to the file on server 48 | for (Part part : request.getParts()) { 49 | fileName = getFileName(part); 50 | part.write(uploadFilePath + File.separator + fileName); 51 | } 52 | 53 | request.setAttribute("message", fileName + " File uploaded successfully!"); 54 | request.setAttribute("img", UPLOAD_DIR+File.separator +fileName); 55 | getServletContext().getRequestDispatcher("/response.jsp").forward( 56 | request, response); 57 | } 58 | 59 | private String getFileName(Part part) { 60 | String contentDisp = part.getHeader("content-disposition"); 61 | System.out.println("content-disposition header= "+contentDisp); 62 | String[] tokens = contentDisp.split(";"); 63 | for (String token : tokens) { 64 | if (token.trim().startsWith("filename")) { 65 | return token.substring(token.indexOf("=") + 2, token.length()-1); 66 | } 67 | } 68 | return ""; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/WEB-INF/UserManagement.jsp: -------------------------------------------------------------------------------- 1 | <%@ page import="java.util.LinkedList" %> 2 | <%@ page import="entities.Persona" %> 3 | <%@ page import="java.util.LinkedList" %> 4 | 5 | 6 | <%@ page language="java" contentType="text/html; charset=UTF-8" 7 | pageEncoding="UTF-8"%> 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | Java Web Intro 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | <% 28 | 29 | Persona p = (Persona) session.getAttribute("usuario"); 30 | LinkedList lp = (LinkedList)request.getAttribute("listaPersonas"); 31 | %> 32 | 33 | 34 | 35 |
36 |
37 | Hola <%=p.getNombre()%> 38 |
39 |
40 |

Personas

41 |
42 |
43 |
idnombreapellidoemailtelhabilitado
<%=per.getId()%><%=per.getNombre()%><%=per.getApellido()%><%=per.getEmail()%><%=per.getTel()%> 58 |
59 | disabled> 60 | 61 |
62 |
44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | <% for (Persona per : lp) { %> 58 | 59 | 60 | 61 | 62 | 63 | 64 | 70 | 71 | 72 | 73 | <% } %> 74 | 75 |
idnombreapellidoemailtelhabilitado
<%=per.getId()%><%=per.getNombre()%><%=per.getApellido()%><%=per.getEmail()%><%=per.getTel()%> 65 |
66 | disabled> 67 | 68 |
69 |
76 |
77 |
78 |
79 |
80 | 81 | 82 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/WEB-INF/lib/mysql-connector-java-8.0.29.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ej6WebIntro2022/src/main/webapp/WEB-INF/lib/mysql-connector-java-8.0.29.jar -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Signin 6 | Signin 7 | servlet.Signin 8 | 9 | 10 | Signin 11 | /signin 12 | /Signin 13 | /signIn 14 | /SignIn 15 | /SIGNIN 16 | 17 | Ej6WebIntro2022 18 | 19 | index.html 20 | index.htm 21 | index.jsp 22 | default.html 23 | default.htm 24 | default.jsp 25 | 26 | 27 | 28 | UploadServlet 29 | UploadServlet 30 | servlet.UploadServlet 31 | 32 | 33 | UploadServlet 34 | /UploadServlet 35 | /uploadservlet 36 | /uploadServlet 37 | 38 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/image.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |
9 | Select File to Upload: 10 |
11 | 12 |
13 | 14 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Java Web Intro 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/response.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 | pageEncoding="ISO-8859-1"%> 3 | 5 | 6 | 7 | Upload File Response 8 | 9 | 10 | <%-- Using JSP EL to get message attribute value from request scope --%> 11 |

${requestScope.message}

12 | HTML5 Doctor Logo 13 | 14 | -------------------------------------------------------------------------------- /ejemplos/Ej6WebIntro2022/src/main/webapp/style/signin.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | height: 100%; 4 | } 5 | 6 | body { 7 | display: -ms-flexbox; 8 | display: flex; 9 | -ms-flex-align: center; 10 | align-items: center; 11 | padding-top: 40px; 12 | padding-bottom: 40px; 13 | background-color: #f5f5f5; 14 | } 15 | 16 | .form-signin { 17 | width: 100%; 18 | max-width: 330px; 19 | padding: 15px; 20 | margin: auto; 21 | } 22 | .form-signin .checkbox { 23 | font-weight: 400; 24 | } 25 | .form-signin .form-control { 26 | position: relative; 27 | box-sizing: border-box; 28 | height: auto; 29 | padding: 10px; 30 | font-size: 16px; 31 | } 32 | .form-signin .form-control:focus { 33 | z-index: 2; 34 | } 35 | .form-signin input[type="email"] { 36 | margin-bottom: -1px; 37 | border-bottom-right-radius: 0; 38 | border-bottom-left-radius: 0; 39 | } 40 | .form-signin input[type="password"] { 41 | margin-bottom: 10px; 42 | border-top-left-radius: 0; 43 | border-top-right-radius: 0; 44 | } 45 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio05/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio05/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ejercicio05 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 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio05/src/entidades/Administrativo.java: -------------------------------------------------------------------------------- 1 | package entidades; 2 | 3 | public class Administrativo extends Empleado{ 4 | private int hsExtra; 5 | private int hsMes; 6 | public int getHsExtra() { 7 | return hsExtra; 8 | } 9 | public void setHsExtra(int hsExtra) { 10 | this.hsExtra = hsExtra; 11 | } 12 | public int getHsMes() { 13 | return hsMes; 14 | } 15 | public void setHsMes(int hsMes) { 16 | this.hsMes = hsMes; 17 | } 18 | 19 | public Administrativo() {} 20 | 21 | public Administrativo(int dni, String nombre, String apellido, 22 | double sueldoBase,int hsExtra, int hsMes) { 23 | super(dni,nombre,apellido,sueldoBase); 24 | 25 | this.setHsExtra(hsExtra); 26 | this.setHsMes(hsMes); 27 | } 28 | 29 | @Override 30 | public double getSueldo() { 31 | 32 | return getSueldoBase()*((getHsExtra()*1.5+getHsMes())/getHsMes()); 33 | } 34 | 35 | public String getDetalle() { 36 | return "Administrativo "+super.getDetalle(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio05/src/entidades/Empleado.java: -------------------------------------------------------------------------------- 1 | package entidades; 2 | 3 | public abstract class Empleado { 4 | 5 | private int dni; 6 | private String nombre; 7 | private String apellido; 8 | private double sueldoBase; 9 | 10 | public int getDni() { 11 | return dni; 12 | } 13 | public void setDni(int dni) { 14 | this.dni = dni; 15 | } 16 | public String getNombre() { 17 | return nombre; 18 | } 19 | public void setNombre(String nombre) { 20 | this.nombre = nombre; 21 | } 22 | public String getApellido() { 23 | return apellido; 24 | } 25 | public void setApellido(String apellido) { 26 | this.apellido = apellido; 27 | } 28 | 29 | 30 | public double getSueldoBase() { 31 | return sueldoBase; 32 | } 33 | public void setSueldoBase(double sueldoBase) { 34 | this.sueldoBase = sueldoBase; 35 | } 36 | public abstract double getSueldo(); 37 | 38 | public String getDetalle() { 39 | return this.getDni()+" - "+this.getApellido()+": "; 40 | } 41 | 42 | public Empleado() {} 43 | 44 | public Empleado(int dni, String nombre, String apellido, double sueldoBase) { 45 | this.setDni(dni); 46 | this.setNombre(nombre); 47 | this.setApellido(apellido); 48 | this.setSueldoBase(sueldoBase); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio05/src/entidades/Vendedor.java: -------------------------------------------------------------------------------- 1 | package entidades; 2 | 3 | public class Vendedor extends Empleado{ 4 | private double porcenComision; 5 | private double totalVtas; 6 | public double getPorcenComision() { 7 | return porcenComision; 8 | } 9 | public void setPorcenComision(double porcenComision) { 10 | this.porcenComision = porcenComision; 11 | } 12 | public double getTotalVtas() { 13 | return totalVtas; 14 | } 15 | public void setTotalVtas(double totalVtas) { 16 | this.totalVtas = totalVtas; 17 | } 18 | 19 | public double getSueldo() { 20 | return this.getSueldoBase()+(this.porcenComision*this.getTotalVtas())/100; 21 | } 22 | 23 | public String getDetalle() { 24 | return "Responsable de vtas "+super.getDetalle(); 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio05/src/ui/Ppal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.util.Scanner; 4 | 5 | import javax.swing.JOptionPane; 6 | 7 | import entidades.*; 8 | 9 | public class Ppal { 10 | static Scanner lector; 11 | public static void main(String[] args) { 12 | 13 | Empleado[] empleados = new Empleado[3]; 14 | lector=new Scanner(System.in); 15 | 16 | Administrativo a=new Administrativo(); 17 | cargaDatosComunes(a); 18 | a.setHsExtra(50); 19 | a.setHsMes(100); 20 | a.setSueldoBase(1000); 21 | 22 | 23 | empleados[0]=a; 24 | 25 | empleados[1]=new Vendedor(); 26 | cargaDatosComunes(empleados[1]); 27 | ((Vendedor)empleados[1]).setTotalVtas(500); 28 | ((Vendedor)empleados[1]).setSueldoBase(2000); 29 | ((Vendedor)empleados[1]).setPorcenComision(10); 30 | 31 | empleados[2]=new Vendedor(); 32 | cargaDatosComunes(empleados[2]); 33 | ((Vendedor)empleados[2]).setTotalVtas(1000); 34 | ((Vendedor)empleados[2]).setSueldoBase(100); 35 | ((Vendedor)empleados[2]).setPorcenComision(20); 36 | 37 | for (Empleado empleado : empleados) { 38 | System.out.println("DNI: "+empleado.getDni()); 39 | // if (empleado instanceof Administrativo) { 40 | // System.out.println("HS extra: "+((Administrativo)empleado).getHsExtra()); 41 | // } 42 | System.out.println(empleado.getDetalle()+ empleado.getSueldo()); 43 | } 44 | lector.close(); 45 | } 46 | 47 | public static void cargaDatosComunes(Empleado e) { 48 | System.out.print("ingrese dni: "); 49 | e.setDni(Integer.parseInt(lector.nextLine())); 50 | 51 | System.out.print("ingrese apellido: "); 52 | e.setApellido(lector.nextLine()); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCB/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCB/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ejercicio6JDBCB 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 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCB/lib/mysql-connector-java-8.0.25.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ejercicio6JDBCB/lib/mysql-connector-java-8.0.25.jar -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCB/src/entities/Product.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.time.*; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class Product { 7 | final private String dateFormat="dd/MM/yyyy"; 8 | final private String timeFormat="HH:mm:ss"; 9 | final private String dateTimeFormat=dateFormat+" "+timeFormat; 10 | private int id; 11 | private String name; 12 | private String description; 13 | private double price; 14 | private int stock; 15 | private boolean shippingIncluded; 16 | private LocalDateTime disabledOn; 17 | private LocalDate disabledDate; 18 | private LocalTime disabledTime; 19 | private ZonedDateTime disabledOnZoned; 20 | 21 | public ZonedDateTime getDisabledOnZoned() { 22 | return disabledOnZoned; 23 | } 24 | public void setDisabledOnZoned(ZonedDateTime disabledOnZoned) { 25 | this.disabledOnZoned = disabledOnZoned; 26 | } 27 | public int getId() { 28 | return id; 29 | } 30 | public void setId(int id) { 31 | this.id = id; 32 | } 33 | public String getName() { 34 | return name; 35 | } 36 | public void setName(String name) { 37 | this.name = name; 38 | } 39 | public String getDescription() { 40 | return description; 41 | } 42 | public void setDescription(String description) { 43 | this.description = description; 44 | } 45 | public double getPrice() { 46 | return price; 47 | } 48 | public void setPrice(double price) { 49 | this.price = price; 50 | } 51 | public int getStock() { 52 | return stock; 53 | } 54 | public void setStock(int stock) { 55 | this.stock = stock; 56 | } 57 | public boolean isShippingIncluded() { 58 | return shippingIncluded; 59 | } 60 | public void setShippingIncluded(boolean shippingIncluded) { 61 | this.shippingIncluded = shippingIncluded; 62 | } 63 | public LocalDateTime getDisabledOn() { 64 | return disabledOn; 65 | } 66 | public void setDisabledOn(LocalDateTime disabledOn) { 67 | this.disabledOn = disabledOn; 68 | } 69 | public LocalDate getDisabledDate() { 70 | return disabledDate; 71 | } 72 | public void setDisabledDate(LocalDate disabledDate) { 73 | this.disabledDate = disabledDate; 74 | } 75 | public LocalTime getDisabledTime() { 76 | return disabledTime; 77 | } 78 | public void setDisabledTime(LocalTime disabledTime) { 79 | this.disabledTime = disabledTime; 80 | } 81 | @Override 82 | public String toString() { 83 | DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern(dateTimeFormat); 84 | DateTimeFormatter dFormat = DateTimeFormatter.ofPattern(dateFormat); 85 | DateTimeFormatter tFormat = DateTimeFormatter.ofPattern(timeFormat); 86 | return "Product [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price 87 | + ", stock=" + stock+ ", shippingIncluded=" + shippingIncluded 88 | + ", disabledOn=" + (disabledOn==null?null:disabledOn.format(dtFormat)) 89 | + ", disabledDate=" + (disabledDate==null?null:disabledDate.format(dFormat)) 90 | + ", disabledTime=" + (disabledTime==null?null:disabledTime.format(tFormat)) 91 | + ", disabledOnZoned=" + (disabledOnZoned==null?null:disabledOnZoned.format(dtFormat.withZone(ZoneId.of("UTC"))))+ "]\n"; 92 | } 93 | 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCB/src/ui/Menu.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.time.*; 4 | import java.time.format.DateTimeFormatter; 5 | import java.time.temporal.TemporalAccessor; 6 | import java.util.Scanner; 7 | 8 | import com.mysql.cj.result.LocalDateTimeValueFactory; 9 | 10 | import data.DbHandler; 11 | import entities.Product; 12 | 13 | public class Menu { 14 | final private String dateFormat="dd/MM/yyyy"; 15 | final private String timeFormat="HH:mm:ss"; 16 | final private String dateTimeFormat=dateFormat+" "+timeFormat; 17 | private Scanner scan; 18 | private DbHandler db=new DbHandler(); 19 | 20 | public void start() { 21 | 22 | 23 | scan = new Scanner(System.in); 24 | 25 | // muestran las opciones y según que elija el usuario 26 | String rta=""; 27 | 28 | do { 29 | rta=menu(); 30 | 31 | switch (rta) { 32 | case "list": 33 | list(); 34 | break; 35 | case "search": 36 | search(); 37 | break; 38 | case "new": 39 | newProduct(); 40 | break; 41 | case "delete": 42 | delete(); 43 | break; 44 | case "update": 45 | update(); 46 | break; 47 | case "exit": 48 | System.out.println("Sore ja, mata ne, byebye"); 49 | break; 50 | default: 51 | System.out.println("command not found...try again"); 52 | break; 53 | } 54 | 55 | } while (!rta.equals("exit")); 56 | 57 | scan.close(); 58 | 59 | } 60 | 61 | private void update() { 62 | Product updPrd = new Product(); 63 | System.out.print("Input the id of the product to be modified: "); 64 | updPrd.setId(Integer.parseInt(scan.nextLine())); 65 | 66 | System.out.println("Current data: "); 67 | System.out.println(db.search(updPrd)); 68 | 69 | loadData(updPrd); 70 | 71 | db.update(updPrd); 72 | 73 | } 74 | 75 | private void delete() { 76 | Product delPrd = new Product(); 77 | System.out.println("Current products:"); 78 | this.list(); 79 | System.out.print("Input the id of the product to be deleted: "); 80 | delPrd.setId(Integer.parseInt(scan.nextLine())); 81 | db.delete(delPrd); 82 | } 83 | 84 | private void newProduct() { 85 | Product newPrd= new Product(); 86 | 87 | System.out.println("Input new product data:"); 88 | 89 | loadData(newPrd); 90 | 91 | db.newProduct(newPrd); 92 | 93 | System.out.println("The new product's id is: " + newPrd.getId()); 94 | 95 | } 96 | 97 | private void loadData(Product prd) { 98 | System.out.print("Name: "); 99 | prd.setName(scan.nextLine()); 100 | 101 | System.out.print("Description: "); 102 | prd.setDescription(scan.nextLine()); 103 | 104 | System.out.print("Price: "); 105 | prd.setPrice(Double.parseDouble(scan.nextLine())); 106 | 107 | System.out.print("Stock: "); 108 | prd.setStock(Integer.parseInt(scan.nextLine())); 109 | 110 | System.out.print("Include Shipping? (Y/N): "); 111 | prd.setShippingIncluded(scan.nextLine().trim().equalsIgnoreCase("Y")); 112 | 113 | System.out.print("Disabled on ("+dateTimeFormat+"): "); 114 | DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern(dateTimeFormat); 115 | prd.setDisabledOn(LocalDateTime.parse(scan.nextLine(),dtFormat));; 116 | 117 | DateTimeFormatter dFormat = DateTimeFormatter.ofPattern(dateFormat); 118 | System.out.print("Disabled date ("+dateFormat+"): "); 119 | prd.setDisabledDate(LocalDate.parse(scan.nextLine(),dFormat));; 120 | 121 | System.out.print("Disabled Time ("+timeFormat+"): "); 122 | DateTimeFormatter tFormat = DateTimeFormatter.ofPattern(timeFormat); 123 | prd.setDisabledTime(LocalTime.parse(scan.nextLine(),tFormat));; 124 | 125 | System.out.print("Disabled zoned ("+dateTimeFormat+"): "); 126 | prd.setDisabledOnZoned(ZonedDateTime.parse(scan.nextLine(),dtFormat.withZone(ZoneId.of("UTC"))));; 127 | 128 | } 129 | 130 | private String menu() { 131 | 132 | System.out.println("Input command: list/search/new/delete/update/exit"); 133 | return scan.nextLine(); 134 | } 135 | 136 | private void list() { 137 | // for(Product p: db.list()) { 138 | // System.out.println(p); 139 | // } 140 | System.out.println(db.list()); 141 | } 142 | 143 | private void search() { 144 | Product p = new Product(); 145 | System.out.print("Input search id: "); 146 | p.setId(Integer.parseInt(scan.nextLine())); 147 | Product prod=db.search(p); 148 | if(prod!=null) { 149 | System.out.println(prod); 150 | }else { 151 | System.out.println("404 - Not found"); 152 | } 153 | } 154 | 155 | } 156 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCB/src/ui/Principal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | public class Principal { 4 | 5 | 6 | public static void main(String[] args) { 7 | new Menu().start(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCTM/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCTM/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ejercicio6JDBCTM 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 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCTM/lib/mysql-connector-java-8.0.25.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ejercicio6JDBCTM/lib/mysql-connector-java-8.0.25.jar -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCTM/src/data/DbHandler.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.*; 4 | import java.time.*; 5 | import java.util.LinkedList; 6 | 7 | import entities.Product; 8 | 9 | public class DbHandler { 10 | 11 | private String driver="com.mysql.cj.jdbc.Driver"; 12 | private String host="localhost"; 13 | private String port="3306"; 14 | private String user="java"; 15 | private String password="himitsu"; 16 | private String db="javaMarket"; 17 | //private String options="?useLegacyDatetimeCode=false&serverTimezone=Asia/Hong_Kong"; 18 | private String options=""; 19 | 20 | private Connection conn=null; 21 | 22 | public DbHandler() { 23 | try { 24 | Class.forName(driver); 25 | } catch (ClassNotFoundException e) { 26 | e.printStackTrace(); 27 | } 28 | } 29 | 30 | private Connection getConnection() { 31 | try { 32 | if(conn==null || conn.isClosed()) 33 | conn=DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+db+options, user, password); 34 | } catch (SQLException e) { 35 | e.printStackTrace(); 36 | } 37 | return conn; 38 | } 39 | 40 | private void releaseConnection() { 41 | try { 42 | if(conn!=null && !conn.isClosed()) { 43 | conn.close(); 44 | } 45 | } catch (SQLException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | 50 | 51 | public LinkedList list(){ 52 | Statement stmt=null; 53 | ResultSet rs=null; 54 | Connection conn; 55 | 56 | try { 57 | conn=this.getConnection(); 58 | LinkedList prods = new LinkedList(); 59 | stmt = conn.createStatement(); 60 | rs = stmt.executeQuery("select * from product"); 61 | 62 | while(rs != null && rs.next()) { 63 | Product p = new Product(); 64 | 65 | p.setId(rs.getInt("id")); 66 | p.setName(rs.getString("name")); 67 | p.setDescription(rs.getString("description")); 68 | p.setPrice(rs.getDouble("price")); 69 | p.setStock(rs.getInt("stock")); 70 | p.setShippingIncluded(rs.getBoolean("shippingIncluded")); 71 | p.setDisabledOn(rs.getObject("disabledOn",LocalDateTime.class)); 72 | p.setDisabledDate(rs.getObject("disabledDate",LocalDate.class)); 73 | p.setDisabledTime(rs.getObject("disabledTime",LocalTime.class)); 74 | p.setDisabledOnZoned(rs.getObject("disabledOnZoned",ZonedDateTime.class)); 75 | 76 | prods.add(p); 77 | } 78 | return prods; 79 | 80 | } catch (SQLException e) { 81 | e.printStackTrace(); 82 | return null; 83 | } finally { 84 | try { 85 | if(rs!=null)rs.close(); 86 | if(stmt!=null)stmt.close(); 87 | this.releaseConnection(); 88 | } catch (SQLException e) { 89 | e.printStackTrace(); 90 | } 91 | } 92 | 93 | 94 | } 95 | 96 | public Product search(Product p){ //reciben un product que solo tenga un id o reciben el id 97 | 98 | 99 | PreparedStatement stmt =null; 100 | ResultSet rs=null; 101 | Connection conn=null; 102 | 103 | try { 104 | conn=this.getConnection(); 105 | Product prod = null; 106 | stmt = conn.prepareStatement("select * from product where id = ?"); 107 | stmt.setInt(1, p.getId()); 108 | 109 | rs = stmt.executeQuery(); 110 | 111 | if(rs!=null && rs.next()) { 112 | prod = new Product(); 113 | prod.setId(rs.getInt("id")); 114 | prod.setName(rs.getString("name")); 115 | prod.setDescription(rs.getString("description")); 116 | prod.setPrice(rs.getDouble("price")); 117 | prod.setStock(rs.getInt("stock")); 118 | prod.setShippingIncluded(rs.getBoolean("shippingIncluded")); 119 | prod.setDisabledOn(rs.getObject("disabledOn",LocalDateTime.class)); 120 | prod.setDisabledDate(rs.getObject("disabledDate",LocalDate.class)); 121 | prod.setDisabledTime(rs.getObject("disabledTime",LocalTime.class)); 122 | prod.setDisabledOnZoned(rs.getObject("disabledOnZoned",ZonedDateTime.class)); 123 | 124 | } 125 | return prod; 126 | } catch (SQLException e) { 127 | e.printStackTrace(); 128 | return null; 129 | } finally { 130 | try { 131 | if(rs!=null)rs.close(); 132 | if(stmt!=null)stmt.close(); 133 | this.releaseConnection(); 134 | } catch (SQLException e) { 135 | e.printStackTrace(); 136 | } 137 | } 138 | 139 | } 140 | 141 | public void newProduct(Product newPrd) { 142 | 143 | PreparedStatement stmt =null; 144 | ResultSet keyRS=null; 145 | Connection conn = null; 146 | 147 | 148 | try { 149 | conn=this.getConnection(); 150 | stmt = conn.prepareStatement( 151 | "insert into product(name, description, price, stock, shippingIncluded, disabledOn, disabledDate, disabledTime, disabledOnZoned) "+ 152 | "values(?,?,?,?,?,?,?,?,?)" 153 | , Statement.RETURN_GENERATED_KEYS); 154 | stmt.setString(1, newPrd.getName()); 155 | stmt.setString(2, newPrd.getDescription()); 156 | stmt.setDouble(3, newPrd.getPrice()); 157 | stmt.setInt(4, newPrd.getStock()); 158 | stmt.setBoolean(5, newPrd.isShippingIncluded()); 159 | stmt.setObject(6, newPrd.getDisabledOn()); 160 | stmt.setObject(7, newPrd.getDisabledDate()); 161 | stmt.setObject(8, newPrd.getDisabledTime()); 162 | stmt.setObject(9, newPrd.getDisabledOnZoned()); 163 | 164 | 165 | stmt.executeUpdate(); 166 | 167 | keyRS= stmt.getGeneratedKeys(); 168 | 169 | if(keyRS!=null && keyRS.next()) { 170 | newPrd.setId(keyRS.getInt(1)); 171 | } 172 | 173 | } catch (SQLException e) { 174 | e.printStackTrace(); 175 | } finally { 176 | try { 177 | if(keyRS!=null)keyRS.close(); 178 | if(stmt!=null)stmt.close(); 179 | this.releaseConnection(); 180 | } catch (SQLException e) { 181 | e.printStackTrace(); 182 | } 183 | } 184 | } 185 | 186 | public void delete(Product delPrd) { 187 | PreparedStatement stmt =null; 188 | Connection conn = null; 189 | 190 | 191 | try { 192 | conn=this.getConnection(); 193 | stmt = conn.prepareStatement("delete from product where id = ?"); 194 | 195 | stmt.setInt(1, delPrd.getId()); 196 | 197 | stmt.executeUpdate(); 198 | 199 | } catch (SQLException e) { 200 | e.printStackTrace(); 201 | } finally { 202 | try { 203 | if(stmt!=null)stmt.close(); 204 | this.releaseConnection(); 205 | } catch (SQLException e) { 206 | e.printStackTrace(); 207 | } 208 | } 209 | } 210 | 211 | public void update(Product updPrd) { 212 | PreparedStatement stmt =null; 213 | Connection conn = null; 214 | 215 | try { 216 | conn=this.getConnection(); 217 | stmt = conn.prepareStatement( 218 | "update product "+ 219 | "set name = ?, description = ?, price = ?, stock = ?, shippingIncluded = ? "+ 220 | ",disabledOn = ?, disabledDate = ?, disabledTime = ?, disabledOnZoned = ? "+ 221 | "where id = ?"); 222 | stmt.setString(1, updPrd.getName()); 223 | stmt.setString(2, updPrd.getDescription()); 224 | stmt.setDouble(3, updPrd.getPrice()); 225 | stmt.setInt(4, updPrd.getStock()); 226 | stmt.setBoolean(5, updPrd.isShippingIncluded()); 227 | stmt.setObject(6, updPrd.getDisabledOn()); 228 | stmt.setObject(7, updPrd.getDisabledDate()); 229 | stmt.setObject(8, updPrd.getDisabledTime()); 230 | stmt.setObject(9, updPrd.getDisabledOnZoned()); 231 | stmt.setInt(10, updPrd.getId()); 232 | 233 | stmt.executeUpdate(); 234 | 235 | } catch (SQLException e) { 236 | e.printStackTrace(); 237 | } finally { 238 | try { 239 | if(stmt!=null)stmt.close(); 240 | this.releaseConnection(); 241 | } catch (SQLException e) { 242 | e.printStackTrace(); 243 | } 244 | } 245 | } 246 | 247 | } 248 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCTM/src/entities/Product.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.time.*; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class Product { 7 | 8 | private int id; 9 | private String name; 10 | private String description; 11 | private double price; 12 | private int stock; 13 | private boolean shippingIncluded; 14 | private LocalDateTime disabledOn; 15 | private LocalDate disabledDate; 16 | private LocalTime disabledTime; 17 | private ZonedDateTime disabledOnZoned; 18 | 19 | private String dateFormat = "dd/MM/yyyy"; 20 | private String timeFormat = "HH:mm:ss"; 21 | private String dateTimeFormat = dateFormat + " "+timeFormat; 22 | 23 | public int getId() { 24 | return id; 25 | } 26 | public void setId(int id) { 27 | this.id = id; 28 | } 29 | public String getName() { 30 | return name; 31 | } 32 | public void setName(String name) { 33 | this.name = name; 34 | } 35 | public String getDescription() { 36 | return description; 37 | } 38 | public void setDescription(String description) { 39 | this.description = description; 40 | } 41 | public double getPrice() { 42 | return price; 43 | } 44 | public void setPrice(double price) { 45 | this.price = price; 46 | } 47 | public int getStock() { 48 | return stock; 49 | } 50 | public void setStock(int stock) { 51 | this.stock = stock; 52 | } 53 | public boolean isShippingIncluded() { 54 | return shippingIncluded; 55 | } 56 | public void setShippingIncluded(boolean shippingIncluded) { 57 | this.shippingIncluded = shippingIncluded; 58 | } 59 | public LocalDateTime getDisabledOn() { 60 | return disabledOn; 61 | } 62 | public void setDisabledOn(LocalDateTime disabledOn) { 63 | this.disabledOn = disabledOn; 64 | } 65 | public LocalDate getDisabledDate() { 66 | return disabledDate; 67 | } 68 | public void setDisabledDate(LocalDate disabledDate) { 69 | this.disabledDate = disabledDate; 70 | } 71 | public LocalTime getDisabledTime() { 72 | return disabledTime; 73 | } 74 | public void setDisabledTime(LocalTime disabledTime) { 75 | this.disabledTime = disabledTime; 76 | } 77 | public ZonedDateTime getDisabledOnZoned() { 78 | return disabledOnZoned; 79 | } 80 | public void setDisabledOnZoned(ZonedDateTime disabledOnZoned) { 81 | this.disabledOnZoned = disabledOnZoned; 82 | } 83 | @Override 84 | public String toString() { 85 | 86 | DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern(dateTimeFormat); 87 | DateTimeFormatter dFormat = DateTimeFormatter.ofPattern(dateFormat); 88 | DateTimeFormatter tFormat = DateTimeFormatter.ofPattern(timeFormat); 89 | 90 | return "Product [id=" + id + ", name=" + name + ", description=" + description 91 | + ", disabledOn=" + (disabledOn==null?null:disabledOn.format(dtFormat)) 92 | + ", disabledDate="+ (disabledDate==null?null:disabledDate.format(dFormat)) 93 | + ", disabledTime=" + (disabledTime==null?null:disabledTime.format(tFormat)) 94 | + ", disabledOnZoned=" + (disabledOnZoned==null?null:disabledOnZoned.format(dtFormat.withZone(ZoneId.of("UTC-3")))) 95 | + ", price=" + price + ", stock="+ stock + ", shippingIncluded=" + shippingIncluded 96 | + "]\n"; 97 | } 98 | 99 | 100 | 101 | } 102 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCTM/src/ui/Menu.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.time.*; 4 | import java.time.format.DateTimeFormatter; 5 | import java.util.Scanner; 6 | 7 | import data.DbHandler; 8 | import entities.Product; 9 | 10 | public class Menu { 11 | 12 | private Scanner scan; 13 | private DbHandler db=new DbHandler(); 14 | private String dateFormat = "dd/MM/yyyy"; 15 | private String timeFormat = "HH:mm:ss"; 16 | private String dateTimeFormat = dateFormat + " "+timeFormat; 17 | public void start() { 18 | 19 | 20 | scan = new Scanner(System.in); 21 | 22 | // muestran las opciones y según que elija el usuario 23 | String rta=""; 24 | 25 | do { 26 | rta=menu(); 27 | 28 | switch (rta) { 29 | case "list": 30 | list(); 31 | break; 32 | case "search": 33 | search(); 34 | break; 35 | case "new": 36 | newProduct(); 37 | break; 38 | case "delete": 39 | delete(); 40 | break; 41 | case "update": 42 | update(); 43 | break; 44 | case "exit": 45 | System.out.println("Sore ja, mata ne, byebye"); 46 | break; 47 | default: 48 | System.out.println("command not found...try again"); 49 | break; 50 | } 51 | 52 | } while (!rta.equals("exit")); 53 | 54 | scan.close(); 55 | 56 | } 57 | 58 | private void update() { 59 | Product updPrd = new Product(); 60 | System.out.print("Input the id of the product to be modified: "); 61 | updPrd.setId(Integer.parseInt(scan.nextLine())); 62 | 63 | System.out.println("Current data: "); 64 | System.out.println(db.search(updPrd)); 65 | 66 | loadData(updPrd); 67 | 68 | db.update(updPrd); 69 | 70 | } 71 | 72 | private void delete() { 73 | Product delPrd = new Product(); 74 | System.out.println("Current products:"); 75 | this.list(); 76 | System.out.print("Input the id of the product to be deleted: "); 77 | delPrd.setId(Integer.parseInt(scan.nextLine())); 78 | db.delete(delPrd); 79 | } 80 | 81 | private void newProduct() { 82 | Product newPrd= new Product(); 83 | 84 | System.out.println("Input new product data:"); 85 | 86 | loadData(newPrd); 87 | 88 | db.newProduct(newPrd); 89 | 90 | System.out.println("The new product's id is: " + newPrd.getId()); 91 | 92 | } 93 | 94 | private void loadData(Product prd) { 95 | System.out.print("Name: "); 96 | prd.setName(scan.nextLine()); 97 | 98 | System.out.print("Description: "); 99 | prd.setDescription(scan.nextLine()); 100 | 101 | System.out.print("Price: "); 102 | prd.setPrice(Double.parseDouble(scan.nextLine())); 103 | 104 | System.out.print("Stock: "); 105 | prd.setStock(Integer.parseInt(scan.nextLine())); 106 | 107 | System.out.print("Include Shipping? (Y/N): "); 108 | prd.setShippingIncluded(scan.nextLine().trim().equalsIgnoreCase("Y")); 109 | 110 | DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern(dateTimeFormat); 111 | System.out.print("Disabled On ("+dateTimeFormat+"): "); 112 | prd.setDisabledOn(LocalDateTime.parse(scan.nextLine(), dtFormat) ); 113 | 114 | DateTimeFormatter dFormat = DateTimeFormatter.ofPattern(dateFormat); 115 | System.out.print("Disabled Date ("+dateFormat+"): "); 116 | prd.setDisabledDate(LocalDate.parse(scan.nextLine(), dFormat) ); 117 | 118 | DateTimeFormatter tFormat = DateTimeFormatter.ofPattern(timeFormat); 119 | System.out.print("Disabled Time ("+timeFormat+"): "); 120 | prd.setDisabledTime(LocalTime.parse(scan.nextLine(), tFormat) ); 121 | 122 | System.out.print("Disabled On Zoned("+dateTimeFormat+"): "); 123 | prd.setDisabledOnZoned(ZonedDateTime.parse(scan.nextLine(), dtFormat.withZone(ZoneId.of("UTC-3"))) ); 124 | } 125 | 126 | private String menu() { 127 | 128 | System.out.println("Input command: list/search/new/delete/update/exit"); 129 | return scan.nextLine(); 130 | } 131 | 132 | private void list() { 133 | // for(Product p: db.list()) { 134 | // System.out.println(p); 135 | // } 136 | System.out.println(db.list()); 137 | } 138 | 139 | private void search() { 140 | Product p = new Product(); 141 | System.out.print("Input search id: "); 142 | p.setId(Integer.parseInt(scan.nextLine())); 143 | Product prod=db.search(p); 144 | if(prod!=null) { 145 | System.out.println(prod); 146 | }else { 147 | System.out.println("404 - Not found"); 148 | } 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6JDBCTM/src/ui/Principal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | public class Principal { 4 | 5 | 6 | public static void main(String[] args) { 7 | new Menu().start(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TNJDBC/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TNJDBC/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ejercicio6TNJDBC 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 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TNJDBC/lib/mysql-connector-java-8.0.25.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ejercicio6TNJDBC/lib/mysql-connector-java-8.0.25.jar -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TNJDBC/src/data/DbProduct.java: -------------------------------------------------------------------------------- 1 | package data; 2 | 3 | import java.sql.*; 4 | import java.time.*; 5 | import java.util.LinkedList; 6 | 7 | import entities.Product; 8 | 9 | public class DbProduct { 10 | 11 | private String driver="com.mysql.cj.jdbc.Driver"; 12 | private String host="localhost"; 13 | private String port="3306"; 14 | private String user="java"; 15 | private String password="himitsu"; 16 | private String db="javaMarket"; 17 | //private String options="?useLegacyDatetimeCode=false&serverTimezone=Asia/Hong_Kong"; 18 | private String options=""; 19 | private Connection conn=null; 20 | 21 | public DbProduct() { 22 | try { 23 | Class.forName(driver); 24 | } catch (ClassNotFoundException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | 29 | public Connection getConnection() { 30 | try { 31 | if(this.conn==null || this.conn.isClosed()) { 32 | this.conn=DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+db+options, user, password); 33 | } 34 | } catch (SQLException e) { 35 | e.printStackTrace(); 36 | } 37 | 38 | return this.conn; 39 | } 40 | 41 | public void releaseConnection() { 42 | try { 43 | if(this.conn!=null && !this.conn.isClosed()) { 44 | this.conn.close(); 45 | } 46 | } catch (SQLException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | 51 | public LinkedList list(){ 52 | ResultSet rs=null; 53 | Statement stmt=null; 54 | Connection conn=null; 55 | 56 | try { 57 | LinkedList prods = new LinkedList(); 58 | 59 | 60 | conn= this.getConnection(); 61 | stmt = conn.createStatement(); 62 | rs= stmt.executeQuery("select * from product"); 63 | 64 | if(rs!=null) { 65 | while(rs.next()) { 66 | Product prod = new Product(); 67 | prod.setId(rs.getInt("id")); 68 | prod.setName(rs.getString("name")); 69 | prod.setDescription(rs.getString("description")); 70 | prod.setPrice(rs.getDouble("price")); 71 | prod.setStock(rs.getInt("stock")); 72 | prod.setShippingIncluded(rs.getBoolean("shippingIncluded")); 73 | prod.setDisabledOn(rs.getObject("disabledOn",LocalDateTime.class)); 74 | prod.setDisabledDate(rs.getObject("disabledDate",LocalDate.class)); 75 | prod.setDisabledTime(rs.getObject("disabledTime",LocalTime.class)); 76 | prod.setDisabledOnZoned(rs.getObject("disabledOnZoned",ZonedDateTime.class)); 77 | prods.add(prod); 78 | } 79 | } 80 | return prods; 81 | } catch (SQLException e) { 82 | e.printStackTrace(); 83 | return null; 84 | } finally { 85 | try { 86 | if(rs!=null)rs.close(); 87 | if(stmt!=null)stmt.close(); 88 | this.releaseConnection(); 89 | } catch (SQLException e) { 90 | e.printStackTrace(); 91 | } 92 | } 93 | 94 | } 95 | 96 | public Product search(Product searchPrd) { 97 | 98 | ResultSet rs=null; 99 | PreparedStatement stmt=null; 100 | Connection conn=null; 101 | 102 | try { 103 | Product prod=null; 104 | conn= this.getConnection(); 105 | 106 | stmt=conn.prepareStatement("select * from product where id = ?"); 107 | stmt.setInt(1, searchPrd.getId()); 108 | 109 | rs=stmt.executeQuery(); 110 | 111 | if(rs!=null && rs.next()) { 112 | prod=new Product(); 113 | prod.setId(rs.getInt("id")); 114 | prod.setName(rs.getString("name")); 115 | prod.setDescription(rs.getString("description")); 116 | prod.setPrice(rs.getDouble("price")); 117 | prod.setStock(rs.getInt("stock")); 118 | prod.setShippingIncluded(rs.getBoolean("shippingIncluded")); 119 | prod.setDisabledOn(rs.getObject("disabledOn",LocalDateTime.class)); 120 | prod.setDisabledDate(rs.getObject("disabledDate",LocalDate.class)); 121 | prod.setDisabledTime(rs.getObject("disabledTime",LocalTime.class)); 122 | prod.setDisabledOnZoned(rs.getObject("disabledOnZoned",ZonedDateTime.class)); 123 | } 124 | return prod; 125 | 126 | } catch (SQLException e) { 127 | e.printStackTrace(); 128 | return null; 129 | } finally { 130 | try { 131 | if(rs!=null)rs.close(); 132 | if(stmt!=null)stmt.close(); 133 | this.releaseConnection(); 134 | } catch (SQLException e) { 135 | e.printStackTrace(); 136 | } 137 | } 138 | } 139 | 140 | public void newProduct(Product newPrd) { 141 | 142 | ResultSet keyRS=null; 143 | PreparedStatement stmt=null; 144 | Connection conn=null; 145 | 146 | try { 147 | conn= this.getConnection(); 148 | 149 | stmt=conn.prepareStatement( 150 | "insert into product(name, description, price, stock, shippingIncluded, disabledOn, disabledDate, disabledTime, disabledOnZoned) "+ 151 | "values(?,?,?,?,?,?,?,?,?)" 152 | ,Statement.RETURN_GENERATED_KEYS); 153 | 154 | stmt.setString(1, newPrd.getName()); 155 | stmt.setString(2, newPrd.getDescription()); 156 | stmt.setDouble(3, newPrd.getPrice()); 157 | stmt.setInt(4, newPrd.getStock()); 158 | stmt.setBoolean(5, newPrd.isShippingIncluded()); 159 | stmt.setObject(6, newPrd.getDisabledOn()); 160 | stmt.setObject(7, newPrd.getDisabledDate()); 161 | stmt.setObject(8, newPrd.getDisabledTime()); 162 | stmt.setObject(9, newPrd.getDisabledOnZoned()); 163 | 164 | stmt.executeUpdate(); 165 | 166 | keyRS=stmt.getGeneratedKeys(); 167 | 168 | if(keyRS!=null && keyRS.next()) { 169 | newPrd.setId(keyRS.getInt(1)); 170 | } 171 | 172 | } catch (SQLException e) { 173 | e.printStackTrace(); 174 | } finally { 175 | try { 176 | if(keyRS!=null)keyRS.close(); 177 | if(stmt!=null)stmt.close(); 178 | this.releaseConnection(); 179 | } catch (SQLException e) { 180 | e.printStackTrace(); 181 | } 182 | } 183 | } 184 | 185 | public void delete(Product delPrd) { 186 | PreparedStatement stmt=null; 187 | Connection conn=null; 188 | 189 | try { 190 | conn= this.getConnection(); 191 | 192 | stmt=conn.prepareStatement("delete from product where id =?"); 193 | 194 | stmt.setInt(1, delPrd.getId()); 195 | 196 | stmt.executeUpdate(); 197 | 198 | } catch (SQLException e) { 199 | e.printStackTrace(); 200 | } finally { 201 | try { 202 | if(stmt!=null)stmt.close(); 203 | this.releaseConnection(); 204 | } catch (SQLException e) { 205 | e.printStackTrace(); 206 | } 207 | } 208 | 209 | } 210 | 211 | public void update(Product updPrd) { 212 | PreparedStatement stmt=null; 213 | Connection conn=null; 214 | 215 | try { 216 | conn= this.getConnection(); 217 | 218 | stmt=conn.prepareStatement( 219 | "update product "+ 220 | "set name=?, description=?, price=?, stock=?, shippingIncluded=? "+ 221 | ", disabledOn=?, disabledDate=?, disabledTime=?, disabledOnZoned=? "+ 222 | "where id=?"); 223 | 224 | stmt.setString(1, updPrd.getName()); 225 | stmt.setString(2, updPrd.getDescription()); 226 | stmt.setDouble(3, updPrd.getPrice()); 227 | stmt.setInt(4, updPrd.getStock()); 228 | stmt.setBoolean(5, updPrd.isShippingIncluded()); 229 | stmt.setObject(6, updPrd.getDisabledOn()); 230 | stmt.setObject(7, updPrd.getDisabledDate()); 231 | stmt.setObject(8, updPrd.getDisabledTime()); 232 | stmt.setObject(9, updPrd.getDisabledOnZoned()); 233 | stmt.setInt(10, updPrd.getId()); 234 | 235 | stmt.executeUpdate(); 236 | 237 | } catch (SQLException e) { 238 | e.printStackTrace(); 239 | } finally { 240 | try { 241 | if(stmt!=null)stmt.close(); 242 | this.releaseConnection(); 243 | } catch (SQLException e) { 244 | e.printStackTrace(); 245 | } 246 | } 247 | 248 | } 249 | 250 | } 251 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TNJDBC/src/entities/Product.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.time.*; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class Product { 7 | 8 | private int id; 9 | private String name; 10 | private String description; 11 | private double price; 12 | private int stock; 13 | private boolean shippingIncluded; 14 | private LocalDateTime disabledOn; 15 | private LocalDate disabledDate; 16 | private LocalTime disabledTime; 17 | private ZonedDateTime disabledOnZoned; 18 | 19 | private String dateFormat="dd/MM/yyyy"; 20 | private String timeFormat="HH:mm:ss"; 21 | private String dateTimeFormat=dateFormat+" "+timeFormat; 22 | 23 | public int getId() { 24 | return id; 25 | } 26 | public void setId(int id) { 27 | this.id = id; 28 | } 29 | public String getName() { 30 | return name; 31 | } 32 | public void setName(String name) { 33 | this.name = name; 34 | } 35 | public String getDescription() { 36 | return description; 37 | } 38 | public void setDescription(String description) { 39 | this.description = description; 40 | } 41 | public double getPrice() { 42 | return price; 43 | } 44 | public void setPrice(double price) { 45 | this.price = price; 46 | } 47 | public int getStock() { 48 | return stock; 49 | } 50 | public void setStock(int stock) { 51 | this.stock = stock; 52 | } 53 | public boolean isShippingIncluded() { 54 | return shippingIncluded; 55 | } 56 | public void setShippingIncluded(boolean shippingIncluded) { 57 | this.shippingIncluded = shippingIncluded; 58 | } 59 | public LocalDateTime getDisabledOn() { 60 | return disabledOn; 61 | } 62 | public void setDisabledOn(LocalDateTime disabledOn) { 63 | this.disabledOn = disabledOn; 64 | } 65 | public LocalDate getDisabledDate() { 66 | return disabledDate; 67 | } 68 | public void setDisabledDate(LocalDate disabledDate) { 69 | this.disabledDate = disabledDate; 70 | } 71 | public LocalTime getDisabledTime() { 72 | return disabledTime; 73 | } 74 | public void setDisabledTime(LocalTime disabledTime) { 75 | this.disabledTime = disabledTime; 76 | } 77 | public ZonedDateTime getDisabledOnZoned() { 78 | return disabledOnZoned; 79 | } 80 | public void setDisabledOnZoned(ZonedDateTime disabledOnZoned) { 81 | this.disabledOnZoned = disabledOnZoned; 82 | } 83 | @Override 84 | public String toString() { 85 | 86 | DateTimeFormatter dtFormat=DateTimeFormatter.ofPattern(dateTimeFormat) ; 87 | DateTimeFormatter dFormat=DateTimeFormatter.ofPattern(dateFormat) ; 88 | DateTimeFormatter tFormat=DateTimeFormatter.ofPattern(timeFormat) ; 89 | return "Product [id=" + id + ", name=" + name + ", description=" + description 90 | + ", disabledOn=" + (disabledOn==null?null:disabledOn.format(dtFormat)) 91 | + ", disabledOnZoned=" + (disabledOnZoned==null?null:disabledOnZoned.format(dtFormat.withZone(ZoneId.of("UTC-3")))) 92 | + ", disabledDate="+ (disabledDate==null?null:disabledDate.format(dFormat)) 93 | + ", disabledTime=" + (disabledTime==null?null:disabledTime.format(tFormat)) 94 | + ", price=" + price + ", stock="+ stock + ", shippingIncluded=" + shippingIncluded 95 | + "]\n"; 96 | } 97 | 98 | 99 | } 100 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TNJDBC/src/ui/Menu.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.time.format.DateTimeFormatter; 4 | import java.time.*; 5 | import java.util.LinkedList; 6 | import java.util.Scanner; 7 | 8 | import data.DbProduct; 9 | import entities.Product; 10 | 11 | public class Menu { 12 | 13 | Scanner scan = new Scanner(System.in); 14 | DbProduct db = new DbProduct(); 15 | 16 | private String dateFormat="dd/MM/yyyy"; 17 | private String timeFormat="HH:mm:ss"; 18 | private String dateTimeFormat=dateFormat+" "+timeFormat; 19 | 20 | public void start() { 21 | String rta=null; 22 | 23 | do { 24 | rta=inputCommand(); 25 | switch (rta) { 26 | case "list": 27 | list(); 28 | break; 29 | case "search": 30 | search(); 31 | break; 32 | case "new": 33 | newProduct(); 34 | break; 35 | case "update": 36 | update(); 37 | break; 38 | case "delete": 39 | delete(); 40 | break; 41 | case "exit": 42 | close(); 43 | break; 44 | default: 45 | System.out.println("Invalid command, try again"); 46 | break; 47 | } 48 | } while (!rta.equals("exit")); 49 | 50 | } 51 | 52 | private void update() { 53 | Product updPrd = new Product(); 54 | 55 | System.out.print("Input the id of the product to be modified: "); 56 | updPrd.setId(Integer.parseInt(scan.nextLine())); 57 | System.out.println(); 58 | System.out.println("Product's current data:"); 59 | System.out.println(db.search(updPrd)); 60 | System.out.println("Input new data:"); 61 | 62 | this.loadData(updPrd); 63 | 64 | db.update(updPrd); 65 | 66 | 67 | } 68 | 69 | private void delete() { 70 | Product delPrd = new Product(); 71 | 72 | System.out.println("Current products:"); 73 | list(); 74 | 75 | System.out.print("Input the id of the product to be deleted: "); 76 | delPrd.setId(Integer.parseInt(scan.nextLine())); 77 | 78 | db.delete(delPrd); 79 | 80 | } 81 | 82 | private void newProduct() { 83 | 84 | Product newPrd = new Product(); 85 | 86 | System.out.println("Insert new product data"); 87 | 88 | this.loadData(newPrd); 89 | 90 | db.newProduct(newPrd); 91 | 92 | System.out.println("Autogenerated id is: "+newPrd.getId()); 93 | } 94 | 95 | private void loadData(Product prd) { 96 | System.out.print("Name: "); 97 | prd.setName(scan.nextLine()); 98 | 99 | System.out.print("Description: "); 100 | prd.setDescription(scan.nextLine()); 101 | 102 | System.out.print("Price: "); 103 | prd.setPrice(Double.parseDouble(scan.nextLine())); 104 | 105 | System.out.print("Stock: "); 106 | prd.setStock(Integer.parseInt(scan.nextLine())); 107 | 108 | System.out.print("Includes shipping (Y/N): "); 109 | prd.setShippingIncluded(scan.nextLine().trim().equalsIgnoreCase("Y")); 110 | 111 | DateTimeFormatter dtFormat=DateTimeFormatter.ofPattern(dateTimeFormat) ; 112 | System.out.print("Disabled on :"); 113 | prd.setDisabledOn(LocalDateTime.parse(scan.nextLine(), dtFormat)); 114 | 115 | DateTimeFormatter dFormat=DateTimeFormatter.ofPattern(dateFormat) ; 116 | System.out.print("Disabled date :"); 117 | prd.setDisabledDate(LocalDate.parse(scan.nextLine(), dFormat)); 118 | 119 | DateTimeFormatter tFormat=DateTimeFormatter.ofPattern(timeFormat) ; 120 | System.out.print("Disabled time :"); 121 | prd.setDisabledTime(LocalTime.parse(scan.nextLine(), tFormat)); 122 | 123 | System.out.print("Disabled on zoned:"); 124 | prd.setDisabledOnZoned(ZonedDateTime.parse(scan.nextLine(), dtFormat.withZone(ZoneId.of("UTC-3")))); 125 | } 126 | 127 | private void search() { 128 | System.out.print("Input search id: "); 129 | Product searchPrd=new Product(); 130 | searchPrd.setId(Integer.parseInt(scan.nextLine())); 131 | Product completePrd=db.search(searchPrd); 132 | if(completePrd==null) { 133 | System.out.println("404 - Not found"); 134 | } else { 135 | System.out.println(completePrd); 136 | } 137 | 138 | } 139 | 140 | private void list() { 141 | System.out.println(db.list()); 142 | // LinkedList prods = db.list(); 143 | // for(Product p:prods) { 144 | // System.out.println(p); 145 | // } 146 | } 147 | 148 | private void close() { 149 | scan.close(); 150 | System.out.println("Sore ja, mata ne, byebye"); 151 | } 152 | 153 | private String inputCommand() { 154 | System.out.print("Please input command (list/search/new/update/delete/exit): "); 155 | return scan.nextLine(); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TNJDBC/src/ui/Principal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | public class Principal { 4 | 5 | public static void main(String[] args) { 6 | 7 | new Menu().start(); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TTJDBC/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TTJDBC/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ejercicio6TTJDBC 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 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TTJDBC/lib/mysql-connector-java-8.0.25.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/ejemplos/Ejercicio6TTJDBC/lib/mysql-connector-java-8.0.25.jar -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TTJDBC/src/entities/Product.java: -------------------------------------------------------------------------------- 1 | package entities; 2 | 3 | import java.time.*; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class Product { 7 | 8 | private String dateFormat ="dd/MM/yyyy"; 9 | private String timeFormat ="HH:mm:ss"; 10 | private String dateTimeFormat = dateFormat+" "+timeFormat; 11 | 12 | private int id; 13 | private String name; 14 | private String description; 15 | private Double price; 16 | private int stock; 17 | private boolean shippingIncluded; 18 | private LocalDateTime disabledOn; 19 | private LocalDate disabledDate; 20 | private LocalTime disabledTime; 21 | private ZonedDateTime disabledOnZoned; 22 | 23 | public int getId() { 24 | return id; 25 | } 26 | public void setId(int id) { 27 | this.id = id; 28 | } 29 | public String getName() { 30 | return name; 31 | } 32 | public void setName(String name) { 33 | this.name = name; 34 | } 35 | public String getDescription() { 36 | return description; 37 | } 38 | public void setDescription(String description) { 39 | this.description = description; 40 | } 41 | public Double getPrice() { 42 | return price; 43 | } 44 | public void setPrice(Double price) { 45 | this.price = price; 46 | } 47 | public int getStock() { 48 | return stock; 49 | } 50 | public void setStock(int stock) { 51 | this.stock = stock; 52 | } 53 | public boolean isShippingIncluded() { 54 | return shippingIncluded; 55 | } 56 | public void setShippingIncluded(boolean shippingIncluded) { 57 | this.shippingIncluded = shippingIncluded; 58 | } 59 | public LocalDateTime getDisabledOn() { 60 | return disabledOn; 61 | } 62 | public void setDisabledOn(LocalDateTime disabledOn) { 63 | this.disabledOn = disabledOn; 64 | } 65 | public LocalDate getDisabledDate() { 66 | return disabledDate; 67 | } 68 | public void setDisabledDate(LocalDate disabledDate) { 69 | this.disabledDate = disabledDate; 70 | } 71 | public LocalTime getDisabledTime() { 72 | return disabledTime; 73 | } 74 | public void setDisabledTime(LocalTime disabledTime) { 75 | this.disabledTime = disabledTime; 76 | } 77 | public ZonedDateTime getDisabledOnZoned() { 78 | return disabledOnZoned; 79 | } 80 | public void setDisabledOnZoned(ZonedDateTime disabledOnZoned) { 81 | this.disabledOnZoned = disabledOnZoned; 82 | } 83 | @Override 84 | public String toString() { 85 | DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern(dateTimeFormat); 86 | DateTimeFormatter dFormat = DateTimeFormatter.ofPattern(dateFormat); 87 | DateTimeFormatter tFormat = DateTimeFormatter.ofPattern(timeFormat); 88 | 89 | return "Product [id=" + id + ", name=" + name + ", description=" + description 90 | + ", disabledOn=" + (disabledOn==null?null:disabledOn.format(dtFormat)) 91 | + ", disabledOnZoned=" + (disabledOnZoned==null?null:disabledOnZoned.format(dtFormat.withZone(ZoneId.of("UTC-3")))) 92 | + ", disabledDate=" + (disabledDate==null?null:disabledDate.format(dFormat)) 93 | + ", disabledTime=" + (disabledTime==null?null:disabledTime.format(tFormat)) 94 | + ", price=" + price + ", stock="+ stock + ", shippingIncluded=" + shippingIncluded 95 | + "]\n"; 96 | } 97 | 98 | 99 | 100 | } 101 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TTJDBC/src/ui/Menu.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | import java.time.*; 4 | import java.time.format.DateTimeFormatter; 5 | import java.util.LinkedList; 6 | import java.util.Scanner; 7 | 8 | import data.DbProduct; 9 | import entities.Product; 10 | 11 | public class Menu { 12 | 13 | private String dateFormat ="dd/MM/yyyy"; 14 | private String timeFormat ="HH:mm:ss"; 15 | private String dateTimeFormat = dateFormat+" "+timeFormat; 16 | 17 | Scanner scan = new Scanner(System.in); 18 | DbProduct db= new DbProduct(); 19 | public void start() { 20 | String rta=null; 21 | do { 22 | rta=inputCommand(); 23 | switch (rta) { 24 | case "list": 25 | list(); 26 | break; 27 | case "search": 28 | search(); 29 | break; 30 | case "new": 31 | newProduct(); 32 | break; 33 | case "update": 34 | update(); 35 | break; 36 | case "delete": 37 | delete(); 38 | break; 39 | case "exit": 40 | close(); 41 | break; 42 | default: 43 | System.out.println("Invalid command try again."); 44 | break; 45 | } 46 | 47 | } while (!rta.equals("exit")); 48 | } 49 | 50 | private void update() { 51 | Product updPrd = new Product(); 52 | 53 | System.out.print("Input the if of the Product to be modified: "); 54 | updPrd.setId(Integer.parseInt(scan.nextLine())); 55 | System.out.println("Product "+ updPrd.getId() + " current data:"); 56 | System.out.println(db.search(updPrd)); 57 | System.out.println(); 58 | System.out.println(); 59 | this.loadData(updPrd); 60 | 61 | db.update(updPrd); 62 | 63 | System.out.println(); 64 | System.out.println(updPrd); 65 | } 66 | 67 | private void delete() { 68 | Product delPrd = new Product(); 69 | 70 | System.out.println("Current products:"); 71 | this.list(); 72 | System.out.println(); 73 | System.out.println(); 74 | System.out.print("Input to be deleted Product's id: "); 75 | 76 | delPrd.setId(Integer.parseInt(scan.nextLine())); 77 | 78 | db.delete(delPrd); 79 | } 80 | 81 | private void newProduct() { 82 | Product newPrd = new Product(); 83 | 84 | System.out.println("New product data: "); 85 | 86 | this.loadData(newPrd); 87 | 88 | db.newProduct(newPrd); 89 | 90 | System.out.print("Generated id: "); 91 | System.out.println(newPrd.getId()); 92 | } 93 | 94 | private void loadData(Product prd) { 95 | System.out.print("Name: "); 96 | prd.setName(scan.nextLine()); 97 | 98 | System.out.print("Description: "); 99 | prd.setDescription(scan.nextLine()); 100 | 101 | System.out.print("Price: "); 102 | prd.setPrice(Double.parseDouble(scan.nextLine())); 103 | 104 | System.out.print("Stock: "); 105 | prd.setStock(Integer.parseInt(scan.nextLine())); 106 | 107 | System.out.print("Is shipping included (Y/N): "); 108 | prd.setShippingIncluded(scan.nextLine().trim().equalsIgnoreCase("Y")); 109 | 110 | System.out.print("Disabled on: "); 111 | DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern(dateTimeFormat); 112 | prd.setDisabledOn(LocalDateTime.parse(scan.nextLine(),dtFormat)); 113 | 114 | System.out.print("Disabled date: "); 115 | DateTimeFormatter dFormat = DateTimeFormatter.ofPattern(dateFormat); 116 | prd.setDisabledDate(LocalDate.parse(scan.nextLine(),dFormat)); 117 | 118 | System.out.print("Disabled time: "); 119 | DateTimeFormatter tFormat = DateTimeFormatter.ofPattern(timeFormat); 120 | prd.setDisabledTime(LocalTime.parse(scan.nextLine(),tFormat)); 121 | 122 | System.out.print("Disabled on zoned: "); 123 | prd.setDisabledOnZoned(ZonedDateTime.parse(scan.nextLine(),dtFormat.withZone(ZoneId.of("UTC-3")))); 124 | } 125 | 126 | private String inputCommand() { 127 | System.out.println("Please insert the command (list/search/new/update/delete/exit):"); 128 | return scan.nextLine(); 129 | } 130 | 131 | private void list() { 132 | System.out.println(db.list()); 133 | // LinkedList prods = db.list(); 134 | // for(Product p: prods) { 135 | // System.out.println(p); 136 | // } 137 | } 138 | 139 | private void search() { 140 | System.out.print("Insert seach id: "); 141 | Product searchPrd = new Product(); 142 | searchPrd.setId(Integer.parseInt(scan.nextLine())); 143 | System.out.println(db.search(searchPrd)); 144 | } 145 | 146 | 147 | private void close() { 148 | scan.close(); 149 | System.out.println("Sore ja, mata ne, byebye"); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /ejemplos/Ejercicio6TTJDBC/src/ui/Principal.java: -------------------------------------------------------------------------------- 1 | package ui; 2 | 3 | public class Principal { 4 | 5 | public static void main(String[] args) { 6 | 7 | new Menu().start(); 8 | 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /ejemplos/RemoteSystemsTempFiles/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | RemoteSystemsTempFiles 4 | 5 | 6 | 7 | 8 | 9 | 10 | org.eclipse.rse.ui.remoteSystemsTempNature 11 | 12 | 13 | -------------------------------------------------------------------------------- /ejemplos/Servers2/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Servers2 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ejemplos/Servers2/apache-tomcat-10.0.13 at localhost-config/context.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | WEB-INF/web.xml 22 | WEB-INF/tomcat-web.xml 23 | ${catalina.base}/conf/web.xml 24 | 25 | 26 | 29 | -------------------------------------------------------------------------------- /ejemplos/Servers2/apache-tomcat-10.0.13 at localhost-config/server.xml: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 35 | 36 | 39 | 40 | 41 | 42 | 47 | 48 | 49 | 50 | 54 | 55 | 56 | 62 | 63 | 64 | 70 | 78 | 88 | 89 | 90 | 96 | 97 | 102 | 103 | 106 | 107 | 108 | 111 | 114 | 115 | 117 | 118 | 122 | 123 | 124 | 125 | 126 | 127 | 129 | 132 | 133 | 136 | 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /ejemplos/Servers2/apache-tomcat-10.0.13 at localhost-config/tomcat-users.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 34 | 38 | 45 | 52 | -------------------------------------------------------------------------------- /enunciados/README.md: -------------------------------------------------------------------------------- 1 | # Enunciados 2 | 3 | **Ejercicio 1** 4 | 5 | Mostrar por consola los 10 primeros números enteros y los 10 primeros números impares 6 | 7 | **Ejercicio 2** 8 | 9 | Leer 10 palabras y mostrarlas en orden inverso al que fueron ingresadas. 10 | 11 | **Ejercicio 3** 12 | 13 | Leer 10 palabras, luego leer una nueva palabra e indicar si la misma ya había sido ingresada en las 10 primeras. 14 | 15 | **Ejercicio 4** 16 | 17 | Leer un entero y luego una lista de 20 enteros. Guardar los mayores al número inicial y mostrarlos al final. Usar arrays, no otras colecciones. 18 | 19 | **Ejercicio 5a** 20 | 21 | ![Diagrama](./img/diagramaClases01.png) 22 | 23 | De acuerdo al diagrama de clases resolver: 24 | 25 | Cargar una lista de empleados (máximo 20) preguntado en cada uno si son administrativos o vendedores y cargar todos los datos respectivos. 26 | 27 | Luego listar los empleados indicando: dni, nombre, apellido y sueldo. 28 | El sueldo debe calcularse en el método getSueldo() de la siguiente forma: 29 | * Si es administrativo: sueldoBase \* ((hsExtra \* 1.5)+hsMes) / hsMes 30 | * Si es vendedor: sueldoBase + (porcenComision\*totalVtas/100) 31 | 32 | Restricciones 33 | * Utilizar un único array para almacenar a todos los empleados. No usar colecciones dinámicas. 34 | * Hacer uso de las ventajas de la programación orientada a objetos: herencia, redefinición y polimorfismo. 35 | * Las clases lógicas (las del diagrama) no pueden tener entrada o salida de datos por pantalla de ningún tipo. Esto debe ser realizado por otra clase que cree los objetos de las clases lógicas y les asigne los datos necesarios. 36 | 37 | **Ejercicio 5b** 38 | 39 | Resolver los ejercicios 4 y 5 usando LinkedList o ArrayList en lugar de Arrays. 40 | 41 | **Ejercicio 6a** 42 | 43 | Resolver: 44 | 1. Crear una clase Product que contenga los siguientes atributos: id:int, name:String, description:String, price:double, stock: int, shippingIncluded: boolean 45 | 2. Crear la base de datos javaMarket con la tabla Product para almacenar objetos de la clase Product con id autoincremental y los demás atributos según corresponda. 46 | 3. Cargar al menos 3 registros en la base de datos para realizar el desarrollo. 47 | 48 | Crear una app que se conecte a la DB y permita: 49 | 1. list. Listar todos los productos indicando: id, name y price. 50 | 2. search. Mostrar los datos completos de un Product. El usuario debe ingresar un id y la app debe mostrar todos los datos de ese articulo. 51 | 3. new. Cargar nuevos Products (sin id) e insertarlos en la tabla. Durante la inserción debe recuperar el id generado en la BD y mostrarlo al usuario (no puede realizar un nuevo select) 52 | 4. delete. Eliminar un Product. El usuario debe ingresar un id y la app debe eliminar el registro 53 | 5. update. Modificar un Product. El usuario debe ingresar un id y la app debe mostrar los datos actuales y preguntar los nuevos datos. Finalmente debe aplicar el cambio en la base de datos. 54 | 55 | Restricciones: 56 | * Todo el manejo de la base de datos debe hacerse en una clase que no sea el programa principal ni la clase Product. 57 | * La clase Product no puede contener código para leer o escribir datos de/a la interfaz, ni de o hacia la DB. 58 | * Cada operación debe realizarse en un método (puede invocar a otros si desea reusar el código). 59 | * Cada método solo puede recibir y/o devolver objetos Product o una colección (array, ArrayList, LinkedList, etc) de objetos Product. Por ejemplo el listar no necesita recibir nada y devuelve una colección de Product, el mostrar recibe un bbjeto Product con el id y devuelve uno completo. 60 | * El archivo .jar del conector a la DB debe ubicarse localmente en el proyecto. 61 | 62 | Sugerencias: 63 | * No preocuparse por validaciones. 64 | * Hacer un menu simple que itere y pregunte por las opciones requeridas (agregar una opción para salir) 65 | * Primero cree la clase lógica, luego el menú sin realizar acciones y finalmente desarrollar las acciones una a una por el orden indicado, ya que se han listado en orden de dificultad. 66 | 67 | **Ejercicio 6b** 68 | 69 | * Al ejercicio 6a en la clase Product agregar el atributo disabledOn:Date. 70 | * Realizar las modificaciones al ejercicio 6a para utilizar el nuevo atributo. 71 | * Crear dos métodos que se encarguen de abrir y cerrar las conexiones a la base de datos y utilizarlos desde los otros métodos. 72 | * Asegurarse de que todos los métodos liberen correctamente los recursos utilizados (cerrar resultsets, statements, conecciones). Esto incluye el manejo de errores con try catch finally. 73 | 74 | **Ejercicio 7** 75 | 76 | Completar el desarrolo del Ejemplo 5 de Acceso a Datos. 77 | Pueden encontrar el código en este [link](../ejemplos/Ej5AccesoADatos) 78 | 1. En primer lugar debe seguir estas [instrucciones](../ejemplos/Ej5AccesoADatos/src/steps.md) 79 | 2. Para ello usará los archivos del directorio [db](../ejemplos/Ej5AccesoADatos/db) para crear la base de datos y usuario para el ejercicio. 80 | 3. Luego debe completar la funcionalidad del ejercicio [planteada en el menú](../ejemplos/Ej5AccesoADatos/src/ui/Menu.java) con los comandos 81 | * search 82 | * new 83 | * edit 84 | * delete 85 | 4. Los comandos deben cumplir con la descripción indicada en el método getCommand() de la clase Menu.java 86 | 5. Algunos como new se encuentran parcialmente implementados. Se recomienda seguir ese orden ya que la dificultad es incremental. 87 | 6. Deben enfocarse en el uso de capas y de acceso a base de datos, no es necesario hacer validaciones de entrada de datos ni enfocarse en la estética de la entrada o salida de datos. 88 | 7. Para más información sobre el ejercicio consultar estos videos: 89 | * [recorrido del ejemplo](https://youtu.be/Rj65U8Vupjs) 90 | * [enunciado](https://youtu.be/QTO1kfTv92A) 91 | 8. Para una explicación más detallada de capas y jdbc pueden consultar los videos de esta lísta de reproducción: [jdbc](https://www.youtube.com/playlist?list=PLm49vB0eFOFHWj_wQzXNL1pmYaI3jt10E) 92 | 93 | 94 | -------------------------------------------------------------------------------- /enunciados/img/EsquemaCapas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/enunciados/img/EsquemaCapas.png -------------------------------------------------------------------------------- /enunciados/img/diagramaClases01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/utnfrrojava/javaClases/afdef22e038f62a3806889334355de6c4f840909/enunciados/img/diagramaClases01.png --------------------------------------------------------------------------------