commit 22c343fda3453026648340d77fb695535adafaa4 Author: gonzalo.diaz18 Date: Mon Nov 9 23:26:49 2026 +0100 Simulación Examen Red Metro diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..040b572 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Eclipse +.classpath +.project +.settings/ + +# Compilación Java +bin/ +target/ +*.class + +# Logs +*.log + +# Sistema operativo +.DS_Store +Thumbs.db diff --git a/config/app.properties b/config/app.properties new file mode 100644 index 0000000..e1a1777 --- /dev/null +++ b/config/app.properties @@ -0,0 +1,8 @@ +db.url=jdbc:mysql://192.168.1.41:3306/redmetro +db.usuario=root +db.password=1234 +fichero.cocheras=ficheros/operaciones-cocherasRM.csv +fichero.codificacion=UTF-8 +cocheras.separador=; +fichero.trenes.entrada=ficheros/trenes_estaciones_accesos.xml +fichero.trenes.salida=ficheros/red_metro_gdo.xml \ No newline at end of file diff --git a/ficheros/operaciones-cocherasRM.csv b/ficheros/operaciones-cocherasRM.csv new file mode 100644 index 0000000..53db8c0 --- /dev/null +++ b/ficheros/operaciones-cocherasRM.csv @@ -0,0 +1,31 @@ +OPERACION;COD_COCHERA;DEPOSITO;DENOMINACION;LOCALIZACION +1;1;1;PUEEEEEEEEEEERTA DE ARGANDA;CARRETERA M-203 KM 2,300 (CAMINO DE VALLECAS A MEJORADA) +1;2;1;UNIVERSIDAD REY JUAN CARLOS;AVENIDA ALCALDE DE MÓSTOLES Nº 35 +1;3;1;EL BERCIAL;PRÓXIMO A CARRETERA DE TURQUÍA (BARRIO DE EL BERCIAL) +1;4;1;ARGANZUELA - PLANETARIO;C/ BRONCE Nº 1 +1;5;1;CIUDAD UNIVERSITARIA;PLAZA RAMÓN Y CAJAL +1;6;1;MIGUEL HERNANDEZ;AVENIDA DE LA ALBUFERA ESQ. CALLE RAFAEL ALBERTI +0;7;1;ARGÜELLES;C/ PRINCESA Nº 56 +1;8;1;ALMENDRALES;AVENIDA DE CÓRDOBA, 21 +1;9;1;MONCLOA;C/ PRINCESA, 96 +1;10;1;NUEVOS MINISTERIOS;PASEO DE LA CASTELLANA Nº 67 +0;11;0;CUATRO CAMINOS;VIRGEN DE NIEVA S/N +1;12;0;VENTAS;ALMERÍA 6 +1;13;0;PLAZA DE CASTILLA;SAN BENITO S/N +1;14;0;CANILLEJAS;NECTAR S/N +1;15;0;ALUCHE;AVDA. DE LOS POBLADOS Nº 11 +1;16;0;FUENCARRAL;AVENIDA CAMPO DE CALATRAVA Nº 86 +0;17;0;SACEDAL;VENTISQUERO DE LA CONDESA S/N +1;18;0;LAGUNA;GOTAREDURA Nº 3 +1;19;0;HORTALEZA;C/ MANUEL AZAÑA +1;20;0;CUATRO VIENTOS CUATRO;CRTA. DE CANALEJAS y DE QUIEN LO MATO S/N +1;21;0;LORANCA;AVDA. DE LA ALEGRÍA (FUENLABRADA) +1;22;0;VALDECARROS;AVENIDA CERRO MILANO 0103 ENSANCHE DE VALLECAS, 73 +1;23;0;VILLAVERDE;AVENIDA REAL DE PINTO +2;1;1;PUERTA DE ARGANDA;CARRETERA M-203 KM 2,300 (CAMINO DE VALLECAS A MEJORADA) +0;14;0;CANILLEJAS;NECTAR S/N +0;15;0;ALUCHE;AVDA. DE LOS POBLADOS Nº 11 +0;16;0;FUENCARRAL;AVENIDA CAMPO DE CALATRAVA Nº 86 +0;17;0;SACEDAL;VENTISQUERO DE LA CONDESA S/N +0;18;0;LAGUNA;GOTAREDURA Nº 3 +3;13;0;PLAZA DE CASTILLA;SAN BENITO S/N \ No newline at end of file diff --git a/ficheros/red_metro_gdo.xml b/ficheros/red_metro_gdo.xml new file mode 100644 index 0000000..c42e6b1 --- /dev/null +++ b/ficheros/red_metro_gdo.xml @@ -0,0 +1,52 @@ + + + + Serie 2000-A + 2000 + CAF + 15 + + Arguelles - Pinar de Chamartín + + Marrón + + + + + Serie 2000-B + 2005 + CAF + 15 + + Arguelles - Pinar de Chamartín + + Marrón + + + + + Serie 3000 + 2010 + CAF + 15 + + Arguelles - Pinar de Chamartín + + Marrón + + + + + Serie 5000 + 2010 + CAF + 1 + + Nuevos Ministerios - Aeropuerto + + Rosa + + + + + diff --git a/ficheros/trenes_estaciones_accesos.xml b/ficheros/trenes_estaciones_accesos.xml new file mode 100644 index 0000000..f2a6ed0 --- /dev/null +++ b/ficheros/trenes_estaciones_accesos.xml @@ -0,0 +1,107 @@ + + + + + + Serie 2000-A + 2000 + CAF + 15 + 5 + + + Serie 2000-B + 2005 + CAF + 15 + 5 + + + Serie 3000 + 2010 + CAF + 15 + 5 + + + Serie 5000 + 2010 + CAF + 1 + 9 + + + + + + + + Alameda de Osuna + C/ de la Corbeta,14 + + + Corbeta: C/ de la Corbeta,14 (esquina calle de La Rioja) + 0 + + + Ascensor: C/ de la Corbeta,14 (esquina calle de La Rioja) + 1 + + + + + Pueblo Nuevo + C/. Alcalá, 373 + + + Hermanos de Pablo: Alcalá, 373 (próx. Hnos. de Pablo) + 0 + + + Emilio Ferrari: Alcalá, 364 + 0 + + + Ascensor: Alcalá, 366 + 1 + + + + + Avenida de América + Avenida de América nº 25 + + + Intercambiador: Avenida de América frente al nº 25 + 1 + + + Pedro Valdivia: Pedro Valdivia, 31 (Francisco Silvela - Príncipe de Vergara) + 0 + + + + + Núñez de Balboa + C/. Núñez de Balboa, 85 + + + Núñez de Balboa: Núñez de Balboa, 85 (Esq. Juan Bravo, 13) + 1 + + + Velázquez: Velázquez, 92 (Esq. Juan Bravo, 11) + 0 + + + Aparcamiento: Aparcamiento Pza. Marqués de Salamanca (Sólo entrada) + 1 + + + Pza. Marqués de Salamanca: Pza. Marqués de Salamanca, 10 + 0 + + + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..2185d3b --- /dev/null +++ b/pom.xml @@ -0,0 +1,27 @@ + + 4.0.0 + RedMetroGDO + RedMetroGDO + 0.0.1-SNAPSHOT + + + + com.mysql + mysql-connector-j + 26.10.0 + compile + + + + src + + + maven-compiler-plugin + 3.13.0 + + 21 + + + + + \ No newline at end of file diff --git a/src/es/madrid/redmetro/gdo/Main.java b/src/es/madrid/redmetro/gdo/Main.java new file mode 100644 index 0000000..a45b06d --- /dev/null +++ b/src/es/madrid/redmetro/gdo/Main.java @@ -0,0 +1,59 @@ +package es.madrid.redmetro.gdo; + +import java.util.Scanner; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.service.CocheraService; +import es.madrid.redmetro.gdo.service.LineaService; +import es.madrid.redmetro.gdo.service.TrenService; + +public class Main { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.println("Introduzca la operación a realizar:"); + String opcion = sc.nextLine().trim().toUpperCase(); + + try { + switch (opcion) { + case "A": + // Pedimos el id de la linea y mostramos su color + System.out.println("Introduzca el identificador de la línea:"); + int idLinea = Integer.parseInt(sc.nextLine().trim()); + LineaService lineaService = new LineaService(); + System.out.println(lineaService.obtenerInformacionColor(idLinea)); + break; + case "B": + // Tratamos el fichero de cocheras + CocheraService cocheraService = new CocheraService(); + cocheraService.tratarFicheroCocheras(); + System.out.println("Fichero de cocheras tratado correctamente"); + break; + case "C": + // Insertamos en la BBDD los trenes del XML + TrenService trenServiceC = new TrenService(); + trenServiceC.cargarTrenesDesdeXML(); + System.out.println("Fichero de trenes cargado correctamente"); + break; + case "D": + // Guardamos en un XML todos los trenes de la BBDD + TrenService trenServiceD = new TrenService(); + trenServiceD.exportarTrenesAXML(); + break; + default: + System.out.println("Operación no válida"); + } + } catch (NumberFormatException e) { + System.out.println("El identificador debe ser un número"); + } catch (RedMetroException e) { + // Mostramos el mensaje y la causa si la hay + System.out.println("Error: " + e.getMessage()); + if (e.getCause() != null) { + System.out.println("Causa: " + e.getCause().getMessage()); + } + } finally { + sc.close(); + } + } +} diff --git a/src/es/madrid/redmetro/gdo/dao/ICocheraDAO.java b/src/es/madrid/redmetro/gdo/dao/ICocheraDAO.java new file mode 100644 index 0000000..11f6e04 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/ICocheraDAO.java @@ -0,0 +1,15 @@ +package es.madrid.redmetro.gdo.dao; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.model.Cochera; + +public interface ICocheraDAO { + + boolean existe(int codigoCochera) throws RedMetroException; + + void insertar(Cochera cochera) throws RedMetroException; + + void modificar(Cochera cochera) throws RedMetroException; + + void borrar(int codigoCochera) throws RedMetroException; +} diff --git a/src/es/madrid/redmetro/gdo/dao/IColorDAO.java b/src/es/madrid/redmetro/gdo/dao/IColorDAO.java new file mode 100644 index 0000000..4e20f94 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/IColorDAO.java @@ -0,0 +1,10 @@ +package es.madrid.redmetro.gdo.dao; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.model.Color; + +public interface IColorDAO { + + // Devuelve el color o null si no existe + Color obtenerPorId(int codigoColor) throws RedMetroException; +} diff --git a/src/es/madrid/redmetro/gdo/dao/ILineaDAO.java b/src/es/madrid/redmetro/gdo/dao/ILineaDAO.java new file mode 100644 index 0000000..2c67dc4 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/ILineaDAO.java @@ -0,0 +1,10 @@ +package es.madrid.redmetro.gdo.dao; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.model.Linea; + +public interface ILineaDAO { + + // Devuelve la linea con su color o null si no existe + Linea obtenerPorId(int codigoLinea) throws RedMetroException; +} diff --git a/src/es/madrid/redmetro/gdo/dao/ITrenDAO.java b/src/es/madrid/redmetro/gdo/dao/ITrenDAO.java new file mode 100644 index 0000000..cf0de1b --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/ITrenDAO.java @@ -0,0 +1,16 @@ +package es.madrid.redmetro.gdo.dao; + +import java.util.List; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.model.Tren; + +public interface ITrenDAO { + + boolean existe(int codigoTren) throws RedMetroException; + + void insertar(Tren tren) throws RedMetroException; + + // Devuelve todos los trenes con su linea y el color de la linea + List obtenerTodos() throws RedMetroException; +} diff --git a/src/es/madrid/redmetro/gdo/dao/impl/CocheraDaoJDBC.java b/src/es/madrid/redmetro/gdo/dao/impl/CocheraDaoJDBC.java new file mode 100644 index 0000000..e32a5e3 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/impl/CocheraDaoJDBC.java @@ -0,0 +1,81 @@ +package es.madrid.redmetro.gdo.dao.impl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import es.madrid.redmetro.gdo.dao.ICocheraDAO; +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.gestores.GestorConexion; +import es.madrid.redmetro.gdo.model.Cochera; + +public class CocheraDaoJDBC implements ICocheraDAO { + + private static final String SQL_EXISTE = + "SELECT COUNT(*) FROM T_COCHERA WHERE cod_cochera = ?"; + private static final String SQL_INSERTAR = + "INSERT INTO T_COCHERA (cod_cochera, nombre, direccion, deposito) VALUES (?, ?, ?, ?)"; + private static final String SQL_MODIFICAR = + "UPDATE T_COCHERA SET nombre = ?, direccion = ?, deposito = ? WHERE cod_cochera = ?"; + private static final String SQL_BORRAR = + "DELETE FROM T_COCHERA WHERE cod_cochera = ?"; + + // Comprueba si la cochera ya esta en la base de datos + @Override + public boolean existe(int codigoCochera) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_EXISTE)) { + + ps.setInt(1, codigoCochera); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + return rs.getInt(1) > 0; + } + } catch (SQLException e) { + throw new RedMetroException("Error al comprobar la cochera " + codigoCochera, e); + } + } + + @Override + public void insertar(Cochera cochera) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_INSERTAR)) { + + ps.setInt(1, cochera.getCodigoCochera()); + ps.setString(2, cochera.getNombre()); + ps.setString(3, cochera.getDireccion()); + ps.setInt(4, cochera.getDeposito()); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RedMetroException("Error al insertar la cochera " + cochera.getCodigoCochera(), e); + } + } + + @Override + public void modificar(Cochera cochera) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_MODIFICAR)) { + + ps.setString(1, cochera.getNombre()); + ps.setString(2, cochera.getDireccion()); + ps.setInt(3, cochera.getDeposito()); + ps.setInt(4, cochera.getCodigoCochera()); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RedMetroException("Error al modificar la cochera " + cochera.getCodigoCochera(), e); + } + } + + @Override + public void borrar(int codigoCochera) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_BORRAR)) { + + ps.setInt(1, codigoCochera); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RedMetroException("Error al borrar la cochera " + codigoCochera, e); + } + } +} diff --git a/src/es/madrid/redmetro/gdo/dao/impl/ColorDaoJDBC.java b/src/es/madrid/redmetro/gdo/dao/impl/ColorDaoJDBC.java new file mode 100644 index 0000000..0c4bdc5 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/impl/ColorDaoJDBC.java @@ -0,0 +1,40 @@ +package es.madrid.redmetro.gdo.dao.impl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import es.madrid.redmetro.gdo.dao.IColorDAO; +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.gestores.GestorConexion; +import es.madrid.redmetro.gdo.model.Color; + +public class ColorDaoJDBC implements IColorDAO { + + private static final String SQL_POR_ID = + "SELECT cod_color, nombre, cod_hexadecimal FROM T_COLOR WHERE cod_color = ?"; + + @Override + public Color obtenerPorId(int codigoColor) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_POR_ID)) { + + ps.setInt(1, codigoColor); + + try (ResultSet rs = ps.executeQuery()) { + // Si existe montamos el color con los setters + if (rs.next()) { + Color color = new Color(); + color.setCodigoColor(rs.getInt("cod_color")); + color.setNombre(rs.getString("nombre")); + color.setCodigoHexadecimal(rs.getString("cod_hexadecimal")); + return color; + } + return null; + } + } catch (SQLException e) { + throw new RedMetroException("Error al consultar el color " + codigoColor, e); + } + } +} diff --git a/src/es/madrid/redmetro/gdo/dao/impl/LineaDaoJDBC.java b/src/es/madrid/redmetro/gdo/dao/impl/LineaDaoJDBC.java new file mode 100644 index 0000000..16fd327 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/impl/LineaDaoJDBC.java @@ -0,0 +1,47 @@ +package es.madrid.redmetro.gdo.dao.impl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import es.madrid.redmetro.gdo.dao.IColorDAO; +import es.madrid.redmetro.gdo.dao.ILineaDAO; +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.gestores.GestorConexion; +import es.madrid.redmetro.gdo.model.Linea; + +public class LineaDaoJDBC implements ILineaDAO { + + private static final String SQL_POR_ID = + "SELECT cod_linea, nombre_corto, nombre_largo, cod_color, kilometros " + + "FROM T_LINEA WHERE cod_linea = ?"; + + // El color de la linea lo pedimos al DAO de colores + private IColorDAO colorDao = new ColorDaoJDBC(); + + @Override + public Linea obtenerPorId(int codigoLinea) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_POR_ID)) { + + ps.setInt(1, codigoLinea); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + Linea linea = new Linea(); + linea.setCodigoLinea(rs.getInt("cod_linea")); + linea.setNombreCorto(rs.getString("nombre_corto")); + linea.setNombreLargo(rs.getString("nombre_largo")); + linea.setKilometros(rs.getFloat("kilometros")); + // Buscamos el color a partir de su codigo + linea.setColor(colorDao.obtenerPorId(rs.getInt("cod_color"))); + return linea; + } + return null; + } + } catch (SQLException e) { + throw new RedMetroException("Error al consultar la linea " + codigoLinea, e); + } + } +} diff --git a/src/es/madrid/redmetro/gdo/dao/impl/TrenDaoJDBC.java b/src/es/madrid/redmetro/gdo/dao/impl/TrenDaoJDBC.java new file mode 100644 index 0000000..17e8929 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/dao/impl/TrenDaoJDBC.java @@ -0,0 +1,107 @@ +package es.madrid.redmetro.gdo.dao.impl; + +import java.sql.Connection; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + +import es.madrid.redmetro.gdo.dao.ILineaDAO; +import es.madrid.redmetro.gdo.dao.ITrenDAO; +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.gestores.GestorConexion; +import es.madrid.redmetro.gdo.model.Cochera; +import es.madrid.redmetro.gdo.model.Tren; + +public class TrenDaoJDBC implements ITrenDAO { + + private static final String SQL_EXISTE = + "SELECT COUNT(*) FROM T_TREN WHERE cod_tren = ?"; + private static final String SQL_INSERTAR = + "INSERT INTO T_TREN (cod_tren, modelo, empresa_constructora, fecha_incorporacion, " + + "cod_cochera, cod_linea) VALUES (?, ?, ?, ?, ?, ?)"; + private static final String SQL_TODOS = + "SELECT cod_tren, modelo, empresa_constructora, fecha_incorporacion, cod_cochera, cod_linea " + + "FROM T_TREN ORDER BY cod_tren"; + + // La linea (y su color) de cada tren la pedimos al DAO de lineas + private ILineaDAO lineaDao = new LineaDaoJDBC(); + + @Override + public boolean existe(int codigoTren) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_EXISTE)) { + + ps.setInt(1, codigoTren); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + return rs.getInt(1) > 0; + } + } catch (SQLException e) { + throw new RedMetroException("Error al comprobar el tren " + codigoTren, e); + } + } + + @Override + public void insertar(Tren tren) throws RedMetroException { + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_INSERTAR)) { + + ps.setInt(1, tren.getCodigoTren()); + ps.setString(2, tren.getModelo()); + ps.setString(3, tren.getEmpresaConstructora()); + + // La fecha puede ser nula en la base de datos + if (tren.getFechaIncorporacion() != null) { + ps.setDate(4, Date.valueOf(tren.getFechaIncorporacion())); + } else { + ps.setNull(4, Types.DATE); + } + + ps.setInt(5, tren.getCochera().getCodigoCochera()); + ps.setInt(6, tren.getLinea().getCodigoLinea()); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RedMetroException("Error al insertar el tren " + tren.getCodigoTren(), e); + } + } + + @Override + public List obtenerTodos() throws RedMetroException { + List trenes = new ArrayList<>(); + + try (Connection con = GestorConexion.getConexion(); + PreparedStatement ps = con.prepareStatement(SQL_TODOS); + ResultSet rs = ps.executeQuery()) { + + while (rs.next()) { + Tren tren = new Tren(); + tren.setCodigoTren(rs.getInt("cod_tren")); + tren.setModelo(rs.getString("modelo")); + tren.setEmpresaConstructora(rs.getString("empresa_constructora")); + + // La fecha puede ser nula + Date fecha = rs.getDate("fecha_incorporacion"); + if (fecha != null) { + tren.setFechaIncorporacion(fecha.toLocalDate()); + } + + // De la cochera solo guardamos el codigo + Cochera cochera = new Cochera(); + cochera.setCodigoCochera(rs.getInt("cod_cochera")); + tren.setCochera(cochera); + + // Cargamos la linea con su color + tren.setLinea(lineaDao.obtenerPorId(rs.getInt("cod_linea"))); + + trenes.add(tren); + } + } catch (SQLException e) { + throw new RedMetroException("Error al obtener los trenes", e); + } + return trenes; + } +} diff --git a/src/es/madrid/redmetro/gdo/excepcion/RedMetroException.java b/src/es/madrid/redmetro/gdo/excepcion/RedMetroException.java new file mode 100644 index 0000000..7f21289 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/excepcion/RedMetroException.java @@ -0,0 +1,15 @@ +package es.madrid.redmetro.gdo.excepcion; + +// Unica excepcion de la aplicacion (checked) +public class RedMetroException extends Exception { + + private static final long serialVersionUID = 1L; + + public RedMetroException(String mensaje) { + super(mensaje); + } + + public RedMetroException(String mensaje, Throwable causa) { + super(mensaje, causa); + } +} \ No newline at end of file diff --git a/src/es/madrid/redmetro/gdo/ficheros/EscritorTrenesXML.java b/src/es/madrid/redmetro/gdo/ficheros/EscritorTrenesXML.java new file mode 100644 index 0000000..1ccadda --- /dev/null +++ b/src/es/madrid/redmetro/gdo/ficheros/EscritorTrenesXML.java @@ -0,0 +1,95 @@ +package es.madrid.redmetro.gdo.ficheros; + +import java.io.File; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.gestores.GestorConfiguracion; +import es.madrid.redmetro.gdo.model.Color; +import es.madrid.redmetro.gdo.model.Linea; +import es.madrid.redmetro.gdo.model.Tren; + +public class EscritorTrenesXML { + + // Genera el XML con los trenes, su linea y el color de la linea + public void escribirTrenes(List trenes) throws RedMetroException { + String ruta = GestorConfiguracion.getInstancia().getPropiedad("fichero.trenes.salida"); + + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = builder.newDocument(); + doc.setXmlStandalone(true); + + // Elemento raiz y + Element raiz = doc.createElement("info-trenes-linea-color"); + doc.appendChild(raiz); + Element elTrenes = doc.createElement("trenes"); + raiz.appendChild(elTrenes); + + for (Tren tren : trenes) { + Element elTren = doc.createElement("tren"); + elTren.setAttribute("id", String.valueOf(tren.getCodigoTren())); + + elTren.appendChild(crearElemento(doc, "modelo", tren.getModelo())); + + // Del campo fecha solo escribimos el anyo (si no hay fecha lo dejamos vacio) + String anyo = ""; + if (tren.getFechaIncorporacion() != null) { + anyo = String.valueOf(tren.getFechaIncorporacion().getYear()); + } + elTren.appendChild(crearElemento(doc, "anyo_incorporacion", anyo)); + + elTren.appendChild(crearElemento(doc, "empresa_constructora", tren.getEmpresaConstructora())); + elTren.appendChild(crearElemento(doc, "cod_cochera", + String.valueOf(tren.getCochera().getCodigoCochera()))); + + // Datos de la linea + Linea linea = tren.getLinea(); + Element elLinea = doc.createElement("linea"); + elLinea.setAttribute("id_linea", String.valueOf(linea.getCodigoLinea())); + elLinea.appendChild(crearElemento(doc, "nombre_l", linea.getNombreLargo())); + + // Datos del color de la linea + Color color = linea.getColor(); + Element elColor = doc.createElement("color"); + elColor.setAttribute("id", String.valueOf(color.getCodigoColor())); + elColor.setAttribute("cod_hex", color.getCodigoHexadecimal()); + elColor.appendChild(crearElemento(doc, "descripcion", color.getNombre())); + + elLinea.appendChild(elColor); + elTren.appendChild(elLinea); + elTrenes.appendChild(elTren); + } + + // Escribimos el documento en el fichero con sangrado + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); + transformer.transform(new DOMSource(doc), new StreamResult(new File(ruta))); + + } catch (ParserConfigurationException | TransformerException e) { + throw new RedMetroException("Error al generar el fichero XML de trenes", e); + } + } + + // Crea un elemento con texto dentro + private Element crearElemento(Document doc, String etiqueta, String texto) { + Element elemento = doc.createElement(etiqueta); + elemento.setTextContent(texto); + return elemento; + } +} diff --git a/src/es/madrid/redmetro/gdo/ficheros/LectorCocherasCSV.java b/src/es/madrid/redmetro/gdo/ficheros/LectorCocherasCSV.java new file mode 100644 index 0000000..93873f2 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/ficheros/LectorCocherasCSV.java @@ -0,0 +1,44 @@ +package es.madrid.redmetro.gdo.ficheros; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.gestores.GestorConfiguracion; + +public class LectorCocherasCSV { + + // Lee el CSV y devuelve cada linea separada en campos + public List leerCocheras() throws RedMetroException { + GestorConfiguracion config = GestorConfiguracion.getInstancia(); + String ruta = config.getPropiedad("fichero.cocheras"); + String separador = config.getPropiedad("cocheras.separador"); + Charset codificacion = Charset.forName(config.getPropiedad("fichero.codificacion")); + + List registros = new ArrayList<>(); + + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(ruta), codificacion))) { + + // La primera linea es la cabecera, la saltamos + br.readLine(); + + String linea; + while ((linea = br.readLine()) != null) { + // Ignoramos las lineas vacias + if (!linea.trim().isEmpty()) { + registros.add(linea.split(Pattern.quote(separador))); + } + } + } catch (IOException e) { + throw new RedMetroException("Error al leer el fichero de cocheras", e); + } + return registros; + } +} diff --git a/src/es/madrid/redmetro/gdo/ficheros/LectorTrenesXML.java b/src/es/madrid/redmetro/gdo/ficheros/LectorTrenesXML.java new file mode 100644 index 0000000..4c0e1e8 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/ficheros/LectorTrenesXML.java @@ -0,0 +1,72 @@ +package es.madrid.redmetro.gdo.ficheros; + +import java.io.File; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.gestores.GestorConfiguracion; +import es.madrid.redmetro.gdo.model.Cochera; +import es.madrid.redmetro.gdo.model.Linea; +import es.madrid.redmetro.gdo.model.Tren; + +public class LectorTrenesXML { + + // Lee el XML con DOM y devuelve solo la informacion de los trenes + public List leerTrenes() throws RedMetroException { + String ruta = GestorConfiguracion.getInstancia().getPropiedad("fichero.trenes.entrada"); + List trenes = new ArrayList<>(); + + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = builder.parse(new File(ruta)); + + // Cogemos todas las etiquetas + NodeList nodosTren = doc.getElementsByTagName("tren"); + + for (int i = 0; i < nodosTren.getLength(); i++) { + Element elTren = (Element) nodosTren.item(i); + + Tren tren = new Tren(); + tren.setCodigoTren(Integer.parseInt(elTren.getAttribute("id"))); + tren.setModelo(getTexto(elTren, "modelo")); + tren.setEmpresaConstructora(getTexto(elTren, "empresa_constructora")); + + // En el XML solo viene el anyo, asi que ponemos el 1 de enero de ese anyo + int anyo = Integer.parseInt(getTexto(elTren, "anyo_incorporacion")); + tren.setFechaIncorporacion(LocalDate.of(anyo, 1, 1)); + + // De la cochera solo necesitamos el codigo + Cochera cochera = new Cochera(); + cochera.setCodigoCochera(Integer.parseInt(getTexto(elTren, "cod_cochera"))); + tren.setCochera(cochera); + + // De la linea solo necesitamos el id + Linea linea = new Linea(); + linea.setCodigoLinea(Integer.parseInt(getTexto(elTren, "id_linea"))); + tren.setLinea(linea); + + trenes.add(tren); + } + } catch (ParserConfigurationException | SAXException | IOException | NumberFormatException e) { + throw new RedMetroException("Error al leer el fichero XML de trenes", e); + } + return trenes; + } + + // Devuelve el texto de una etiqueta hija + private String getTexto(Element padre, String etiqueta) { + return padre.getElementsByTagName(etiqueta).item(0).getTextContent().trim(); + } +} diff --git a/src/es/madrid/redmetro/gdo/gestores/GestorConexion.java b/src/es/madrid/redmetro/gdo/gestores/GestorConexion.java new file mode 100644 index 0000000..b927db8 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/gestores/GestorConexion.java @@ -0,0 +1,23 @@ +package es.madrid.redmetro.gdo.gestores; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; + +public class GestorConexion { + + // Abre una conexion con la base de datos usando los datos del properties + public static Connection getConexion() throws RedMetroException { + GestorConfiguracion config = GestorConfiguracion.getInstancia(); + try { + return DriverManager.getConnection( + config.getPropiedad("db.url"), + config.getPropiedad("db.usuario"), + config.getPropiedad("db.password")); + } catch (SQLException e) { + throw new RedMetroException("Error al conectar con la base de datos", e); + } + } +} diff --git a/src/es/madrid/redmetro/gdo/gestores/GestorConfiguracion.java b/src/es/madrid/redmetro/gdo/gestores/GestorConfiguracion.java new file mode 100644 index 0000000..133abce --- /dev/null +++ b/src/es/madrid/redmetro/gdo/gestores/GestorConfiguracion.java @@ -0,0 +1,43 @@ +package es.madrid.redmetro.gdo.gestores; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import es.madrid.redmetro.gdo.excepcion.RedMetroException; + +public class GestorConfiguracion { + + // Ruta del fichero de configuracion + private static final String RUTA_PROPERTIES = "config/app.properties"; + + private static GestorConfiguracion instancia; + private Properties propiedades; + + // Constructor privado: carga el fichero una sola vez + private GestorConfiguracion() throws RedMetroException { + propiedades = new Properties(); + try (FileInputStream fis = new FileInputStream(RUTA_PROPERTIES)) { + propiedades.load(fis); + } catch (IOException e) { + throw new RedMetroException("No se pudo leer el fichero de configuracion", e); + } + } + + // Devuelve siempre la misma instancia + public static GestorConfiguracion getInstancia() throws RedMetroException { + if (instancia == null) { + instancia = new GestorConfiguracion(); + } + return instancia; + } + + // Devuelve el valor de una propiedad o lanza error si no existe + public String getPropiedad(String clave) throws RedMetroException { + String valor = propiedades.getProperty(clave); + if (valor == null) { + throw new RedMetroException("Falta la propiedad " + clave + " en app.properties"); + } + return valor; + } +} diff --git a/src/es/madrid/redmetro/gdo/model/Cochera.java b/src/es/madrid/redmetro/gdo/model/Cochera.java new file mode 100644 index 0000000..23ae8aa --- /dev/null +++ b/src/es/madrid/redmetro/gdo/model/Cochera.java @@ -0,0 +1,48 @@ +package es.madrid.redmetro.gdo.model; + +public class Cochera { + + private int codigoCochera; + private String nombre; + private String direccion; + private int deposito; + + public int getCodigoCochera() { + return codigoCochera; + } + + public void setCodigoCochera(int codigoCochera) { + this.codigoCochera = codigoCochera; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getDireccion() { + return direccion; + } + + public void setDireccion(String direccion) { + this.direccion = direccion; + } + + public int getDeposito() { + return deposito; + } + + public void setDeposito(int deposito) { + this.deposito = deposito; + } + + @Override + public String toString() { + return "Cochera [codigoCochera=" + codigoCochera + ", nombre=" + nombre + ", direccion=" + direccion + + ", deposito=" + deposito + "]"; + } + +} diff --git a/src/es/madrid/redmetro/gdo/model/Color.java b/src/es/madrid/redmetro/gdo/model/Color.java new file mode 100644 index 0000000..3b268e8 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/model/Color.java @@ -0,0 +1,38 @@ +package es.madrid.redmetro.gdo.model; + +public class Color { + + private int codigoColor; + private String nombre; + private String codigoHexadecimal; + + public int getCodigoColor() { + return codigoColor; + } + + public void setCodigoColor(int codigoColor) { + this.codigoColor = codigoColor; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getCodigoHexadecimal() { + return codigoHexadecimal; + } + + public void setCodigoHexadecimal(String codigoHexadecimal) { + this.codigoHexadecimal = codigoHexadecimal; + } + + @Override + public String toString() { + return "Color [codigoColor=" + codigoColor + ", nombre=" + nombre + ", codigoHexadecimal=" + codigoHexadecimal + + "]"; + } +} diff --git a/src/es/madrid/redmetro/gdo/model/Linea.java b/src/es/madrid/redmetro/gdo/model/Linea.java new file mode 100644 index 0000000..5c59c97 --- /dev/null +++ b/src/es/madrid/redmetro/gdo/model/Linea.java @@ -0,0 +1,56 @@ +package es.madrid.redmetro.gdo.model; + +public class Linea { + + private int codigoLinea; + private String nombreCorto; + private String nombreLargo; + private Color color; + private float kilometros; + + public int getCodigoLinea() { + return codigoLinea; + } + + public void setCodigoLinea(int codigoLinea) { + this.codigoLinea = codigoLinea; + } + + public String getNombreCorto() { + return nombreCorto; + } + + public void setNombreCorto(String nombreCorto) { + this.nombreCorto = nombreCorto; + } + + public String getNombreLargo() { + return nombreLargo; + } + + public void setNombreLargo(String nombreLargo) { + this.nombreLargo = nombreLargo; + } + + public Color getColor() { + return color; + } + + public void setColor(Color color) { + this.color = color; + } + + public float getKilometros() { + return kilometros; + } + + public void setKilometros(float kilometros) { + this.kilometros = kilometros; + } + + @Override + public String toString() { + return "Linea [codigoLinea=" + codigoLinea + ", nombreCorto=" + nombreCorto + ", nombreLargo=" + nombreLargo + + ", color=" + color + ", kilometros=" + kilometros + "]"; + } +} diff --git a/src/es/madrid/redmetro/gdo/model/Tren.java b/src/es/madrid/redmetro/gdo/model/Tren.java new file mode 100644 index 0000000..75d8d9c --- /dev/null +++ b/src/es/madrid/redmetro/gdo/model/Tren.java @@ -0,0 +1,67 @@ +package es.madrid.redmetro.gdo.model; + +import java.time.LocalDate; + +public class Tren { + + private int codigoTren; + private String modelo; + private String empresaConstructora; + private LocalDate fechaIncorporacion; + private Cochera cochera; + private Linea linea; + + public int getCodigoTren() { + return codigoTren; + } + + public void setCodigoTren(int codigoTren) { + this.codigoTren = codigoTren; + } + + public String getModelo() { + return modelo; + } + + public void setModelo(String modelo) { + this.modelo = modelo; + } + + public String getEmpresaConstructora() { + return empresaConstructora; + } + + public void setEmpresaConstructora(String empresaConstructora) { + this.empresaConstructora = empresaConstructora; + } + + public LocalDate getFechaIncorporacion() { + return fechaIncorporacion; + } + + public void setFechaIncorporacion(LocalDate fechaIncorporacion) { + this.fechaIncorporacion = fechaIncorporacion; + } + + public Cochera getCochera() { + return cochera; + } + + public void setCochera(Cochera cochera) { + this.cochera = cochera; + } + + public Linea getLinea() { + return linea; + } + + public void setLinea(Linea linea) { + this.linea = linea; + } + + @Override + public String toString() { + return "Tren [codigoTren=" + codigoTren + ", modelo=" + modelo + ", empresaConstructora=" + empresaConstructora + + ", fechaIncorporacion=" + fechaIncorporacion + ", cochera=" + cochera + ", linea=" + linea + "]"; + } +} diff --git a/src/es/madrid/redmetro/gdo/service/CocheraService.java b/src/es/madrid/redmetro/gdo/service/CocheraService.java new file mode 100644 index 0000000..e5c76cd --- /dev/null +++ b/src/es/madrid/redmetro/gdo/service/CocheraService.java @@ -0,0 +1,62 @@ +package es.madrid.redmetro.gdo.service; + +import java.util.List; + +import es.madrid.redmetro.gdo.dao.ICocheraDAO; +import es.madrid.redmetro.gdo.dao.impl.CocheraDaoJDBC; +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.ficheros.LectorCocherasCSV; +import es.madrid.redmetro.gdo.model.Cochera; + +public class CocheraService { + + private ICocheraDAO cocheraDao = new CocheraDaoJDBC(); + private LectorCocherasCSV lector = new LectorCocherasCSV(); + + // Opcion B: trata el fichero de cocheras segun el codigo de operacion + public void tratarFicheroCocheras() throws RedMetroException { + List registros = lector.leerCocheras(); + + for (String[] campos : registros) { + try { + // Formato: operacion;cod_cochera;deposito;denominacion;localizacion + int operacion = Integer.parseInt(campos[0].trim()); + + Cochera cochera = new Cochera(); + cochera.setCodigoCochera(Integer.parseInt(campos[1].trim())); + cochera.setDeposito(Integer.parseInt(campos[2].trim())); + cochera.setNombre(campos[3].trim()); + cochera.setDireccion(campos[4].trim()); + + int cod = cochera.getCodigoCochera(); + + switch (operacion) { + case 0: + // No hacer nada + break; + case 1: + // Insertar solo si no existe + if (!cocheraDao.existe(cod)) { + cocheraDao.insertar(cochera); + System.out.println("Cochera " + cod + " insertada"); + } else { + System.out.println("La cochera " + cod + " ya existe, no se inserta"); + } + break; + case 2: + cocheraDao.modificar(cochera); + System.out.println("Cochera " + cod + " modificada"); + break; + case 3: + cocheraDao.borrar(cod); + System.out.println("Cochera " + cod + " borrada"); + break; + default: + throw new RedMetroException("Codigo de operacion no valido: " + operacion); + } + } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { + throw new RedMetroException("Linea del CSV con formato incorrecto", e); + } + } + } +} \ No newline at end of file diff --git a/src/es/madrid/redmetro/gdo/service/LineaService.java b/src/es/madrid/redmetro/gdo/service/LineaService.java new file mode 100644 index 0000000..147473d --- /dev/null +++ b/src/es/madrid/redmetro/gdo/service/LineaService.java @@ -0,0 +1,27 @@ +package es.madrid.redmetro.gdo.service; + +import es.madrid.redmetro.gdo.dao.ILineaDAO; +import es.madrid.redmetro.gdo.dao.impl.LineaDaoJDBC; +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.model.Color; +import es.madrid.redmetro.gdo.model.Linea; + +public class LineaService { + + private ILineaDAO lineaDao = new LineaDaoJDBC(); + + // Opcion A: devuelve el texto con la informacion del color de la linea + public String obtenerInformacionColor(int idLinea) throws RedMetroException { + Linea linea = lineaDao.obtenerPorId(idLinea); + + if (linea == null) { + throw new RedMetroException("No existe la linea " + idLinea); + } + + Color color = linea.getColor(); + return "El color de la Línea " + linea.getCodigoLinea() + " (" + linea.getNombreLargo() + + "), que tiene una longitud de " + linea.getKilometros() + + " Kilómetros, es " + color.getNombre() + + " (" + color.getCodigoHexadecimal() + ")."; + } +} diff --git a/src/es/madrid/redmetro/gdo/service/TrenService.java b/src/es/madrid/redmetro/gdo/service/TrenService.java new file mode 100644 index 0000000..f3d3f2c --- /dev/null +++ b/src/es/madrid/redmetro/gdo/service/TrenService.java @@ -0,0 +1,39 @@ +package es.madrid.redmetro.gdo.service; + +import java.util.List; + +import es.madrid.redmetro.gdo.dao.ITrenDAO; +import es.madrid.redmetro.gdo.dao.impl.TrenDaoJDBC; +import es.madrid.redmetro.gdo.excepcion.RedMetroException; +import es.madrid.redmetro.gdo.ficheros.EscritorTrenesXML; +import es.madrid.redmetro.gdo.ficheros.LectorTrenesXML; +import es.madrid.redmetro.gdo.model.Tren; + +public class TrenService { + + private ITrenDAO trenDao = new TrenDaoJDBC(); + private LectorTrenesXML lector = new LectorTrenesXML(); + private EscritorTrenesXML escritor = new EscritorTrenesXML(); + + // Opcion C: inserta en la base de datos los trenes del XML + public void cargarTrenesDesdeXML() throws RedMetroException { + List trenes = lector.leerTrenes(); + + for (Tren tren : trenes) { + // Si el tren ya esta en la base de datos no lo volvemos a insertar + if (!trenDao.existe(tren.getCodigoTren())) { + trenDao.insertar(tren); + System.out.println("Tren " + tren.getCodigoTren() + " insertado"); + } else { + System.out.println("El tren " + tren.getCodigoTren() + " ya existe, no se inserta"); + } + } + } + + // Opcion D: guarda en un XML la informacion de todos los trenes + public void exportarTrenesAXML() throws RedMetroException { + List trenes = trenDao.obtenerTodos(); + escritor.escribirTrenes(trenes); + System.out.println("Se han guardado " + trenes.size() + " trenes en el XML"); + } +}