This commit is contained in:
Avelino
2026-11-10 06:00:30 +01:00
commit ed438d8cfc
75 changed files with 1746 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry including="**/*.java" kind="src" output="target/classes" path="src">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>examen_simulacion</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
+14
View File
@@ -0,0 +1,14 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=17
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=17
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=17
+4
View File
@@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Conectores_02</groupId>
<artifactId>Conectores_02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- Conector de MySQL JDBC -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<!-- Cambia esto al número de la versión de Java que tengas instalada (ej: 17, 21, etc.) -->
<release>17</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
+106
View File
@@ -0,0 +1,106 @@
# Base de datos
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/red_metro_anp?useSSL=false&serverTimezone=Europe/Madrid&allowPublicKeyRetrieval=true
db.user=root
db.password=1234
# Ficheros
fichero.cocheras=ficheros/operaciones-cocherasRM.csv
fichero.trenes.entrada=ficheros/trenes_estaciones_accesos.xml
fichero.trenes.salida=ficheros/red_metro_anp.xml
csv.separador=;
# Mensajes
msg.operacion=Introduzca la operación a realizar
msg.linea.id=Introduzca el identificador de la línea
msg.operacion.invalida=Operación no válida
#SQL
sql.linea.porId=SELECT cod_linea, nombre_corto, nombre_largo, cod_color, kilometros FROM T_linea WHERE cod_linea = ?
sql.color.porId=SELECT cod_color, nombre, cod_hexadecimal FROM T_COLOR WHERE cod_color = ?
msg.linea.resultado=El color de la %s (%s), que tiene una longitud de %s kilómetros, es %s (%s).
msg.linea.noExiste=No existe ninguna línea con el identificador %s
msg.color.noExiste=No existe el color %s asociado a la línea
msg.linea.idInvalido=El identificador de línea debe ser un número entero
# CSV
csv.encoding=UTF-8
csv.columnas=5
# SQL cocheras
sql.cochera.porId=SELECT cod_cochera, nombre, direccion, deposito FROM T_COCHERA WHERE cod_cochera = ?
sql.cochera.insert=INSERT INTO T_COCHERA (cod_cochera, nombre, direccion, deposito) VALUES (?, ?, ?, ?)
sql.cochera.update=UPDATE T_COCHERA SET nombre = ?, direccion = ?, deposito = ? WHERE cod_cochera = ?
sql.cochera.delete=DELETE FROM T_COCHERA WHERE cod_cochera = ?
# Mensajes opción B
msg.csv.formato=Línea %d del fichero CSV incorrecta: se esperaban %d columnas y hay %d
msg.csv.numero=Línea %d del fichero CSV incorrecta: valor numérico no válido
msg.csv.lectura=Error al leer el fichero de cocheras
msg.cochera.insertada=Cochera %d insertada (%s)
msg.cochera.yaExiste=Cochera %d no insertada: ya existe en la base de datos
msg.cochera.modificada=Cochera %d modificada (%s)
msg.cochera.borrada=Cochera %d borrada
msg.cochera.noExiste=Cochera %d: no existe en la base de datos, operación %d no realizada
msg.cochera.opDesconocida=Cochera %d: código de operación %d desconocido, se ignora
msg.cochera.error=Cochera %d: error en la operación %d (%s)
# XML (etiquetas de entrada)
xml.trenes=trenes
xml.tren=tren
xml.tren.id=id
xml.tren.modelo=modelo
xml.tren.anyo=anyo_incorporacion
xml.tren.constructora=empresa_constructora
xml.tren.cochera=cod_cochera
xml.tren.linea=id_linea
# Fecha que se asigna al convertir el año de incorporación en DATE
tren.fecha.mes=1
tren.fecha.dia=1
# SQL trenes
sql.tren.porId=SELECT cod_tren, modelo, empresa_constructora, fecha_incorporacion, cod_cochera, cod_linea FROM T_TREN WHERE cod_tren = ?
sql.tren.insert=INSERT INTO T_TREN (cod_tren, modelo, empresa_constructora, fecha_incorporacion, cod_cochera, cod_linea) VALUES (?, ?, ?, ?, ?, ?)
# Mensajes opción C
msg.xml.lectura=Error al leer el fichero XML de trenes
msg.xml.sinTrenes=El fichero XML no contiene el nodo de trenes
msg.xml.etiqueta=Tren %s: falta la etiqueta <%s>
msg.xml.numero=Tren %s: valor numérico no válido en <%s>
msg.tren.insertado=Tren %d insertado (%s)
msg.tren.yaExiste=Tren %d no insertado: ya existe en la base de datos
msg.tren.sinCochera=Tren %d no insertado: no existe la cochera %d
msg.tren.sinLinea=Tren %d no insertado: no existe la línea %d
msg.tren.error=Tren %d: error al insertar (%s)
# XML de salida (etiquetas)
xmlout.raiz=info-trenes-linea-color
xmlout.trenes=trenes
xmlout.tren=tren
xmlout.tren.id=id
xmlout.modelo=modelo
xmlout.anyo=anyo_incorporacion
xmlout.constructora=empresa_contructora
xmlout.cochera=cod_cochera
xmlout.linea=linea
xmlout.linea.id=id_linea
xmlout.linea.nombre=nombre_1
xmlout.color=color
xmlout.color.id=id
xmlout.color.hex=cod_hex
xmlout.color.descripcion=descripcion
xmlout.encoding=UTF-8
xmlout.indentacion=2
# SQL
sql.tren.todos=SELECT cod_tren, modelo, empresa_constructora, fecha_incorporacion, cod_cochera, cod_linea FROM T_TREN ORDER BY cod_tren
# Mensajes opción D
msg.xmlout.escritura=Error al generar el fichero XML de salida
msg.xmlout.generado=Fichero %s generado con %d trenes
msg.xmlout.sinTrenes=No hay trenes en la base de datos, no se genera el fichero
msg.xmlout.incoherente=El tren %d referencia la línea %d o su color, que no existen
+31
View File
@@ -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
1 OPERACION COD_COCHERA DEPOSITO DENOMINACION LOCALIZACION
2 1 1 1 PUEEEEEEEEEEERTA DE ARGANDA CARRETERA M-203 KM 2,300 (CAMINO DE VALLECAS A MEJORADA)
3 1 2 1 UNIVERSIDAD REY JUAN CARLOS AVENIDA ALCALDE DE MÓSTOLES Nº 35
4 1 3 1 EL BERCIAL PRÓXIMO A CARRETERA DE TURQUÍA (BARRIO DE EL BERCIAL)
5 1 4 1 ARGANZUELA - PLANETARIO C/ BRONCE Nº 1
6 1 5 1 CIUDAD UNIVERSITARIA PLAZA RAMÓN Y CAJAL
7 1 6 1 MIGUEL HERNANDEZ AVENIDA DE LA ALBUFERA ESQ. CALLE RAFAEL ALBERTI
8 0 7 1 ARGÜELLES C/ PRINCESA Nº 56
9 1 8 1 ALMENDRALES AVENIDA DE CÓRDOBA, 21
10 1 9 1 MONCLOA C/ PRINCESA, 96
11 1 10 1 NUEVOS MINISTERIOS PASEO DE LA CASTELLANA Nº 67
12 0 11 0 CUATRO CAMINOS VIRGEN DE NIEVA S/N
13 1 12 0 VENTAS ALMERÍA 6
14 1 13 0 PLAZA DE CASTILLA SAN BENITO S/N
15 1 14 0 CANILLEJAS NECTAR S/N
16 1 15 0 ALUCHE AVDA. DE LOS POBLADOS Nº 11
17 1 16 0 FUENCARRAL AVENIDA CAMPO DE CALATRAVA Nº 86
18 0 17 0 SACEDAL VENTISQUERO DE LA CONDESA S/N
19 1 18 0 LAGUNA GOTAREDURA Nº 3
20 1 19 0 HORTALEZA C/ MANUEL AZAÑA
21 1 20 0 CUATRO VIENTOS CUATRO CRTA. DE CANALEJAS y DE QUIEN LO MATO S/N
22 1 21 0 LORANCA AVDA. DE LA ALEGRÍA (FUENLABRADA)
23 1 22 0 VALDECARROS AVENIDA CERRO MILANO 0103 ENSANCHE DE VALLECAS, 73
24 1 23 0 VILLAVERDE AVENIDA REAL DE PINTO
25 2 1 1 PUERTA DE ARGANDA CARRETERA M-203 KM 2,300 (CAMINO DE VALLECAS A MEJORADA)
26 0 14 0 CANILLEJAS NECTAR S/N
27 0 15 0 ALUCHE AVDA. DE LOS POBLADOS Nº 11
28 0 16 0 FUENCARRAL AVENIDA CAMPO DE CALATRAVA Nº 86
29 0 17 0 SACEDAL VENTISQUERO DE LA CONDESA S/N
30 0 18 0 LAGUNA GOTAREDURA Nº 3
31 3 13 0 PLAZA DE CASTILLA SAN BENITO S/N
+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?><info-trenes-linea-color>
<trenes>
<tren id="1">
<modelo>Serie 2000-A</modelo>
<anyo_incorporacion>2000</anyo_incorporacion>
<empresa_contructora>CAF</empresa_contructora>
<cod_cochera>15</cod_cochera>
<linea id_linea="5">
<nombre_1>Arguelles - Pinar de Chamartín</nombre_1>
<color cod_hex="#741013" id="4">
<descripcion>Marrón</descripcion>
</color>
</linea>
</tren>
<tren id="2">
<modelo>Serie 2000-B</modelo>
<anyo_incorporacion>2005</anyo_incorporacion>
<empresa_contructora>CAF</empresa_contructora>
<cod_cochera>15</cod_cochera>
<linea id_linea="5">
<nombre_1>Arguelles - Pinar de Chamartín</nombre_1>
<color cod_hex="#741013" id="4">
<descripcion>Marrón</descripcion>
</color>
</linea>
</tren>
<tren id="3">
<modelo>Serie 3000</modelo>
<anyo_incorporacion>2010</anyo_incorporacion>
<empresa_contructora>CAF</empresa_contructora>
<cod_cochera>15</cod_cochera>
<linea id_linea="5">
<nombre_1>Arguelles - Pinar de Chamartín</nombre_1>
<color cod_hex="#741013" id="4">
<descripcion>Marrón</descripcion>
</color>
</linea>
</tren>
<tren id="4">
<modelo>Serie 5000</modelo>
<anyo_incorporacion>2010</anyo_incorporacion>
<empresa_contructora>CAF</empresa_contructora>
<cod_cochera>1</cod_cochera>
<linea id_linea="9">
<nombre_1>Nuevos Ministerios - Aeropuerto</nombre_1>
<color cod_hex="#f5418e" id="8">
<descripcion>Rosa</descripcion>
</color>
</linea>
</tren>
</trenes>
</info-trenes-linea-color>
+107
View File
@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<info-trenes-estaciones-accesos>
<!-- Información trenes -->
<trenes>
<tren id="1">
<modelo>Serie 2000-A</modelo>
<anyo_incorporacion>2000</anyo_incorporacion>
<empresa_constructora>CAF</empresa_constructora>
<cod_cochera>15</cod_cochera>
<id_linea>5</id_linea>
</tren>
<tren id="2">
<modelo>Serie 2000-B</modelo>
<anyo_incorporacion>2005</anyo_incorporacion>
<empresa_constructora>CAF</empresa_constructora>
<cod_cochera>15</cod_cochera>
<id_linea>5</id_linea>
</tren>
<tren id="3">
<modelo>Serie 3000</modelo>
<anyo_incorporacion>2010</anyo_incorporacion>
<empresa_constructora>CAF</empresa_constructora>
<cod_cochera>15</cod_cochera>
<id_linea>5</id_linea>
</tren>
<tren id="4">
<modelo>Serie 5000</modelo>
<anyo_incorporacion>2010</anyo_incorporacion>
<empresa_constructora>CAF</empresa_constructora>
<cod_cochera>1</cod_cochera>
<id_linea>9</id_linea>
</tren>
</trenes>
<!-- Información estaciones -->
<estaciones>
<estacion id="1">
<nombre>Alameda de Osuna</nombre>
<direccion>C/ de la Corbeta,14</direccion>
<accesos>
<acceso id="1">
<nombre>Corbeta: C/ de la Corbeta,14 (esquina calle de La Rioja)</nombre>
<acceso_discapacidad>0</acceso_discapacidad>
</acceso>
<acceso id="2">
<nombre>Ascensor: C/ de la Corbeta,14 (esquina calle de La Rioja)</nombre>
<acceso_discapacidad>1</acceso_discapacidad>
</acceso>
</accesos>
</estacion>
<estacion id="2">
<nombre>Pueblo Nuevo</nombre>
<direccion>C/. Alcalá, 373</direccion>
<accesos>
<acceso id="3">
<nombre>Hermanos de Pablo: Alcalá, 373 (próx. Hnos. de Pablo)</nombre>
<acceso_discapacidad>0</acceso_discapacidad>
</acceso>
<acceso id="4">
<nombre>Emilio Ferrari: Alcalá, 364</nombre>
<acceso_discapacidad>0</acceso_discapacidad>
</acceso>
<acceso id="5">
<nombre>Ascensor: Alcalá, 366</nombre>
<acceso_discapacidad>1</acceso_discapacidad>
</acceso>
</accesos>
</estacion>
<estacion id="3">
<nombre>Avenida de América</nombre>
<direccion>Avenida de América nº 25</direccion>
<accesos>
<acceso id="6">
<nombre>Intercambiador: Avenida de América frente al nº 25</nombre>
<acceso_discapacidad>1</acceso_discapacidad>
</acceso>
<acceso id="7">
<nombre>Pedro Valdivia: Pedro Valdivia, 31 (Francisco Silvela - Príncipe de Vergara)</nombre>
<acceso_discapacidad>0</acceso_discapacidad>
</acceso>
</accesos>
</estacion>
<estacion id="4">
<nombre>Núñez de Balboa</nombre>
<direccion>C/. Núñez de Balboa, 85</direccion>
<accesos>
<acceso id="8">
<nombre>Núñez de Balboa: Núñez de Balboa, 85 (Esq. Juan Bravo, 13)</nombre>
<acceso_discapacidad>1</acceso_discapacidad>
</acceso>
<acceso id="9">
<nombre>Velázquez: Velázquez, 92 (Esq. Juan Bravo, 11)</nombre>
<acceso_discapacidad>0</acceso_discapacidad>
</acceso>
<acceso id="10">
<nombre>Aparcamiento: Aparcamiento Pza. Marqués de Salamanca (Sólo entrada)</nombre>
<acceso_discapacidad>1</acceso_discapacidad>
</acceso>
<acceso id="11">
<nombre>Pza. Marqués de Salamanca: Pza. Marqués de Salamanca, 10</nombre>
<acceso_discapacidad>0</acceso_discapacidad>
</acceso>
</accesos>
</estacion>
</estaciones>
</info-trenes-estaciones-accesos>
+29
View File
@@ -0,0 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Conectores_02</groupId>
<artifactId>Conectores_02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- Conector de MySQL JDBC -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<!-- Cambia esto al número de la versión de Java que tengas instalada (ej: 17, 21, etc.) -->
<release>17</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
+62
View File
@@ -0,0 +1,62 @@
package es.madrid.red.metro.anp;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;
import es.madrid.red.metro.anp.conexion.ConexionDB;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.service.CocheraService;
import es.madrid.red.metro.anp.service.LineaService;
import es.madrid.red.metro.anp.service.TrenService;
import es.madrid.red.metro.anp.service.impl.CocheraServiceImpl;
import es.madrid.red.metro.anp.service.impl.LineaServiceImpl;
import es.madrid.red.metro.anp.service.impl.TrenServiceImpl;
public class Main {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println(ConfigConexion.get("msg.operacion"));
String operacion = sc.nextLine().trim().toUpperCase();
if ("A".equals(operacion)) {
System.out.println(ConfigConexion.get("msg.linea.id"));
try {
int codLinea = Integer.parseInt(sc.nextLine().trim());
LineaService service = new LineaServiceImpl();
System.out.println(service.obtenerColorDeLinea(codLinea));
} catch (NumberFormatException e) {
System.out.println(ConfigConexion.get("msg.linea.idInvalido"));
}
} else if ("B".equals(operacion)) {
CocheraService service = new CocheraServiceImpl();
List<String> informe = service.procesarFicheroCocheras();
informe.forEach(System.out::println);
} else if ("C".equals(operacion)) {
TrenService service = new TrenServiceImpl();
service.cargarTrenesDesdeXML().forEach(System.out::println);
} else if ("D".equals(operacion)) {
TrenService service = new TrenServiceImpl();
System.out.println(service.exportarTrenesAXml());
} else {
System.out.println(ConfigConexion.get("msg.operacion.invalida"));
}
} catch (RedMetroException e) {
System.out.println(e.getMessage());
}
}
}
@@ -0,0 +1,26 @@
package es.madrid.red.metro.anp.conexion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import es.madrid.red.metro.anp.exception.RedMetroException;
public class ConexionDB {
private ConexionDB() {}
public static Connection getConexion() throws RedMetroException {
try {
Class.forName(ConfigConexion.get("db.driver"));
return DriverManager.getConnection(
ConfigConexion.get("db.url"),
ConfigConexion.get("db.user"),
ConfigConexion.get("db.password")
);
} catch (ClassNotFoundException | SQLException e) {
throw new RedMetroException("Error al conectar con la base de datos", e);
}
}
}
@@ -0,0 +1,30 @@
package es.madrid.red.metro.anp.conexion;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import es.madrid.red.metro.anp.exception.RedMetroException;
public class ConfigConexion {
private static final String RUTA_CONFIG = "ficheros/config.properties";
private static final Properties PROPS = new Properties();
static {
try (FileInputStream fis = new FileInputStream(RUTA_CONFIG)) {
PROPS.load(fis);
} catch (IOException e) {
throw new IllegalStateException("No se pudo leer" + RUTA_CONFIG, e);
}
}
private ConfigConexion() {}
public static String get(String clave) throws RedMetroException {
String valor = PROPS.getProperty(clave);
if (valor == null) {
throw new RedMetroException("Falta la propiedad: " + clave);
}
return valor;
}
}
@@ -0,0 +1,16 @@
package es.madrid.red.metro.anp.dao;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Cochera;
public interface CocheraDAO {
Cochera findById(int codCochera) throws RedMetroException;
void insert(Cochera cochera) throws RedMetroException;
boolean update(Cochera cochera) throws RedMetroException;
boolean delete(int codCochera) throws RedMetroException;
}
@@ -0,0 +1,11 @@
package es.madrid.red.metro.anp.dao;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Color;
public interface ColorDAO {
Color findById(int codColor) throws RedMetroException;
}
@@ -0,0 +1,10 @@
package es.madrid.red.metro.anp.dao;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Linea;
public interface LineaDAO {
Linea findById(int codLinea) throws RedMetroException;
}
@@ -0,0 +1,15 @@
package es.madrid.red.metro.anp.dao;
import java.util.List;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Tren;
public interface TrenDAO {
Tren findById(int codTren) throws RedMetroException;
void insert(Tren tren) throws RedMetroException;
List<Tren> findAll() throws RedMetroException;
}
@@ -0,0 +1,84 @@
package es.madrid.red.metro.anp.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import es.madrid.red.metro.anp.conexion.ConexionDB;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.dao.CocheraDAO;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Cochera;
public class CocheraDAOImpl implements CocheraDAO {
@Override
public Cochera findById(int codCochera) throws RedMetroException {
String sql = ConfigConexion.get("sql.cochera.porId");
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, codCochera);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
return new Cochera(rs.getInt("cod_cochera"), rs.getString("nombre"),
rs.getString("direccion"), rs.getInt("deposito"));
}
} catch (SQLException e) {
throw new RedMetroException("Error al consultar la cochera" + codCochera, e);
}
}
@Override
public void insert(Cochera c) throws RedMetroException {
String sql = ConfigConexion.get("sql.cochera.insert");
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, c.getCodCochera());
ps.setString(2, c.getNombre());
ps.setString(3, c.getDireccion());
ps.setInt(4, c.getDeposito());
ps.executeUpdate();
} catch (SQLException e) {
throw new RedMetroException("Error al insertar la cochera " + c.getCodCochera(), e);
}
}
@Override
public boolean update(Cochera c) throws RedMetroException {
String sql = ConfigConexion.get("sql.cochera.update");
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, c.getNombre());
ps.setString(2, c.getDireccion());
ps.setInt(3, c.getDeposito());
ps.setInt(4, c.getCodCochera());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new RedMetroException("Error al modificar la cochera " + c.getCodCochera(), e);
}
}
@Override
public boolean delete(int codCochera) throws RedMetroException {
String sql = ConfigConexion.get("sql.cochera.delete");
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, codCochera);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new RedMetroException("Error al borrar la cochera " + codCochera, e);
}
}
}
@@ -0,0 +1,37 @@
package es.madrid.red.metro.anp.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import es.madrid.red.metro.anp.conexion.ConexionDB;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.dao.ColorDAO;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Color;
public class ColorDAOImpl implements ColorDAO {
@Override
public Color findById(int codColor) throws RedMetroException {
String sql = ConfigConexion.get("sql.color.porId");
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, codColor);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
return new Color(rs.getInt("cod_color"),
rs.getString("nombre"),
rs.getString("cod_hexadecimal"));
}
} catch (SQLException e) {
throw new RedMetroException("Error al consultar el color" + codColor, e);
}
}
}
@@ -0,0 +1,42 @@
package es.madrid.red.metro.anp.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import es.madrid.red.metro.anp.conexion.ConexionDB;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.dao.LineaDAO;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Linea;
public class LineaDAOImpl implements LineaDAO {
@Override
public Linea findById(int codLinea) throws RedMetroException {
String sql = ConfigConexion.get("sql.linea.porId");
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, codLinea);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
Linea linea = new Linea();
linea.setCodLinea(rs.getInt("cod_linea"));
linea.setNombreCorto(rs.getString("nombre_corto"));
linea.setNombreLargo(rs.getString("nombre_largo"));
linea.setCodColor(rs.getInt("cod_color"));
linea.setKilometros(rs.getFloat("kilometros"));
return linea;
}
} catch (SQLException e) {
throw new RedMetroException("Error al consultar la línea" + codLinea, e);
}
}
}
@@ -0,0 +1,99 @@
package es.madrid.red.metro.anp.dao.impl;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import es.madrid.red.metro.anp.conexion.ConexionDB;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.dao.TrenDAO;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Tren;
public class TrenDAOImpl implements TrenDAO {
@Override
public Tren findById(int codTren) throws RedMetroException {
String sql = ConfigConexion.get("sql.tren.porId");
try(Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, codTren);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
Tren t = new Tren();
t.setCodTren(rs.getInt("cod_tren"));
t.setModelo(rs.getString("modelo"));
t.setEmpresaConstructora(rs.getString("empresa_constructora"));
Date fecha = rs.getDate("fecha_incorporacion");
if (fecha != null) {
t.setFechaIncorporacion(fecha.toLocalDate());
}
t.setCodCochera(rs.getInt("cod_cochera"));
t.setCodLinea(rs.getInt("cod_linea"));
return t;
}
} catch (SQLException e) {
throw new RedMetroException("Error al consultar el tren " + codTren, e);
}
}
@Override
public void insert(Tren t) throws RedMetroException {
String sql = ConfigConexion.get("sql.tren.insert");
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, t.getCodTren());
ps.setString(2, t.getModelo());
ps.setString(3, t.getEmpresaConstructora());
ps.setDate(4, Date.valueOf(t.getFechaIncorporacion()));
ps.setInt(5, t.getCodCochera());
ps.setInt(6, t.getCodLinea());
ps.executeUpdate();
} catch (SQLException e) {
throw new RedMetroException("Error al insertar el tren " + t.getCodTren(), e);
}
}
@Override
public List<Tren> findAll() throws RedMetroException {
String sql = ConfigConexion.get("sql.tren.todos");
List<Tren> trenes = new ArrayList<>();
try (Connection con = ConexionDB.getConexion();
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
trenes.add(mapear(rs));
}
return trenes;
} catch (SQLException e) {
throw new RedMetroException("Error al consultar los trenes", e);
}
}
private Tren mapear(ResultSet rs) throws SQLException {
Tren t = new Tren();
t.setCodTren(rs.getInt("cod_tren"));
t.setModelo(rs.getString("modelo"));
t.setEmpresaConstructora(rs.getString("empresa_constructora"));
Date fecha = rs.getDate("fecha_incorporacion");
if (fecha != null) {
t.setFechaIncorporacion(fecha.toLocalDate());
}
t.setCodCochera(rs.getInt("cod_cochera"));
t.setCodLinea(rs.getInt("cod_linea"));
return t;
}
}
@@ -0,0 +1,16 @@
package es.madrid.red.metro.anp.exception;
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);
}
}
@@ -0,0 +1,64 @@
package es.madrid.red.metro.anp.fichero;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Cochera;
import es.madrid.red.metro.anp.model.OperacionCochera;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
public class CocheraCsvReader {
public List<OperacionCochera> leer(String ruta) throws RedMetroException {
List<OperacionCochera> operaciones = new ArrayList<>();
String separador = ConfigConexion.get("csv.separador");
int columnasEsperadas = Integer.parseInt(ConfigConexion.get("csv.columnas"));
Charset charset = Charset.forName(ConfigConexion.get("csv.encoding"));
try (BufferedReader br = Files.newBufferedReader(Paths.get(ruta), charset)) {
br.readLine();
String linea;
while ((linea = br.readLine()) != null) {
if (linea.trim().isEmpty()) {
continue;
}
String[] campos = linea.split(separador, -1);
if (campos.length != columnasEsperadas) {
throw new RedMetroException("Error de formato en la línea "
+ ". Se esperaban " + columnasEsperadas + " columnas pero hay " + campos.length);
}
try {
int operacion = Integer.parseInt(campos[0].trim());
int codCochera = Integer.parseInt(campos[1].trim());
int deposito = Integer.parseInt(campos[2].trim());
String nombre = campos[3].trim();
String direccion = campos[4].trim();
operaciones.add(new OperacionCochera(operacion,
new Cochera(codCochera, nombre, direccion, deposito)));
} catch (NumberFormatException e) {
throw new RedMetroException("Error numérico en la línea " + e);
}
}
} catch (IOException e) {
throw new RedMetroException("Error al leer el archivo CSV de cocheras", e);
}
return operaciones;
}
}
@@ -0,0 +1,96 @@
package es.madrid.red.metro.anp.fichero;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Tren;
public class TrenXMLReader {
public List<Tren> leer(String ruta) throws RedMetroException {
List<Tren> trenes = new ArrayList<>();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(ruta));
NodeList nodosTrenes = doc.getElementsByTagName(ConfigConexion.get("xml.trenes"));
if (nodosTrenes.getLength() == 0) {
throw new RedMetroException(ConfigConexion.get("msg.xml.sinTrenes"));
}
Element elementoTrenes = (Element) nodosTrenes.item(0);
NodeList listaTren = elementoTrenes.getElementsByTagName(ConfigConexion.get("xml.tren"));
for (int i = 0; i < listaTren.getLength(); i++) {
Node nodo = listaTren.item(i);
if (nodo.getNodeType() == Node.ELEMENT_NODE) {
trenes.add(construirTren((Element) nodo));
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new RedMetroException(ConfigConexion.get("msg.xml.lectura"), e);
}
return trenes;
}
private Tren construirTren(Element el) throws RedMetroException {
String idTexto = el.getAttribute(ConfigConexion.get("xml.tren.id"));
Tren tren = new Tren();
tren.setCodTren(aEntero(idTexto, idTexto, ConfigConexion.get("xml.tren.id")));
tren.setModelo(texto(el, idTexto, "xml.tren.modelo"));
tren.setEmpresaConstructora(texto(el, idTexto, "xml.tren.constructora"));
tren.setCodCochera(aEntero(texto(el, idTexto, "xml.tren.cochera"), idTexto,
ConfigConexion.get("xml.tren.cochera")));
tren.setCodLinea(aEntero(texto(el, idTexto, "xml.tren.linea"), idTexto,
ConfigConexion.get("xml.tren.linea")));
int anyo = aEntero(texto(el, idTexto, "xml.tren.anyo"), idTexto,
ConfigConexion.get("xml.tren.anyo"));
int mes = Integer.parseInt(ConfigConexion.get("tren.fecha.mes"));
int dia = Integer.parseInt(ConfigConexion.get("tren.fecha.dia"));
tren.setFechaIncorporacion(LocalDate.of(anyo, mes, dia));
return tren;
}
private String texto(Element padre, String idTren, String claveEtiqueta) throws RedMetroException {
String etiqueta = ConfigConexion.get(claveEtiqueta);
NodeList nodos = padre.getElementsByTagName(etiqueta);
if (nodos.getLength() == 0) {
throw new RedMetroException(
String.format(ConfigConexion.get("msg.xml.etiqueta"), idTren, etiqueta));
}
return nodos.item(0).getTextContent().trim();
}
private int aEntero(String valor, String idTren, String etiqueta) throws RedMetroException {
try {
return Integer.parseInt(valor);
} catch (NumberFormatException e) {
throw new RedMetroException(
String.format(ConfigConexion.get("msg.xml.numero"), idTren, etiqueta), e);
}
}
}
@@ -0,0 +1,99 @@
package es.madrid.red.metro.anp.fichero;
import java.io.File;
import java.util.List;
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.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Color;
import es.madrid.red.metro.anp.model.Linea;
import es.madrid.red.metro.anp.model.Tren;
import es.madrid.red.metro.anp.model.TrenInfo;
public class TrenXmlWriter {
public void escribir(List<TrenInfo> trenes, String ruta) throws RedMetroException {
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
doc.setXmlStandalone(true); // evita standalone="no" en la cabecera
Element raiz = doc.createElement(ConfigConexion.get("xmlout.raiz"));
doc.appendChild(raiz);
Element nodoTrenes = doc.createElement(ConfigConexion.get("xmlout.trenes"));
raiz.appendChild(nodoTrenes);
for (TrenInfo info : trenes) {
nodoTrenes.appendChild(construirTren(doc, info));
}
guardar(doc, ruta);
} catch (ParserConfigurationException | TransformerException e) {
throw new RedMetroException(ConfigConexion.get("msg.xmlout.escritura"), e);
}
}
private Element construirTren(Document doc, TrenInfo info) throws RedMetroException {
Tren tren = info.getTren();
Linea linea = info.getLinea();
Color color = info.getColor();
Element elTren = doc.createElement(ConfigConexion.get("xmlout.tren"));
elTren.setAttribute(ConfigConexion.get("xmlout.tren.id"), String.valueOf(tren.getCodTren()));
añadir(doc, elTren, "xmlout.modelo", tren.getModelo());
// Si no hay fecha, la etiqueta se escribe vacía
String anyo = tren.getFechaIncorporacion() == null
? "" : String.valueOf(tren.getFechaIncorporacion().getYear());
añadir(doc, elTren, "xmlout.anyo", anyo);
añadir(doc, elTren, "xmlout.constructora", tren.getEmpresaConstructora());
añadir(doc, elTren, "xmlout.cochera", String.valueOf(tren.getCodCochera()));
// <linea id_linea="..."> con su nombre y su color
Element elLinea = doc.createElement(ConfigConexion.get("xmlout.linea"));
elLinea.setAttribute(ConfigConexion.get("xmlout.linea.id"), String.valueOf(linea.getCodLinea()));
añadir(doc, elLinea, "xmlout.linea.nombre", linea.getNombreLargo());
Element elColor = doc.createElement(ConfigConexion.get("xmlout.color"));
elColor.setAttribute(ConfigConexion.get("xmlout.color.id"), String.valueOf(color.getCodColor()));
elColor.setAttribute(ConfigConexion.get("xmlout.color.hex"), color.getCodHexadecimal());
añadir(doc, elColor, "xmlout.color.descripcion", color.getNombre());
elLinea.appendChild(elColor);
elTren.appendChild(elLinea);
return elTren;
}
/** Crea <etiqueta>texto</etiqueta> y la cuelga del padre. */
private void añadir(Document doc, Element padre, String claveEtiqueta, String texto)
throws RedMetroException {
Element el = doc.createElement(ConfigConexion.get(claveEtiqueta));
el.setTextContent(texto);
padre.appendChild(el);
}
private void guardar(Document doc, String ruta)
throws TransformerException, RedMetroException {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.ENCODING, ConfigConexion.get("xmlout.encoding"));
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
ConfigConexion.get("xmlout.indentacion"));
t.transform(new DOMSource(doc), new StreamResult(new File(ruta)));
}
}
@@ -0,0 +1,53 @@
package es.madrid.red.metro.anp.model;
public class Cochera {
private int codCochera;
private String nombre;
private String direccion;
private int deposito;
public Cochera() {}
public Cochera(int codCochera, String nombre, String direccion, int deposito) {
super();
this.codCochera = codCochera;
this.nombre = nombre;
this.direccion = direccion;
this.deposito = deposito;
}
public int getCodCochera() {
return codCochera;
}
public void setCodCochera(int codCochera) {
this.codCochera = codCochera;
}
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;
}
}
@@ -0,0 +1,42 @@
package es.madrid.red.metro.anp.model;
public class Color {
private int codColor;
private String nombre;
private String codHexadecimal;
public Color() {}
public Color(int codColor, String nombre, String codHexadecimal) {
super();
this.codColor = codColor;
this.nombre = nombre;
this.codHexadecimal = codHexadecimal;
}
public int getCodColor() {
return codColor;
}
public void setCodColor(int codColor) {
this.codColor = codColor;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCodHexadecimal() {
return codHexadecimal;
}
public void setCodHexadecimal(String codHexadecimal) {
this.codHexadecimal = codHexadecimal;
}
}
@@ -0,0 +1,71 @@
package es.madrid.red.metro.anp.model;
public class Linea {
private int codLinea;
private String nombreCorto;
private String nombreLargo;
private int codColor;
private float Kilometros;
public Linea() {}
public Linea(int codLinea, String nombreCorto, String nombreLargo, int codColor, float kilometros) {
super();
this.codLinea = codLinea;
this.nombreCorto = nombreCorto;
this.nombreLargo = nombreLargo;
this.codColor = codColor;
Kilometros = kilometros;
}
public int getCodLinea() {
return codLinea;
}
public void setCodLinea(int codLinea) {
this.codLinea = codLinea;
}
public String getNombreCorto() {
return nombreCorto;
}
public void setNombreCorto(String nombreCorto) {
this.nombreCorto = nombreCorto;
}
public int getCodColor() {
return codColor;
}
public void setCodColor(int codColor) {
this.codColor = codColor;
}
public float getKilometros() {
return Kilometros;
}
public void setKilometros(float kilometros) {
Kilometros = kilometros;
}
public String getNombreLargo() {
return nombreLargo;
}
public void setNombreLargo(String nombreLargo) {
this.nombreLargo = nombreLargo;
}
}
@@ -0,0 +1,27 @@
package es.madrid.red.metro.anp.model;
public class OperacionCochera {
public static final int NADA = 0;
public static final int INSERTAR = 1;
public static final int MODIFICAR = 2;
public static final int BORRAR = 3;
private final int operacion;
private final Cochera cochera;
public OperacionCochera(int operacion, Cochera cochera) {
super();
this.operacion = operacion;
this.cochera = cochera;
}
public int getOperacion() {
return operacion;
}
public Cochera getCochera() {
return cochera;
}
}
@@ -0,0 +1,78 @@
package es.madrid.red.metro.anp.model;
import java.time.LocalDate;
public class Tren {
private int codTren;
private String modelo;
private String empresaConstructora;
private LocalDate FechaIncorporacion;
private int codCochera;
private int codLinea;
public Tren() {}
public Tren(int codTren, String modelo, String empresaConstructora, LocalDate fechaIncorporacion, int codCochera,
int codLinea) {
super();
this.codTren = codTren;
this.modelo = modelo;
this.empresaConstructora = empresaConstructora;
FechaIncorporacion = fechaIncorporacion;
this.codCochera = codCochera;
this.codLinea = codLinea;
}
public int getCodTren() {
return codTren;
}
public void setCodTren(int codTren) {
this.codTren = codTren;
}
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) {
FechaIncorporacion = fechaIncorporacion;
}
public int getCodCochera() {
return codCochera;
}
public void setCodCochera(int codCochera) {
this.codCochera = codCochera;
}
public int getCodLinea() {
return codLinea;
}
public void setCodLinea(int codLinea) {
this.codLinea = codLinea;
}
}
@@ -0,0 +1,28 @@
package es.madrid.red.metro.anp.model;
public class TrenInfo {
private final Tren tren;
private final Linea linea;
private final Color color;
public Tren getTren() {
return tren;
}
public Linea getLinea() {
return linea;
}
public Color getColor() {
return color;
}
public TrenInfo(Tren tren, Linea linea, Color color) {
super();
this.tren = tren;
this.linea = linea;
this.color = color;
}
}
@@ -0,0 +1,11 @@
package es.madrid.red.metro.anp.service;
import java.util.List;
import es.madrid.red.metro.anp.exception.RedMetroException;
public interface CocheraService {
List<String> procesarFicheroCocheras() throws RedMetroException;
}
@@ -0,0 +1,9 @@
package es.madrid.red.metro.anp.service;
import es.madrid.red.metro.anp.exception.RedMetroException;
public interface LineaService {
String obtenerColorDeLinea(int codLinea) throws RedMetroException;
}
@@ -0,0 +1,13 @@
package es.madrid.red.metro.anp.service;
import java.util.List;
import es.madrid.red.metro.anp.exception.RedMetroException;
public interface TrenService {
List<String> cargarTrenesDesdeXML() throws RedMetroException;
String exportarTrenesAXml() throws RedMetroException;
}
@@ -0,0 +1,89 @@
package es.madrid.red.metro.anp.service.impl;
import java.util.ArrayList;
import java.util.List;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.dao.impl.CocheraDAOImpl;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.fichero.CocheraCsvReader;
import es.madrid.red.metro.anp.model.Cochera;
import es.madrid.red.metro.anp.model.OperacionCochera;
import es.madrid.red.metro.anp.service.CocheraService;
import es.madrid.red.metro.anp.dao.*;
public class CocheraServiceImpl implements CocheraService {
private final CocheraDAO cocheraDAO = new CocheraDAOImpl();
private final CocheraCsvReader lector = new CocheraCsvReader();
@Override
public List<String> procesarFicheroCocheras() throws RedMetroException {
List<OperacionCochera> operaciones = lector.leer(ConfigConexion.get("fichero.cocheras"));
List<String> informe = new ArrayList<>();
for (OperacionCochera op : operaciones) {
Cochera c = op.getCochera();
int cod = c.getCodCochera();
try {
switch (op.getOperacion()) {
case OperacionCochera.NADA:
break;
case OperacionCochera.INSERTAR:
if (cocheraDAO.findById(cod) != null) {
informe.add(String.format(ConfigConexion.get("msg.cochera.yaExiste"), cod));
} else {
cocheraDAO.insert(c);
informe.add(String.format(ConfigConexion.get("msg.cochera.insertada"),
cod, c.getNombre()));
}
break;
case OperacionCochera.MODIFICAR:
if (cocheraDAO.update(c)) {
informe.add(String.format(ConfigConexion.get("msg.cochera.modificada"),
cod, c.getNombre()));
} else {
informe.add(String.format(ConfigConexion.get("msg.cochera.noExiste"),
cod, op.getOperacion()));
}
break;
case OperacionCochera.BORRAR:
if (cocheraDAO.delete(cod)) {
informe.add(String.format(ConfigConexion.get("msg.cochera.borrada"), cod));
} else {
informe.add(String.format(ConfigConexion.get("msg.cochera.noExiste"),
cod, op.getOperacion()));
}
break;
default:
informe.add(String.format(ConfigConexion.get("msg.cochera.opDesconocida"),
cod, op.getOperacion()));
}
} catch (RedMetroException e) {
informe.add(String.format(ConfigConexion.get("msg.cochera.error"),
cod, op.getOperacion(), e.getCause() != null
? e.getCause().getMessage() : e.getMessage()));
}
}
return informe;
}
}
@@ -0,0 +1,42 @@
package es.madrid.red.metro.anp.service.impl;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.dao.ColorDAO;
import es.madrid.red.metro.anp.dao.LineaDAO;
import es.madrid.red.metro.anp.dao.impl.ColorDAOImpl;
import es.madrid.red.metro.anp.dao.impl.LineaDAOImpl;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.model.Color;
import es.madrid.red.metro.anp.model.Linea;
import es.madrid.red.metro.anp.service.LineaService;
public class LineaServiceImpl implements LineaService {
private final LineaDAO lineaDAO = new LineaDAOImpl();
private final ColorDAO colorDAO = new ColorDAOImpl();
@Override
public String obtenerColorDeLinea(int codLinea) throws RedMetroException {
Linea linea = lineaDAO.findById(codLinea);
if (linea == null) {
throw new RedMetroException(
String.format(ConfigConexion.get("msg.linea.noExiste"), codLinea));
}
Color color = colorDAO.findById(linea.getCodColor());
if(color == null) {
throw new RedMetroException(
String.format(ConfigConexion.get("msg.color.noExiste"), linea.getCodColor()));
}
return String.format(ConfigConexion.get("msg.linea.resultado"),
linea.getNombreCorto(),
linea.getNombreLargo(),
String.valueOf(linea.getKilometros()),
color.getNombre(),
color.getCodHexadecimal());
}
}
@@ -0,0 +1,121 @@
package es.madrid.red.metro.anp.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import es.madrid.red.metro.anp.conexion.ConfigConexion;
import es.madrid.red.metro.anp.dao.CocheraDAO;
import es.madrid.red.metro.anp.dao.ColorDAO;
import es.madrid.red.metro.anp.dao.LineaDAO;
import es.madrid.red.metro.anp.dao.TrenDAO;
import es.madrid.red.metro.anp.dao.impl.CocheraDAOImpl;
import es.madrid.red.metro.anp.dao.impl.ColorDAOImpl;
import es.madrid.red.metro.anp.dao.impl.LineaDAOImpl;
import es.madrid.red.metro.anp.dao.impl.TrenDAOImpl;
import es.madrid.red.metro.anp.exception.RedMetroException;
import es.madrid.red.metro.anp.fichero.TrenXMLReader;
import es.madrid.red.metro.anp.fichero.TrenXmlWriter;
import es.madrid.red.metro.anp.model.Color;
import es.madrid.red.metro.anp.model.Linea;
import es.madrid.red.metro.anp.model.Tren;
import es.madrid.red.metro.anp.model.TrenInfo;
import es.madrid.red.metro.anp.service.TrenService;
public class TrenServiceImpl implements TrenService {
private final TrenDAO trenDAO = new TrenDAOImpl();
private final CocheraDAO cocheraDAO = new CocheraDAOImpl();
private final LineaDAO lineaDAO = new LineaDAOImpl();
private final TrenXMLReader lector = new TrenXMLReader();
private final ColorDAO colorDAO = new ColorDAOImpl();
private final TrenXmlWriter escritor = new TrenXmlWriter();
@Override
public List<String> cargarTrenesDesdeXML() throws RedMetroException {
List<Tren> trenes = lector.leer(ConfigConexion.get("fichero.trenes.entrada"));
List<String> informe = new ArrayList<>();
for (Tren t : trenes) {
int cod = t.getCodTren();
try {
if (trenDAO.findById(cod) != null) {
informe.add(String.format(ConfigConexion.get("msg.tren.yaExiste"), cod));
} else if (cocheraDAO.findById(t.getCodCochera()) == null) {
informe.add(String.format(ConfigConexion.get("msg.tren.sinCochera"),
cod, t.getCodCochera()));
} else if (lineaDAO.findById(t.getCodLinea()) == null) {
informe.add(String.format(ConfigConexion.get("msg.tren.sinLinea"),
cod, t.getCodLinea()));
} else {
trenDAO.insert(t);
informe.add(String.format(ConfigConexion.get("msg.tren.insertado"),
cod, t.getModelo()));
}
} catch (RedMetroException e) {
informe.add(String.format(ConfigConexion.get("msg.tren.error"), cod,
e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
}
return informe;
}
@Override
public String exportarTrenesAXml() throws RedMetroException {
List<Tren> trenes = trenDAO.findAll();
if (trenes.isEmpty()) {
return ConfigConexion.get("msg.xmlout.sinTrenes");
}
// Cachés para no consultar varias veces la misma línea o color
Map<Integer, Linea> lineas = new HashMap<>();
Map<Integer, Color> colores = new HashMap<>();
List<TrenInfo> infos = new ArrayList<>();
for (Tren t : trenes) {
Linea linea = lineas.get(t.getCodLinea());
if (linea == null) {
linea = lineaDAO.findById(t.getCodLinea());
lineas.put(t.getCodLinea(), linea);
}
Color color = null;
if (linea != null) {
color = colores.get(linea.getCodColor());
if (color == null) {
color = colorDAO.findById(linea.getCodColor());
colores.put(linea.getCodColor(), color);
}
}
// Las FK lo impiden, pero se valida por seguridad
if (linea == null || color == null) {
throw new RedMetroException(String.format(
ConfigConexion.get("msg.xmlout.incoherente"), t.getCodTren(), t.getCodLinea()));
}
infos.add(new TrenInfo(t, linea, color));
}
String ruta = ConfigConexion.get("fichero.trenes.salida");
escritor.escribir(infos, ruta);
return String.format(ConfigConexion.get("msg.xmlout.generado"), ruta, infos.size());
}
}
+4
View File
@@ -0,0 +1,4 @@
Manifest-Version: 1.0
Build-Jdk-Spec: 21
Created-By: Maven Integration for Eclipse
@@ -0,0 +1,7 @@
#Generated by Maven Integration for Eclipse
#Mon Nov 09 19:16:49 CET 2026
artifactId=Conectores_02
groupId=Conectores_02
m2e.projectLocation=C\:\\Users\\PC GAMING\\eclipse-workspace\\examen_simulacion
m2e.projectName=examen_simulacion
version=0.0.1-SNAPSHOT
@@ -0,0 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Conectores_02</groupId>
<artifactId>Conectores_02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- Conector de MySQL JDBC -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<!-- Cambia esto al número de la versión de Java que tengas instalada (ej: 17, 21, etc.) -->
<release>17</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
Binary file not shown.