Primer Commit

This commit is contained in:
SASI
2026-11-08 21:46:52 +01:00
commit 23f474f56f
28 changed files with 1358 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
bin/
.settings/
.classpath
.project
target/
+10
View File
@@ -0,0 +1,10 @@
sgdb.conexion.url=jdbc:mysql://192.168.1.134:3306/
bbdd.nombre=red_metro_ss
bbdd.usuario=root
bbdd.clave=root
fichero.cocheras.csv=ficheros/operaciones-cocherasRM.csv
fichero.cocheras.separador=;
fichero.trenes.xml=ficheros/trenes_estaciones_accesos.xml
fichero.salida.xml=ficheros/red_metro_ss.xml
+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
+45
View File
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<info-trenes-linea-color>
<trenes>
<tren id="1">
<modelo>Serie 2000-A</modelo>
<anyo_incorporacion>2000</anyo_incorporacion>
<empresa_constructora>CAF</empresa_constructora>
<cod_cochera>15</cod_cochera>
<linea id_linea="5">
<nombre_l>Arguelles - Pinar de Chamartín</nombre_l>
<color cod_hex="#741013" id="4"/>
</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>
<linea id_linea="5">
<nombre_l>Arguelles - Pinar de Chamartín</nombre_l>
<color cod_hex="#741013" id="4"/>
</linea>
</tren>
<tren id="3">
<modelo>Serie 3000</modelo>
<anyo_incorporacion>2010</anyo_incorporacion>
<empresa_constructora>CAF</empresa_constructora>
<cod_cochera>15</cod_cochera>
<linea id_linea="5">
<nombre_l>Arguelles - Pinar de Chamartín</nombre_l>
<color cod_hex="#741013" id="4"/>
</linea>
</tren>
<tren id="4">
<modelo>Serie 5000</modelo>
<anyo_incorporacion>2010</anyo_incorporacion>
<empresa_constructora>CAF</empresa_constructora>
<cod_cochera>1</cod_cochera>
<linea id_linea="9">
<nombre_l>Nuevos Ministerios - Aeropuerto</nombre_l>
<color cod_hex="#f5418e" id="8"/>
</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>
+30
View File
@@ -0,0 +1,30 @@
<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>RedMetroSS</groupId>
<artifactId>RedMetroSS</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- Source:
https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>26.10.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<release>25</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,45 @@
package es.madrid.redmetro.ss;
import java.util.Scanner;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.service.CocheraService;
import es.madrid.redmetro.ss.service.LineaService;
import es.madrid.redmetro.ss.service.TrenService;
public class AppPrincipal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Introduce la operacion a realizar: ");
String opcion = sc.nextLine();
try {
switch(opcion) {
case "A":
System.out.println("Introduce el id de la linea: ");
int idLinea = sc.nextInt();
LineaService lineaService = new LineaService();
lineaService.obtenerInformacionLineaColor(idLinea);
break;
case "B":
CocheraService cocheraService = new CocheraService();
cocheraService.procesarFicheroCocheras();
break;
case "C":
TrenService trenService = new TrenService();
trenService.importarTrenes();
break;
case "D":
TrenService trenServiceD = new TrenService();
trenServiceD.exportarTrenes();
}
}catch(RedMetroException e) {
System.err.println("[ERROR ]" + e.getMessage());
}
sc.close();
}
}
@@ -0,0 +1,13 @@
package es.madrid.redmetro.ss.dao;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.model.Cochera;
public interface ICocheraDAO {
Cochera obtenerCocheraPorCodigo(int codigo) throws RedMetroException;
void insertar(Cochera cochera) throws RedMetroException;
void actualizar(Cochera cochera) throws RedMetroException;
void borrar(int codCochera) throws RedMetroException;
}
@@ -0,0 +1,5 @@
package es.madrid.redmetro.ss.dao;
public interface IColorDAO {
}
@@ -0,0 +1,10 @@
package es.madrid.redmetro.ss.dao;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.model.Linea;
public interface ILineaDAO {
Linea buscarPorIdConColor(int idLinea)throws RedMetroException;
}
@@ -0,0 +1,13 @@
package es.madrid.redmetro.ss.dao;
import java.util.List;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.model.Tren;
public interface ITrenDAO {
void insertar(Tren tren) throws RedMetroException;
List<Tren> obtenerTodosConLineaColor() throws RedMetroException;
}
@@ -0,0 +1,87 @@
package es.madrid.redmetro.ss.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import es.madrid.redmetro.ss.dao.ICocheraDAO;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.model.Cochera;
public class CocheraDaoJDBC implements ICocheraDAO{
private Connection conexion;
public CocheraDaoJDBC(Connection conexion) {
this.conexion = conexion;
}
@Override
public Cochera obtenerCocheraPorCodigo(int codCochera) throws RedMetroException {
String sql = "SELECT * FROM T_COCHERA WHERE cod_cochera = ?";
try(PreparedStatement sentencia = conexion.prepareStatement(sql)){
sentencia.setInt(1, codCochera);
try(ResultSet rs = sentencia.executeQuery()){
if(rs.next()) {
return new Cochera(rs.getInt("cod_cochera"),
rs.getString("nombre"),
rs.getString("direccion"),
rs.getInt("deposito"));
}
}
} catch (SQLException e) {
throw new RedMetroException("Error al buscar cochera por codigo: " + codCochera, e);
}
return null;
}
@Override
public void insertar(Cochera cochera) throws RedMetroException {
String sql = "INSERT INTO T_COCHERA (cod_cochera, nombre, direccion, deposito) VALUES (?, ?, ?, ?);";
try(PreparedStatement sentencia = conexion.prepareStatement(sql)){
sentencia.setInt(1, cochera.getCodCochera());
sentencia.setString(2, cochera.getNombre());
sentencia.setString(3, cochera.getDireccion());
sentencia.setInt(4, cochera.getDeposito());
sentencia.executeUpdate();
} catch (SQLException e) {
throw new RedMetroException("Error al insertat cochera " + cochera.getCodCochera(), e);
}
}
@Override
public void actualizar(Cochera cochera) throws RedMetroException {
String sql = "UPDATE T_COCHERA SET nombre = ?, direccion = ?, deposito = ? WHERE cod_cochera = ?;";
try(PreparedStatement ps = conexion.prepareStatement(sql)){
ps.setString(1, cochera.getNombre());
ps.setString(2, cochera.getDireccion());
ps.setInt(3, cochera.getDeposito());
ps.setInt(4, cochera.getCodCochera());
ps.executeUpdate();
} catch (SQLException e) {
throw new RedMetroException("Error al actualizar la cohera: " +cochera.getCodCochera(), e);
}
}
@Override
public void borrar(int codCochera) throws RedMetroException {
String sql = "DELETE FROM T_COCHERA WHERE cod_cochera = ?;";
try(PreparedStatement ps = conexion.prepareStatement(sql)){
ps.setInt(1, codCochera);
ps.executeUpdate();
} catch (SQLException e) {
throw new RedMetroException("Error al borrar cochera: " + codCochera, e);
}
}
}
@@ -0,0 +1,5 @@
package es.madrid.redmetro.ss.dao.impl;
public class ColorDaoJDBC {
}
@@ -0,0 +1,50 @@
package es.madrid.redmetro.ss.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import es.madrid.redmetro.ss.dao.ILineaDAO;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.model.Color;
import es.madrid.redmetro.ss.model.Linea;
public class LineaDaoJDBC implements ILineaDAO{
private final Connection conexion;
public LineaDaoJDBC(Connection conexion) {
this.conexion = conexion;
}
@Override
public Linea buscarPorIdConColor(int idLinea) throws RedMetroException {
String sql = "SELECT tl.*, tc.* FROM T_LINEA tl JOIN T_COLOR tc ON tl.cod_color = tc.cod_color\r\n"
+ " WHERE tl.cod_linea = ?;";
try(PreparedStatement sentencia = conexion.prepareStatement(sql)){
sentencia.setInt(1, idLinea);
try(ResultSet resultado = sentencia.executeQuery()){
if(resultado.next()) {
Color c = new Color(resultado.getInt("cod_color"), resultado.getString("nombre"),resultado.getString("cod_hexadecimal"));
Linea l = new Linea(resultado.getInt("cod_linea"),
resultado.getString("nombre_corto"),
resultado.getString("nombre_largo"),
resultado.getInt("cod_color"),
resultado.getDouble("kilometros"),
c);
return l;
}
}
} catch (SQLException e) {
throw new RedMetroException("Error al consultar linea por ID "+ idLinea + e);
}
return null;
}
}
@@ -0,0 +1,112 @@
package es.madrid.redmetro.ss.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import es.madrid.redmetro.ss.dao.ITrenDAO;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.model.Color;
import es.madrid.redmetro.ss.model.Linea;
import es.madrid.redmetro.ss.model.Tren;
public class TrenDaoJDBC implements ITrenDAO{
private Connection conexion;
public TrenDaoJDBC(Connection conexion) {
this.conexion = conexion;
}
@Override
public void insertar(Tren tren) throws RedMetroException {
String sql = "INSERT INTO T_TREN (cod_tren, modelo, empresa_constructora, fecha_incorporacion, cod_cochera, cod_linea) VALUES (?, ?, ?, ?, ?, ?);";
try(PreparedStatement ps = conexion.prepareStatement(sql)){
ps.setInt(1, tren.getCodTren());
ps.setString(2, tren.getModelo());
ps.setString(3, tren.getEmpresaConstructora());
// CORRECCIÓN: Como ya es LocalDate, usamos java.sql.Date.valueOf() para mandarlo a MySQL
ps.setDate(4, java.sql.Date.valueOf(tren.getFechaIncorporacion()));
ps.setInt(5, tren.getCodCochera());
ps.setInt(6, tren.getCodLinea());
ps.executeUpdate();
} catch (SQLException e) {
throw new RedMetroException("Error al insertar el tren " + tren.getCodTren(),e);
}
}
@Override
public List<Tren> obtenerTodosConLineaColor() throws RedMetroException {
List<Tren> listaTrenes = new ArrayList<>();
String sql = "SELECT t.cod_tren, t.modelo, t.empresa_constructora, t.fecha_incorporacion, t.cod_cochera, t.cod_linea, "
+ "l.nombre_corto, l.nombre_largo, l.kilometros, l.cod_color, "
+ "c.nombre AS nombre_color, c.cod_hexadecimal "
+ "FROM T_TREN t "
+ "JOIN T_LINEA l ON t.cod_linea = l.cod_linea "
+ "JOIN T_COLOR c ON l.cod_color = c.cod_color";
try(PreparedStatement ps = conexion.prepareStatement(sql);
ResultSet rs = ps.executeQuery()){
while(rs.next()) {
Color color = new Color(rs.getInt("cod_color"), rs.getString("nombre_color"), rs.getString("cod_hexadecimal"));
Linea linea = new Linea(rs.getInt("cod_linea"),
rs.getString("nombre_corto"),
rs.getString("nombre_largo"),
rs.getInt("cod_color"),
rs.getDouble("kilometros"),
color);
Tren tren = new Tren(rs.getInt("cod_tren"),
rs.getString("modelo"),
rs.getString("empresa_constructora"),
rs.getDate("fecha_incorporacion").toLocalDate(),
rs.getInt("cod_cochera"),
rs.getInt("cod_linea"),
linea);
listaTrenes.add(tren);
}
} catch (SQLException e) {
throw new RedMetroException("Error al obtener los trenes con línea y color", e);
}
return listaTrenes;
}
}
@@ -0,0 +1,17 @@
package es.madrid.redmetro.ss.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,20 @@
package es.madrid.redmetro.ss.gestores;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class GestorConexionBBDD {
public static Connection obtenerConexion() throws SQLException {
String url = GestorConfiguracion.getConexionURL() + GestorConfiguracion.getNombreBBDD();
String usuario = GestorConfiguracion.getUsuarioBBDD();
String clave = GestorConfiguracion.getClaveBBDD();
return DriverManager.getConnection(url, usuario, clave);
}
}
@@ -0,0 +1,62 @@
package es.madrid.redmetro.ss.gestores;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import es.madrid.redmetro.ss.gestores.GestorConfiguracion;
public class GestorConfiguracion {
private static final String RUTA_CONFIG = "application.properties";
private static final Properties PROPIEDADES = new Properties();
static {
try(InputStream inputStream = GestorConfiguracion.class.getClassLoader().getResourceAsStream(RUTA_CONFIG)){
if ( inputStream == null) {
throw new IOException("No se ha podido encontrar el archivo de configuracion");
}
PROPIEDADES.load(inputStream);
} catch (IOException e) {
throw new RuntimeException("No ha podido cargar el archivo" + e);
}
}
public static String getConexionURL() {
return PROPIEDADES.getProperty("sgdb.conexion.url");
}
public static String getNombreBBDD() {
return PROPIEDADES.getProperty("bbdd.nombre");
}
public static String getUsuarioBBDD() {
return PROPIEDADES.getProperty("bbdd.usuario");
}
public static String getClaveBBDD() {
return PROPIEDADES.getProperty("bbdd.clave");
}
public static String getRutaCocherasCSV() {
return PROPIEDADES.getProperty("fichero.cocheras.csv");
}
public static String getSeparadorCSV() {
return PROPIEDADES.getProperty("fichero.cocheras.separador");
}
public static String getRutaTrenesXML() {
return PROPIEDADES.getProperty("fichero.trenes.xml");
}
public static String getRutaSalidaXML() {
return PROPIEDADES.getProperty("fichero.salida.xml"); }
}
@@ -0,0 +1,61 @@
package es.madrid.redmetro.ss.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) {
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;
}
@Override
public String toString() {
return "Cochera [codCochera=" + codCochera + ", nombre=" + nombre + ", direccion=" + direccion + ", deposito="
+ deposito + "]";
}
}
@@ -0,0 +1,55 @@
package es.madrid.redmetro.ss.model;
public class Color {
private int codColor;
private String nombre;
private String codHexadecimal;
public Color() {
}
public Color(int codColor, String nombre, String codHexadecimal) {
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;
}
@Override
public String toString() {
return "Color [codColor=" + codColor + ", nombre=" + nombre + ", codHexadecimal=" + codHexadecimal + "]";
}
}
@@ -0,0 +1,76 @@
package es.madrid.redmetro.ss.model;
public class Linea {
private int codLinea;
private String nombreCorto;
private String nombreLargo;
private int codColor;
private double kilometros;
private Color color;
public Linea() {
}
public Linea(int codLinea, String nombreCorto, String nombreLargo, int codColor, double kilometros, Color color) {
super();
this.codLinea = codLinea;
this.nombreCorto = nombreCorto;
this.nombreLargo = nombreLargo;
this.codColor = codColor;
this.kilometros = kilometros;
this.color = color;
}
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 String getNombreLargo() {
return nombreLargo;
}
public void setNombreLargo(String nombreLargo) {
this.nombreLargo = nombreLargo;
}
public int getCodColor() {
return codColor;
}
public void setCodColor(int codColor) {
this.codColor = codColor;
}
public double getKilometros() {
return kilometros;
}
public void setKilometros(double kilometros) {
this.kilometros = kilometros;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@Override
public String toString() {
return "Linea [codLinea=" + codLinea + ", nombreCorto=" + nombreCorto + ", nombreLargo=" + nombreLargo
+ ", codColor=" + codColor + ", kilometros=" + kilometros + ", color=" + color + "]";
}
}
+109
View File
@@ -0,0 +1,109 @@
package es.madrid.redmetro.ss.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;
private Linea linea;
private Cochera cochera;
public Tren() {
}
public Tren(int codTren, String modelo, String empresaConstructora, LocalDate fechaIncorporacion, int codCochera,
int codLinea, Linea linea, Cochera cochera) {
this.codTren = codTren;
this.modelo = modelo;
this.empresaConstructora = empresaConstructora;
this.fechaIncorporacion = fechaIncorporacion;
this.codCochera = codCochera;
this.codLinea = codLinea;
this.linea = linea;
this.cochera = cochera;
}
public Tren(int codTren, String modelo, String empresaConstructora, LocalDate fechaIncorporacion, int codCochera, int codLinea) {
this.codTren = codTren;
this.modelo = modelo;
this.empresaConstructora = empresaConstructora;
this.fechaIncorporacion = fechaIncorporacion;
this.codCochera = codCochera;
this.codLinea = codLinea;
}
public Tren(int codTren, String modelo, String empresaConstructora, LocalDate fechaIncorporacion, int codCochera, int codLinea, Linea linea) {
this.codTren = codTren;
this.modelo = modelo;
this.empresaConstructora = empresaConstructora;
this.fechaIncorporacion = fechaIncorporacion;
this.codCochera = codCochera;
this.codLinea = codLinea;
this.linea = linea;
}
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) {
this.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;
}
public Linea getLinea() {
return linea;
}
public void setLinea(Linea linea) {
this.linea = linea;
}
public Cochera getCochera() {
return cochera;
}
public void setCochera(Cochera cochera) {
this.cochera = cochera;
}
@Override
public String toString() {
return "Tren [codTren=" + codTren + ", modelo=" + modelo + ", empresaConstructora=" + empresaConstructora
+ ", fechaIncorporacion=" + fechaIncorporacion + ", codCochera=" + codCochera + ", codLinea=" + codLinea
+ ", linea=" + linea + ", cochera=" + cochera + "]";
}
}
@@ -0,0 +1,55 @@
package es.madrid.redmetro.ss.service;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import es.madrid.redmetro.ss.dao.ICocheraDAO;
import es.madrid.redmetro.ss.dao.impl.CocheraDaoJDBC;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.gestores.GestorConexionBBDD;
import es.madrid.redmetro.ss.model.Cochera;
import es.madrid.redmetro.ss.util.LecturaCSV;
public class CocheraService {
public void procesarFicheroCocheras() throws RedMetroException {
List<LecturaCSV.RegistroCSV> registros = new ArrayList<>();
registros = LecturaCSV.leerCocheras();
try(Connection con = GestorConexionBBDD.obtenerConexion()){
ICocheraDAO cocheraDao = new CocheraDaoJDBC(con);
System.out.println("\n--- Procesando archivo de cocheras ---");
for(LecturaCSV.RegistroCSV reg : registros) {
Cochera c = reg.cochera;
switch(reg.operacion) {
case 0:
System.out.println("No se hace nada con la cochera" + c.getCodCochera());
break;
case 1:
if(cocheraDao.obtenerCocheraPorCodigo(c.getCodCochera()) == null) {
cocheraDao.insertar(c);
System.out.println("Insertada cochera: " + c.getCodCochera());
}else {
System.out.println("Omitida inserción. La cochera " + c.getCodCochera() + " ya existe.");
}
break;
case 2:
cocheraDao.actualizar(c);
System.out.println("Actualizada cochera: " + c.getCodCochera());
break;
case 3:
cocheraDao.borrar(c.getCodCochera());
System.out.println("Borrada cochera: " + c.getCodCochera());
break;
}
}
} catch (SQLException e) {
throw new RedMetroException("Error al conectar con la BBDD en CocheraService", e);
}
}
}
@@ -0,0 +1,34 @@
package es.madrid.redmetro.ss.service;
import java.sql.Connection;
import java.sql.SQLException;
import es.madrid.redmetro.ss.dao.ILineaDAO;
import es.madrid.redmetro.ss.dao.impl.LineaDaoJDBC;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.gestores.GestorConexionBBDD;
import es.madrid.redmetro.ss.model.Linea;
public class LineaService {
public void obtenerInformacionLineaColor(int idLinea) throws RedMetroException {
try(Connection con = GestorConexionBBDD.obtenerConexion()){
ILineaDAO lineaDao = new LineaDaoJDBC(con);
Linea linea = lineaDao.buscarPorIdConColor(idLinea);
if (linea != null && linea.getColor() != null) {
System.out.println("El color de la Linea " + linea.getCodLinea()
+ "(" + linea.getNombreLargo() + "), que tiene una longitud de "
+ linea.getKilometros() + "Km, es "
+ linea.getColor().getNombre() + "("
+ linea.getColor().getCodHexadecimal() + ")");
} else {
System.out.println("\n[AVISO] No se encontró ninguna línea con el ID: " + idLinea);
}
}catch(SQLException e) {
throw new RedMetroException("Error al conectar con la BBDD en LineaService" + e);
}
}
}
@@ -0,0 +1,48 @@
package es.madrid.redmetro.ss.service;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import es.madrid.redmetro.ss.dao.ITrenDAO;
import es.madrid.redmetro.ss.dao.impl.TrenDaoJDBC;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.gestores.GestorConexionBBDD;
import es.madrid.redmetro.ss.model.Tren;
import es.madrid.redmetro.ss.util.EscrituraXML;
import es.madrid.redmetro.ss.util.LecturaXML;
public class TrenService {
public void importarTrenes() throws RedMetroException {
List<Tren> listaTrenes = LecturaXML.leerTrenes();
try(Connection con = GestorConexionBBDD.obtenerConexion()){
ITrenDAO trenDao = new TrenDaoJDBC(con);
System.out.println("\n--- Iniciando importación de Trenes desde XML ---");
for(Tren tren : listaTrenes) {
trenDao.insertar(tren);
}
} catch (SQLException e) {
throw new RedMetroException("Error al conectar con la bbdd para importar trenes", e);
}
}
public void exportarTrenes() throws RedMetroException {
try(Connection con = GestorConexionBBDD.obtenerConexion()){
ITrenDAO trenDao = new TrenDaoJDBC(con);
System.out.println("\n--- Extrayendo datos de la base de datos ---");
List<Tren> listaTrenes = trenDao.obtenerTodosConLineaColor();
EscrituraXML.generarXML(listaTrenes);
} catch (SQLException e) {
throw new RedMetroException("Error al exportar los trenes", e);
}
}
}
@@ -0,0 +1,113 @@
package es.madrid.redmetro.ss.util;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.gestores.GestorConfiguracion;
import es.madrid.redmetro.ss.model.Tren;
public class EscrituraXML {
public static void generarXML(List<Tren> trenes) throws RedMetroException {
String rutaSalida = GestorConfiguracion.getRutaSalidaXML();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element raiz = doc.createElement("info-trenes-linea-color");
doc.appendChild(raiz);
Element nodoTrenes = doc.createElement("trenes");
raiz.appendChild(nodoTrenes);
for(Tren t:trenes) {
Element nodoTren = doc.createElement("tren");
nodoTren.setAttribute("id", String.valueOf(t.getCodTren()));
Element modelo = doc.createElement("modelo");
modelo.setTextContent(String.valueOf(t.getModelo()));
nodoTren.appendChild(modelo);
Element anyo = doc.createElement("anyo_incorporacion");
anyo.setTextContent(String.valueOf(t.getFechaIncorporacion().getYear()));
nodoTren.appendChild(anyo);
Element empresa = doc.createElement("empresa_constructora");
empresa.setTextContent(t.getEmpresaConstructora());
nodoTren.appendChild(empresa);
Element cochera = doc.createElement("cod_cochera");
cochera.setTextContent(String.valueOf(t.getCodCochera()));
nodoTren.appendChild(cochera);
Element nodoLinea = doc.createElement("linea");
nodoLinea.setAttribute("id_linea", String.valueOf(t.getLinea().getCodLinea()));
Element nombreL = doc.createElement("nombre_l");
nombreL.setTextContent(t.getLinea().getNombreLargo());
nodoLinea.appendChild(nombreL);
Element nodoColor = doc.createElement("color");
nodoColor.setAttribute("id", String.valueOf(t.getLinea().getColor().getCodColor()));
nodoColor.setAttribute("cod_hex", String.valueOf(t.getLinea().getColor().getCodHexadecimal()));
nodoLinea.appendChild(nodoColor);
nodoTren.appendChild(nodoLinea);
nodoTrenes.appendChild(nodoTren);
}
// 3. Escribir el documento en un archivo físico
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// Esto es para que el XML salga bonito y tabulado (indentado), no todo en una línea
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(rutaSalida);
transformer.transform(source, result);
}catch(Exception e) {
throw new RedMetroException("Error al generar el XML en: " + rutaSalida, e);
}
}
}
@@ -0,0 +1,82 @@
package es.madrid.redmetro.ss.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.gestores.GestorConfiguracion;
import es.madrid.redmetro.ss.model.Cochera;
public class LecturaCSV {
// Clase interna para agrupar el número de operación y la cochera
public static class RegistroCSV{
public int operacion;
public Cochera cochera;
public RegistroCSV(int operacion, Cochera cochera) {
this.operacion = operacion;
this.cochera = cochera;
}
}
public static List<RegistroCSV> leerCocheras() throws RedMetroException{
Path path = Path.of(GestorConfiguracion.getRutaCocherasCSV());
String separador = GestorConfiguracion.getSeparadorCSV();
List<RegistroCSV> lista = new ArrayList<>();
try {
List<String> lineas = Files.readAllLines(path);
for(int i = 1; i < lineas.size(); i++) {
String linea = lineas.get(i).trim();
if (linea.isEmpty()) continue;
String[] campos = linea.split(separador);
int operacion = Integer.parseInt(campos[0].trim());
int codCochero = Integer.parseInt(campos[1].trim());
int deposito = Integer.parseInt(campos[2].trim());
String nombre = campos[3].trim();
String direccion = campos[4].trim();
Cochera c = new Cochera(codCochero, nombre, direccion, deposito);
lista.add(new RegistroCSV(operacion, c));
}
} catch (IOException e) {
throw new RedMetroException("Error al leer el archivo CSV " + e);
}
return lista;
}
}
@@ -0,0 +1,58 @@
package es.madrid.redmetro.ss.util;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import es.madrid.redmetro.ss.exception.RedMetroException;
import es.madrid.redmetro.ss.gestores.GestorConfiguracion;
import es.madrid.redmetro.ss.model.Tren;
public class LecturaXML {
public static List<Tren> leerTrenes() throws RedMetroException{
List<Tren> listaTrenes = new ArrayList<>();
String ruta = GestorConfiguracion.getRutaTrenesXML();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// 1. Cargamos el archivo directamente con new File() como hablamos
Document doc = db.parse(new File(ruta));
// 2. normalize() fusiona textos fragmentados por saltos de línea
doc.getDocumentElement().normalize();
NodeList listaNodos = doc.getElementsByTagName("tren");
for(int i = 0; i < listaNodos.getLength(); i++) {
Element elemento = (Element) listaNodos.item(i);
int id = Integer.parseInt(elemento.getAttribute("id"));
String modelo = elemento.getElementsByTagName("modelo").item(0).getTextContent();
String anyoString = elemento.getElementsByTagName("anyo_incorporacion").item(0).getTextContent();
String empresa = elemento.getElementsByTagName("empresa_constructora").item(0).getTextContent();
int codCochera = Integer.parseInt(elemento.getElementsByTagName("cod_cochera").item(0).getTextContent());
int idLinea = Integer.parseInt(elemento.getElementsByTagName("id_linea").item(0).getTextContent());
LocalDate fecha = LocalDate.parse(anyoString + "-01-01");
Tren tren = new Tren(id, modelo, empresa, fecha, codCochera, idLinea);
listaTrenes.add(tren);
}
}catch(Exception e) {
throw new RedMetroException("Error al leer el XML de trenes" + ruta, e);
}
return listaTrenes;
}
}