· 11 years ago · Jun 22, 2015, 08:21 AM
1package Modelo;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileNotFoundException;
6import java.io.FileOutputStream;
7import java.io.IOException;
8import java.io.InputStream;
9import java.io.OutputStream;
10import java.sql.Connection;
11import java.sql.DriverManager;
12import java.sql.PreparedStatement;
13import java.sql.ResultSet;
14import java.sql.SQLException;
15import java.util.Properties;
16
17import vistas.Vista_global;
18import vistas.Vista_login;
19import vistas.Vista_mod;
20import vistas.Vista_singin;
21import controlador.Controlador;
22
23public class bbdd {
24
25 private Vista_global vistaGlobal;
26 private Controlador controlador;
27 private Vista_login vista_login;
28 private Vista_singin vista_singin;
29 private Vista_mod vista_mod;
30
31 public Vista_mod getVista_mod() {
32 return vista_mod;
33 }
34
35 public void setVista_mod(Vista_mod vista_mod) {
36 this.vista_mod = vista_mod;
37 }
38
39 private File config;
40 private Properties propiedades;
41 private InputStream entrada = null;
42
43 private String bd;
44 private String user;
45 private String password;
46 private String ubicacion;
47 private String driver;
48 private String url;
49 private Connection conexion;
50 private int nIntentos = 3;
51
52 /**
53 * CONSTRUCTOR: establece el nombre del archivo con los datos de
54 * configuración Llama a método setDatosAcceso()
55 *
56 * @param archivo
57 * : objeto File.
58 * @throws FileNotFoundException
59 * @throws SQLException
60 * @throws ClassNotFoundException
61 */
62 public bbdd(File archivo) throws FileNotFoundException, ClassNotFoundException, SQLException {
63
64 config = archivo;
65 setDatosAcceso();
66 conexionON();
67
68 }
69
70 /**
71 * Establece la conexión con la base de datos.
72 *
73 * @throws ClassNotFoundException
74 * @throws SQLException
75 */
76 public void conexionON() throws ClassNotFoundException, SQLException {
77
78 Class.forName("com.mysql.jdbc.Driver");
79 conexion = DriverManager.getConnection(url, user, password);
80
81 }
82
83 /**
84 * Cierra la conexión con la base de datos.
85 */
86 public void conexionOFF() {
87 try {
88 conexion.close();
89 } catch (SQLException e) {
90 e.printStackTrace();
91 }
92 }
93
94 /* **************************** */
95 /* MÉTODO SETTER DE PROPIEDADES */
96 /* **************************** */
97
98 public void setVistaGlobal(Vista_global eVistaGlobal) {
99 vistaGlobal = eVistaGlobal;
100 }
101
102 public void setControlador(Controlador eControlador) {
103 controlador = eControlador;
104 }
105
106 public void setVista_login(Vista_login eVista_login) {
107 vista_login = eVista_login;
108 }
109
110 public void setVista_singin(Vista_singin vista_singin) {
111 this.vista_singin = vista_singin;
112 }
113
114 /*
115 * public void setVista_mod(Vista_mod eVista_mod) { vista_mod = eVista_mod;
116 * }
117 */
118
119 /**
120 * setDatosAcceso() establece los valores de las propiedades de acceso a la
121 * bbdd
122 *
123 * @throws FileNotFoundException
124 */
125 private void setDatosAcceso() throws FileNotFoundException {
126
127 entrada = new FileInputStream(config);
128 propiedades = new Properties();
129
130 try {
131 propiedades.load(entrada);
132 // Establecer valores de las propiedades de acceso a la bbdd.
133 bd = propiedades.getProperty("bd");
134 user = propiedades.getProperty("user");
135 password = propiedades.getProperty("password");
136 ubicacion = propiedades.getProperty("ubicacion");
137 driver = propiedades.getProperty("driver");
138 url = driver + ubicacion + bd;
139 } catch (IOException e1) {
140 vista_login.failConection();
141 }
142 }
143
144 /* ******************************************** */
145 /* MÉTODOS RELACIONADOS SELECT, INSERT Y UPDATE */
146 /* ******************************************** */
147
148 public void setLogeo(String eEmail, String ePassword) throws SQLException,
149 ClassNotFoundException {
150 if (eEmail.equals("") || ePassword.equals("")) {
151 vista_login.showMessage("No debes dejar ningun campo vacÃo");
152 } else {
153 try {
154
155 String select = "SELECT * FROM inventario.usuario WHERE email=? AND password=?";
156 PreparedStatement stmt = conexion.prepareStatement(select);
157 stmt.setString(1, eEmail);
158 stmt.setString(2, ePassword);
159 ResultSet resultados = stmt.executeQuery();
160
161 resultados.next();
162 if (ePassword.equals(resultados.getString("password"))) {
163
164 vista_login.irAlPrograma();
165 resultados.close();
166 stmt.close();
167 } else {
168 throw new Exception();
169 }
170 } catch (Exception e) {
171 nIntentos--;
172 if (nIntentos == 0) {
173 vista_login.cerrarApp();
174 } else {
175 vista_login.failLogin(nIntentos);
176
177 }
178 }
179 }
180 }
181
182 public void register(String name, String eEmail, String ePassword,
183 String passwordConfirm) throws ClassNotFoundException {
184
185
186 boolean cojemos;
187 String marcaEmail;
188
189 if (name.equals("") || ePassword.equals("") || eEmail.equals("")
190 || passwordConfirm.equals("")) {
191 vista_singin
192 .showMessage("Todos los campos son necesarios para completar el registro");
193
194 } else if (!ePassword.equals(passwordConfirm)) {
195 vista_singin
196 .showMessage("Las contraseñas deben coincidir para continuar con el registro");
197 } else {
198
199 cojemos = false;
200 marcaEmail = "";
201 for (int i = 0; i < eEmail.length(); i++) {
202 if (eEmail.charAt(i) == '@') {
203 cojemos = true;
204 }
205 if (cojemos == true) {
206 marcaEmail += eEmail.charAt(i);
207 }
208 }
209 if (cojemos == false) {
210 vista_singin
211 .showMessage("La estructura del email debe ser tunombre@tuservidor.es/com");
212
213 } else if (marcaEmail.equals("@hotmail.com")
214 || marcaEmail.equals("@hotmail.es")
215 || marcaEmail.equals("@gmail.com")
216 || marcaEmail.equals("@yahoo.com")) {
217
218 // SI TODO ESTA CORRECTO SE REGISTRA
219 System.out.println(eEmail);
220
221 try {
222
223 String comprobar = "SELECT * FROM inventario.usuario WHERE email=?";
224 PreparedStatement stmt = conexion
225 .prepareStatement(comprobar);
226 stmt.setString(1, eEmail);
227 ResultSet resultados = stmt.executeQuery();
228
229 resultados.next();
230 String texto = resultados.getString("email");
231 vista_singin
232 .showMessage("El email "
233 + texto
234 + " ya esta registrado en nuestra base de datos \n Utilize otro E-mail");
235
236 resultados.close();
237 stmt.close();
238
239 } catch (SQLException e1) {
240
241 // SI SE PRODUCE LA EXCEPCION SE GENERARA EL MENSAJE DE
242 // REGISTRO; SINO, SE DIRÃ QUE EL EMAIL YA ESTA REGISTRADO
243 // EN LA BBDD
244
245 String insercion = ("INSERT INTO inventario.usuario(nombre,password,email) VALUES ('"
246 + name + "','" + ePassword + "','" + eEmail + "')");
247 vista_singin.showMessage("El registro se ha completado");
248 vista_singin.desactivarVista();
249 vista_login.activarVista(vista_singin.getX(),
250 vista_singin.getY());
251
252 try {
253
254 PreparedStatement stmt2 = conexion
255 .prepareStatement(insercion);
256 stmt2.executeUpdate();
257
258 } catch (SQLException e) {
259
260 vista_singin
261 .showMessage("Fallo al registrarse en la base de datos");
262
263 }
264 }
265 } else {
266 vista_singin
267 .showMessage("Tu email debe ser de los siguientes dominios \n - hotmail.com \n - hotmail.es \n - gmail.com \n - yahoo.com");
268
269 }
270 }
271 }
272
273 public void getTabla(String eTabla) throws SQLException {
274
275 String tabla = "";
276
277 if (eTabla.equals("Usuarios")) {
278 tabla = "usuario";
279 } else if (eTabla.equals("Equipos")) {
280 tabla = "equipo";
281 } else if (eTabla.equals("Prestamos")) {
282 tabla = "reserva";
283 }
284
285
286 if (tabla.equals("usuario")) {
287
288 String select = "SELECT * FROM inventario." + tabla;
289 PreparedStatement stmt = conexion.prepareStatement(select);
290
291 ResultSet resultados = stmt.executeQuery();
292
293 while (resultados.next()) {
294
295 int id_usuario = resultados.getInt("id_usuario");
296
297 String nombre = resultados.getString("nombre");
298 String password = resultados.getString("password");
299
300 String email = resultados.getString("email");
301 vistaGlobal.recibirUsuario(id_usuario, nombre, password, email);
302 }
303
304 } else if (tabla.equals("equipo")) {
305
306 String select = "SELECT * FROM inventario." + tabla;
307 PreparedStatement stmt = conexion.prepareStatement(select);
308
309 ResultSet resultados = stmt.executeQuery();
310
311 while (resultados.next()) {
312 int id_equipo = resultados.getInt("id_equipo");
313 String placa_base = resultados.getString("placa_base");
314 int num_armario = resultados.getInt("num_armario");
315 vistaGlobal.recibirEquipo(id_equipo, placa_base, num_armario);
316 }
317
318 } else if (tabla.equals("reserva")) {
319 // vistaGlobal.recibirPrestamo(id_equipo, placa_base, armario,
320 // usuario, fecha_prestamo, fecha_devolucion);
321
322 // consulta para juntar las 3 tablas (equipo, usuario y reserva):
323 String select = "SELECT * FROM inventario.usuario user INNER JOIN inventario.reserva res ON user.id_usuario = res.id_usuario INNER JOIN inventario.equipo eq ON res.id = eq.id_equipo";
324
325 PreparedStatement stmt = conexion.prepareStatement(select);
326
327 ResultSet resultados = stmt.executeQuery();
328
329 while (resultados.next()) {
330
331 int id_equipo = resultados.getInt("id_equipo");
332 String placa_base = resultados.getString("placa_base");
333 int num_armario = resultados.getInt("num_armario");
334
335 int id_usuario = resultados.getInt("id_usuario");
336 String nombre = resultados.getString("nombre");
337
338 String fecha_inicio = resultados.getString("fecha_inicio");
339 String fecha_fin = resultados.getString("fecha_fin");
340
341 vistaGlobal.recibirPrestamo(id_equipo, placa_base, num_armario,
342 id_usuario, nombre, fecha_inicio, fecha_fin);
343 }
344
345 } else {
346
347 // ///////////////////////////////////////////
348 // ////////// MENSAJE DE ERROR ///////////////
349 // ///////////////////////////////////////////
350
351 }
352 }
353
354 public void enviarDatosArchivo() {
355 vista_mod.recibirDatosArchivo(user, password, bd, ubicacion, driver);
356 }
357
358 public void modificarDatosArchivo(String eUsuario, String ePassword,
359 String eBd, String eUbicacion, String eDriver) throws IOException {
360
361 OutputStream salida = new FileOutputStream(config);
362
363 propiedades.setProperty("bd", eBd);
364 propiedades.setProperty("user", eUsuario);
365 propiedades.setProperty("password", ePassword);
366 propiedades.setProperty("ubicacion", eUbicacion);
367 propiedades.setProperty("driver", eDriver);
368
369 propiedades.store(salida, "");
370
371 setDatosAcceso();
372
373 }
374
375 /**
376 * Modifica, elimina o incorpora registros en tabla "usuario"
377 *
378 * @param orden
379 * @param id_usuario
380 * @param nombre
381 * @param password
382 * @param email
383 * @throws SQLException
384 */
385 public void modificacionDatosUsuario(String orden, int id_usuario,
386 String nombre, String password, String email) throws SQLException {
387
388 if (orden.equals("modificar")) {
389
390 String select = "UPDATE inventario.usuario SET nombre = ?, password= ?, email= ? WHERE id_usuario = ?";
391 PreparedStatement stmt = conexion.prepareStatement(select);
392 stmt.setString(1, nombre);
393 stmt.setString(2, password);
394 stmt.setString(3, email);
395 stmt.setInt(4, id_usuario);
396 int resultados = stmt.executeUpdate();
397
398 } else if (orden.equals("insertar")) {
399
400 String select = "INSERT INTO inventario.usuario (nombre, password, email) VALUES (?, ?, ?)";
401 PreparedStatement stmt = conexion.prepareStatement(select);
402 stmt.setString(1, nombre);
403 stmt.setString(2, password);
404 stmt.setString(3, email);
405
406 int resultados = stmt.executeUpdate();
407 } else if (orden.equals("eliminar")) {
408
409 String select = "DELETE FROM inventario.usuario WHERE id_usuario=?";
410 PreparedStatement stmt = conexion.prepareStatement(select);
411 stmt.setInt(1, id_usuario);
412
413 int resultados = stmt.executeUpdate();
414
415 }
416
417 }
418
419 /**
420 * Modifica, elimina o incorpora registros en tabla "reserva"
421 *
422 * @param orden
423 * @param id_equipo
424 * @param placa_base
425 * @param armario
426 * @param usuario
427 * @param fecha_prestamo
428 * @param fecha_devolucion
429 * @throws SQLException
430 */
431 public void modificacionDatosPrestamos(String orden, int id_equipo,
432 String placa_base, int armario, int id_usuario, String usuario,
433 String fecha_prestamo, String fecha_devolucion) throws SQLException {
434
435 /*
436 * id_equipo placa_base armario usuario - id_usuario fecha préstamo
437 * fecha devolucion
438 */
439 if (orden.equals("modificar")) {
440 ResultSet idUser;
441 try {
442 // 1ª Buscar el id del usuario por si hubiera cambiado y
443 // asociarlo a la reserva.
444 String selectUser = "SELECT id_usuario FROM inventario.usuario WHERE nombre= ?";
445 PreparedStatement statementUser = conexion
446 .prepareStatement(selectUser);
447 statementUser.setString(1, usuario);
448 idUser = statementUser.executeQuery();
449 idUser.next();
450 id_usuario = idUser.getInt("id_usuario");
451 } catch (SQLException e) {
452 e.printStackTrace();
453 }
454
455 // Modificar en tabla reservas el id_equipo, el id_usuario,
456 // fecha_inicio (fecha_prestamo), fecha_fin (fecha_devolucion)
457
458 String update1 = "UPDATE inventario.reserva SET id_usuario= ?, id= ?, fecha_inicio= ?, fecha_fin=? WHERE id_usuario = "
459 + id_usuario + " AND id = " + id_equipo + " AND fecha_inicio = " + fecha_prestamo;
460 PreparedStatement stmt = conexion.prepareStatement(update1);
461 stmt.setInt(1, id_usuario);
462 stmt.setInt(2, id_equipo);
463 stmt.setString(3, fecha_prestamo);
464 stmt.setString(4, fecha_devolucion);
465 int resultados = stmt.executeUpdate();
466
467 } else if (orden.equals("insertar")) {
468
469 String insert1 = "INSERT INTO inventario.reserva (id_usuario, id, fecha_inicio, fecha_fin) VALUES (?, ?, ?, ?)";
470 PreparedStatement stmt2 = conexion.prepareStatement(insert1);
471 stmt2.setInt(1, id_usuario);
472 stmt2.setInt(2, id_equipo);
473 stmt2.setString(3, fecha_prestamo);
474 stmt2.setString(4, fecha_devolucion);
475
476 ResultSet resultados = stmt2.executeQuery();
477
478 }
479
480 }
481
482 /**
483 * Modifica, elimina o incorpora registros en tabla "equipo"
484 *
485 * @param orden
486 * @param id_equipo
487 * @param placa_base
488 * @param armario
489 * @throws SQLException
490 */
491 public void modificacionDatosEquipo(String orden, int id_equipo,
492 String placa_base, int armario) throws SQLException {
493
494
495 if (orden.equals("modificar")) {
496
497 String select = "UPDATE inventario.equipo SET placa_base= ?, num_armario= ? WHERE id_equipo = ?";
498 PreparedStatement stmt = conexion.prepareStatement(select);
499 stmt.setString(1, placa_base);
500 stmt.setInt(2, armario);
501 stmt.setInt(3, id_equipo);
502 int resultados = stmt.executeUpdate();
503
504 } else if (orden.equals("insertar")) {
505
506 String select = "INSERT INTO inventario.equipo (id, placa_base, num_armario) VALUES (?, ?, ?)";
507 PreparedStatement stmt = conexion.prepareStatement(select);
508 stmt.setInt(1, id_equipo);
509 stmt.setString(2, placa_base);
510 stmt.setInt(3, armario);
511
512 int resultados = stmt.executeUpdate();
513
514 } else if (orden.equals("eliminar")) {
515 String select = "DELETE FROM inventario.equipo WHERE id_equipo=?";
516 PreparedStatement stmt = conexion.prepareStatement(select);
517 stmt.setInt(1, id_equipo);
518
519 int resultados = stmt.executeUpdate();
520
521 }
522 }
523
524}