· 8 years ago · May 07, 2018, 02:30 AM
1import java.io.InputStreamReader;
2import java.sql.*;
3import java.util.LinkedList;
4import java.io.BufferedReader;
5import java.io.FileReader;
6import java.util.Scanner;
7
8public class Diagnostico {
9
10 private final String DATAFILE = "data/disease_data.data";
11 private Connection conn = null;
12 private String nombreBD = "diagnostico";
13
14 private class Codigo {
15 private String vocabulario;
16 private String codigo;
17 public Codigo(String codigo,String vocabulario) {
18 this.vocabulario = vocabulario;
19 this.codigo = codigo;
20 }
21 public String getVocabulario() {
22 return vocabulario;
23 }
24 public String getCodigo() {
25 return codigo;
26 }
27 }//class codigo
28
29 private class Sintoma {
30 private String codigoSintoma;
31 private String semanticaTipo;
32 private String sintoma;
33 public Sintoma(String sintoma,String codigoSintoma,String semanticaTipo) {
34 this.codigoSintoma = codigoSintoma;
35 this.semanticaTipo = semanticaTipo;
36 this.sintoma = sintoma;
37 }
38 public String getCodigoSintoma() {
39 return codigoSintoma;
40 }
41 public String getSemanticaTipo() {
42 return semanticaTipo;
43 }
44 public String getSintoma() {
45 return sintoma;
46 }
47 }//class sintoma
48
49 private class Enfermedad {
50 private LinkedList<Codigo> codigo;
51 private LinkedList<Sintoma> sintoma;
52 private String nombre;
53
54 public Enfermedad (String nombre,LinkedList<Codigo> codigo,LinkedList<Sintoma>sintoma) {
55 this.nombre= nombre;
56 this.codigo = codigo;
57 this.sintoma = sintoma;
58 }
59 public String getNombre() {
60 return nombre;
61 }
62 public LinkedList<Codigo> getCodigo() {
63 return codigo ;
64 }
65 public LinkedList<Sintoma> getSintoma() {
66 return sintoma;
67 }
68 }
69 private void showMenu() {
70
71 int option = -1;
72 do {
73 System.out.println("Bienvenido a sistema de diagnóstico\n");
74 System.out.println("Selecciona una opción:\n");
75 System.out.println("\t1. Creación de base de datos y carga de datos.");
76 System.out.println("\t2. Realizar diagnóstico.");
77 System.out.println("\t3. Listar sÃntomas de una enfermedad.");
78 System.out.println("\t4. Listar enfermedades y sus códigos asociados.");
79 System.out.println("\t5. Listar sÃntomas existentes en la BD y su tipo semántico.");
80 System.out.println("\t6. Mostrar estadÃsticas de la base de datos.");
81 System.out.println("\t7. Salir.");
82 try {
83 option = readInt();
84 switch (option) {
85 case 1:
86 crearBD();
87 break;
88 case 2:
89 realizarDiagnostico();
90 break;
91 case 3:
92 listarSintomasEnfermedad();
93 break;
94 case 4:
95 listarEnfermedadesYCodigosAsociados();
96 break;
97 case 5:
98 listarSintomasYTiposSemanticos();
99 break;
100 case 6:
101 mostrarEstadisticasBD();
102 break;
103 case 7:
104 exit();
105 break;
106 }
107 } catch (Exception e) {
108 System.err.println("Opción introducida no válida!");
109 }
110 } while (option != 7);
111 exit();
112 }
113
114 private void exit() {
115 if (conn != null){
116 try{
117 if(!conn.isClosed())
118 conn.close();
119 }
120 catch (Exception e){
121 System.out.println("No se pudo desconectar de la base de datos");
122 }
123 }
124 System.out.println("Saliendo.. ¡hasta otra!");
125 System.exit(0);
126 }
127
128 private boolean existeDB() {
129 boolean exist = false;
130 try{
131 Statement st = conn.createStatement();
132 String sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + this.nombreBD + "'";
133 ResultSet rs = st.executeQuery(sql);
134 if (rs.next()) {
135 exist = true;
136 }
137 }catch (SQLException ex) {
138 exist = false;
139 } return exist;
140 }
141
142 private void conectar() throws Exception {
143 String drv ="com.mysql.jdbc.Driver";
144 Class.forName(drv).newInstance();
145
146 String serverAddress = "localhost:3306";
147 String user = "bddx";
148 String pwd = "bddx_pwd";
149 String url = "jdbc:mysql://" + serverAddress + "/";
150 conn = DriverManager.getConnection(url, user, pwd);
151 if (!conn.isClosed()){
152 System.out.println("¡Conectado a la base de datos!");
153 }
154 }
155
156 private void crearBD() {
157 try{
158 if(conn == null){
159 this.conectar();
160 }
161 }
162 catch(Exception e) {
163 System.out.println(e);
164 }
165 try{
166 if(!existeDB()){
167 Statement stmt = conn.createStatement();
168 System.out.println("Creando diagnostico...");
169 String qs= "CREATE DATABASE diagnostico";
170 stmt.executeUpdate(qs);
171 conn.setCatalog(nombreBD);
172 System.out.println("La base de datos diagnostico ha sido creada.");
173 Statement stmt1= conn.createStatement();
174 stmt1.executeUpdate("CREATE TABLE source (source_id INT UNIQUE AUTO_INCREMENT, name VARCHAR(255))");
175 Statement stmt2= conn.createStatement();
176 stmt2.executeUpdate("CREATE TABLE code (source_id INT, code VARCHAR(255), PRIMARY KEY (code), FOREIGN KEY (source_id)"
177 + " REFERENCES source (source_id))");
178 Statement stmt3= conn.createStatement();
179 stmt3.executeUpdate("CREATE TABLE disease (disease_id INT UNIQUE AUTO_INCREMENT, name VARCHAR(255))");
180 Statement stmt4= conn.createStatement();
181 stmt4.executeUpdate("CREATE TABLE disease_has_code (source_id INT, code VARCHAR(255),disease_id INT, FOREIGN KEY (disease_id)"
182 + " REFERENCES disease (disease_id), FOREIGN KEY (code) REFERENCES code (code), FOREIGN KEY (source_id) "
183 + "REFERENCES code (source_id))");
184 Statement stmt6= conn.createStatement();
185 stmt6.executeUpdate("CREATE TABLE semantic_type (semantic_type_id INT UNIQUE AUTO_INCREMENT, cui VARCHAR(45))");
186 Statement stmt5= conn.createStatement();
187 stmt5.executeUpdate("CREATE TABLE symptom (cui VARCHAR(25), name VARCHAR(255), semantic_type_id INT, PRIMARY KEY (cui),"
188 + " FOREIGN KEY (semantic_type_id) REFERENCES semantic_type (semantic_type_id))");
189 Statement stmt7= conn.createStatement();
190 stmt7.executeUpdate("CREATE TABLE disease_symptom (disease_id INT, cui VARCHAR(25), FOREIGN KEY (disease_id) REFERENCES disease (disease_id),"
191 + " FOREIGN KEY (cui) REFERENCES symptom (cui))");
192 LinkedList<String> lista = readData();
193 for(String enfermedades: lista){
194 String arreglado = enfermedades.replaceAll("'", "''"); //cambiamos los apostrofes por doble apostrofe para que no haya problemas al insertar
195 String [] cadena= arreglado.split("="); // separamos enfermedad[0] y sintomas[1]
196 String [] cadEnf = cadena[0].split(":"); // separamos enfermedad[0] de codigo y vocabulario[1]
197 String nomEnf= cadEnf[0];
198 String [] cadCodigos= cadEnf[1].split(";"); //separamos los codigos
199 LinkedList<Codigo> lisCod = new LinkedList<>();
200 for(int i=0;i<cadCodigos.length; i++){
201 String [] codigo= cadCodigos[i].split("@"); // separamos codigo[0] y vocabulario[1]
202 String cod= codigo[0]; //di si a los comentarios!
203 String voc= codigo[1];
204 Codigo cd= new Codigo (cod,voc); //creamos un nuevo codigo ( codigo, vocabulario)
205 lisCod.add(cd);
206 }
207 String [] cadSint= cadena[1].split(";"); //separamos los sintomas
208 LinkedList<Sintoma> lisSint = new LinkedList<>();
209 for(int i=0; i<cadSint.length; i++){
210 String [] sintomas= cadSint[i].split(":"); //separamos sintoma, codigoSintoma y vocabularioSint
211 String sint=sintomas[0];
212 String codSint= sintomas[1];
213 String vocSint= sintomas[2];
214 Sintoma st= new Sintoma (sint, codSint, vocSint); // creamos nuevo Sintoma(sintoma, codigoSintoma, vocabulario)
215 lisSint.add(st);
216 }
217 Enfermedad enfermito = new Enfermedad(nomEnf,lisCod,lisSint);
218 conn.setAutoCommit(false);
219 //insercion datos Tabla SOURCE
220 String sqlSou= "INSERT INTO source (name) VALUES ('"+enfermito.getCodigo().element().getVocabulario()+"')";
221 stmt1.executeUpdate(sqlSou,Statement.RETURN_GENERATED_KEYS);
222 ResultSet souKey = stmt1.getGeneratedKeys();
223 souKey.next();
224 //insercion datos Tabla CODE
225 stmt2.executeUpdate("INSERT INTO code (source_id, code) VALUES ('"+souKey.getInt(1)+"','"+enfermito.getCodigo().element().getCodigo()+"')");
226 ResultSet codeKey = stmt2.executeQuery("SELECT code FROM code");
227 codeKey.next();
228 //insercion datos Tabla DISEASE
229 System.out.println(enfermito.getNombre().toString());
230 // String prueba = enfermito.getNombre().replaceAll("'","''");
231 String sqlDis= "INSERT INTO disease (name) VALUES ('"+enfermito.getNombre()+"')"; //esta es la que provoca el error y ni idea de porque
232 stmt3.executeUpdate(sqlDis, Statement.RETURN_GENERATED_KEYS);
233 ResultSet disKey = stmt3.getGeneratedKeys();
234 disKey.next();
235 //insercion datos Tabla DISEASE_HAS_CODE
236 stmt4.executeUpdate("INSERT INTO disease_has_code (source_id, code,disease_id) VALUES ('"+souKey.getInt(1)+"','"+codeKey.getString(1)+""
237 + "','"+disKey.getInt(1)+"')");
238 //insercion datos Tabla semantic_type
239 String sqlSem= "INSERT INTO semantic_type(cui) VALUES ('"+enfermito.getSintoma().element().getSemanticaTipo()+"')";
240 stmt6.executeUpdate(sqlSem, Statement.RETURN_GENERATED_KEYS);
241 ResultSet semKey = stmt6.getGeneratedKeys();
242 semKey.next();
243 //insercion datos Tabla symptom
244 stmt5.executeUpdate("INSERT INTO symptom (cui,name,semantic_type_id) VALUES ('"+enfermito.getSintoma().element().getCodigoSintoma()+"',"
245 + "'"+enfermito.getSintoma().element().getSintoma()+"','"+semKey.getInt(1)+"')");
246 ResultSet sympKey = stmt2.executeQuery("SELECT cui FROM symptom");
247 sympKey.next();
248 //insercion datos Tabla disease_symptom
249 stmt7.executeUpdate("INSERT INTO disease_symptom (disease_id, cui) VALUES ('"+disKey.getInt(1)+"','"+sympKey.getString(1)+"')");
250 souKey.close();
251 codeKey.close();
252 disKey.close();
253 semKey.close();
254 sympKey.close();
255 }//fin insertar
256 //Ahora procedemos a cerrar los Statement
257 stmt1.close();
258 stmt2.close();
259 stmt3.close();
260 stmt4.close();
261 stmt5.close();
262 stmt6.close();
263 stmt7.close();
264 }
265 else{
266 Scanner scanner = new Scanner(System.in);
267 System.out.println("Le informamos de la existencia de diagnostico, ¿desea borrarla?");
268 String condicion = scanner.nextLine();
269 if(condicion.equals("Si")|| condicion.equals("si")){
270 Statement stmt = conn.createStatement();
271 System.out.println("Borrando diagnostico...");
272 String qs= "DROP DATABASE diagnostico";
273 stmt.executeUpdate(qs);
274 System.out.println("Borrado completado.");
275 System.out.println("Creando la base de datos de nuevo.");
276 stmt.close();
277 this.crearBD();
278 }
279 }//fin existeBD
280 conn.commit();
281 }//fin try
282 catch (Exception e) {
283 try {
284 conn.rollback();
285 } catch (SQLException e1) {
286 System.out.println(e);
287 }
288 System.out.println(e);
289 }//fin catch
290 finally{
291 try {
292 conn.setAutoCommit(true);
293 } catch (SQLException e) {
294 System.out.println(e);
295 }
296 }//fin finally
297 //
298 // String base = "CREATE SCHEMA if not exists diagnostico;";
299 // String source = "CREATE TABLE diagnostico."
300 // + "source (source_id INT NULL,"
301 // + " name VARCHAR(255) NULL,PRIMARY KEY (source_id));";
302 // String code = "CREATE TABLE diagnostico."
303 // + "code (code VARCHAR(255) NOT NULL, "
304 // + "source_id INT NULL,PRIMARY KEY (code));";
305 // String disease_has_code = "";
306 // String disease = "";
307 // String disease_symptom = "";
308 // String symptom = "";
309 // String symptom_semantic_type = "";
310 // String semantic_type = "";
311 // try{
312 // if (conn == null || conn.isClosed())
313 // this.conectar();
314 // }
315 // catch(Exception e){
316 //
317 // }
318 // Statement st = conn.createStatement();
319 // // Comprobamos si existe la base de datos
320 // ResultSet rs = st.executeQuery("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'diagnostico' ");
321 // // Si no existe la creamos
322 // if(rs == null || !rs.next()){
323 // st.executeUpdate(base);
324 // }
325 // else {
326 // //Preguntamos si se quiere borrar la base
327 // Scanner sc = new Scanner(System.in);
328 // System.out.println("¿Quieres borrar la base de datos? S/N");
329 // String respuesta = sc.next();
330 // sc.close();
331 // // Se crea de nuevo
332 // if (respuesta.equals("S")){
333 // st.executeUpdate("DROP DATABASE diagnostico;");
334 // this.crearBD();
335 // }
336 // }
337 }
338
339 private void realizarDiagnostico() {
340 try {
341 if (conn == null || conn.isClosed())
342 this.conectar();
343 }
344 catch (Exception e) {
345 System.out.println(e);
346 }
347 /* Lo que tenga que hacer */
348
349 }
350
351 private void listarSintomasEnfermedad() {
352 try {
353 if (conn == null || conn.isClosed())
354 this.conectar();
355 }
356 catch (Exception e) {
357 System.out.println(e);
358 }
359 /* Lo que tenga que hacer */
360
361 }
362
363 private void listarEnfermedadesYCodigosAsociados() {
364 try {
365 if (conn == null || conn.isClosed())
366 this.conectar();
367 }
368 catch (Exception e) {
369 System.out.println(e);
370 }
371 /* Lo que tenga que hacer */
372
373 }
374
375 private void listarSintomasYTiposSemanticos() {
376 try {
377 if (conn == null || conn.isClosed())
378 this.conectar();
379 }
380 catch (Exception e) {
381 System.out.println(e);
382 }
383 /* Lo que tenga que hacer */
384
385 }
386
387 private void mostrarEstadisticasBD() {
388 try {
389 if (conn == null || conn.isClosed())
390 this.conectar();
391 }
392 catch (Exception e) {
393 System.out.println(e);
394 }
395 /* Lo que tenga que hacer */
396
397 }
398
399 /**
400 * Método para leer números enteros de teclado.
401 *
402 * @return Devuelve el número leÃdo.
403 * @throws Exception
404 * Puede lanzar excepción.
405 */
406 private int readInt() throws Exception {
407 try {
408 System.out.print("> ");
409 return Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
410 } catch (Exception e) {
411 throw new Exception("Not number");
412 }
413 }
414
415 /**
416 * Método para leer cadenas de teclado.
417 *
418 * @return Devuelve la cadena leÃda.
419 * @throws Exception
420 * Puede lanzar excepción.
421 */
422 private String readString() throws Exception {
423 try {
424 System.out.print("> ");
425 return new BufferedReader(new InputStreamReader(System.in)).readLine();
426 } catch (Exception e) {
427 throw new Exception("Error reading line");
428 }
429 }
430
431 /**
432 * Método para leer el fichero que contiene los datos.
433 *
434 * @return Devuelve una lista de String con el contenido.
435 * @throws Exception
436 * Puede lanzar excepción.
437 */
438 private LinkedList<String> readData() throws Exception {
439 LinkedList<String> data = new LinkedList<String>();
440 BufferedReader bL = new BufferedReader(new FileReader(DATAFILE));
441 while (bL.ready()) {
442 data.add(bL.readLine());
443 }
444 bL.close();
445 return data;
446 }
447
448 public static void main(String args[]) throws Exception {
449
450 new Diagnostico().showMenu();
451 }
452}