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