Advertisement
Guest User

Untitled

a guest
Jun 2nd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.57 KB | None | 0 0
  1. package aplivalidarusuarios;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.EOFException;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.ObjectInputStream;
  11. import java.io.ObjectOutputStream;
  12. import java.util.Scanner;
  13. import java.util.Calendar;
  14. import java.util.ArrayList;
  15.  
  16. public class ApliValidarUsuarios {
  17.  
  18.     public static Scanner sc = new Scanner(System.in);
  19.    
  20.     public static void main(String[] args) {
  21.        
  22.         // Programación en JAVA
  23.         // Práctica bloque 6: lectura y escritura de ficheros
  24.         // Realizado por Rubén Segura Romo, 1º DAW
  25.        
  26.        
  27.         //En el siguiente menú muestro las diversas opciones de trabajo
  28.         //del programa y ejecuto los métodos que correspondan a cada acción
  29.        
  30.        
  31.         int opcion;
  32.         boolean fin = false;
  33.        
  34.         do{
  35.             opcion = menu();
  36.             switch(opcion){
  37.                 case 1:
  38.                         darAltaUsuario();
  39.                                                 break;
  40.                 case 2:
  41.                         mostrarUsuarios();
  42.                         break;
  43.                 case 3:
  44.                         entrarAlSistema();
  45.                         break;
  46.                 case 4:
  47.                         mostrarLogAutorizados();
  48.                         break;
  49.                 case 5:
  50.                         mostrarLogNoAutorizados();
  51.                         break;
  52.                 case 6:
  53.                         System.out.println("");
  54.                         System.out.println("**               ¡Hasta otra!                **");
  55.                         System.out.println("** Ha finalizado correctamente la aplicación **");
  56.                         fin = true;
  57.             }
  58.         }while(!fin);
  59.     }
  60.    
  61.     public static void darAltaUsuario(){
  62.         //Voy a utilizar Objetos de la clase usuario para darlos de alta
  63.         FileOutputStream fos = null;
  64.         ObjectOutputStream oos = null;
  65.         String user="";
  66.         String password="";
  67.         ArrayList<String> us = new ArrayList<String>();
  68.         Usuario u = null;
  69.         // Con los booleanos voy a controlar cuando us usuario o contraseña son válidos o no
  70.         boolean usu = false;
  71.         boolean pass = false;
  72.     try{
  73.             fos = new FileOutputStream("/Usuario/usuarios.bin",true);
  74.             oos = new ObjectOutputStream(fos);
  75.             System.out.println("-- Se procede a la creación de un nuevo usuario -- ");
  76.             do{
  77.                 System.out.print("-- Introduce nombre de usuario: ");
  78.                 user = sc.nextLine();
  79.                 if(us.contains(user)){
  80.                     System.out.println("¡El usuario ya existe en el sistema!");
  81.                 }else if(user.length() < 8 && user.toLowerCase().charAt(0) >= 'a' && user.toLowerCase().charAt(0) <= 'z' ){
  82.                     System.out.println("¡Usuario no válido!");
  83.                     System.out.println("Compruebe que su contraseña tiene un longitud mínima de 8 caracteres alfanuméricos");
  84.                 }else{
  85.                     //si ha pasado todos los filtros digo que el usuario es válido y además
  86.                     //voy a guardar el usuario en un arraylist para luego utilizarlo como filtro
  87.                     //al añadir nuevos usuario
  88.                     usu = true;
  89.                     us.add(user);
  90.                 }
  91.             }while(usu == false); //Con la contraseña sigo el mismo proceso que para el usuairo
  92.             do{
  93.                 System.out.print("-- Introduce contraseña: ");
  94.                 password = sc.nextLine();
  95.                 if(password.length() < 8){
  96.                     System.out.println("¡Contraseña no válida!");
  97.                     System.out.println("Compruebe que su contraseña tiene un longitud mínima de 8 caracteres"
  98.                             + " alfanuméricos y al menos una letra es mayúscula, por favor");
  99.                 }else{
  100.                     pass = true;
  101.                 }
  102.             }while(pass == false);
  103.             //Finalmente creo un objeto con el usuario y contraseña y guardo el objeto.
  104.             u = new Usuario(user, password);
  105.             oos.writeObject(u);
  106.                 System.out.println("-- Usuario registrado correctamente --");
  107.         }catch(FileNotFoundException e){
  108.             System.err.println(e.getMessage());
  109.         }catch(IOException e){
  110.             System.err.println(e.getMessage());
  111.         }finally{
  112.             try{
  113.                 if(fos != null){
  114.                     fos.close();
  115.                 }
  116.                 if(oos != null){
  117.                     oos.close();
  118.                 }
  119.             }catch(IOException e){
  120.                 System.err.println(e.getMessage());
  121.             }
  122.         }
  123.     }
  124.    
  125.     public static void mostrarUsuarios(){
  126.         FileInputStream fis = null;
  127.         ObjectInputStream ois = null;
  128.         Usuario u = null;
  129.         try{
  130.             fis = new FileInputStream("/Usuario/usuarios.bin");
  131.             ois = new ObjectInputStream(fis);
  132.             System.out.println("-- USUARIOS REGISTRADOS EN EL SISTEMA --");
  133.             // Leo los objetos del fichero de usuarios.bin
  134.             // y muestro los usuarios mediante un metodo de la clase
  135.             // Usuario para obtener el nombre de usuario
  136.             while(true){
  137.                 u = (Usuario) ois.readObject();
  138.                 System.out.println("Usuario: " + u.getUser());
  139.             }
  140.         }catch(FileNotFoundException e){
  141.             System.err.println(e.getMessage());
  142.         }catch(EOFException e){
  143.             System.err.println(e.getMessage());
  144.         }catch(ClassNotFoundException e){
  145.             System.err.println(e.getMessage());
  146.         }catch(IOException e){
  147.             System.err.println(e.getMessage());
  148.         }finally{
  149.             try{
  150.                 if(fis != null){
  151.                     fis.close();
  152.                 }
  153.                 if(ois != null){
  154.                     ois.close();
  155.                 }
  156.             }catch(IOException e){
  157.                 System.err.println(e.getMessage());
  158.             }
  159.         }
  160.     }
  161.     public static void entrarAlSistema(){
  162.         //Para entrar al sistema voy a ir leyendo objetos y comparandolos
  163.         // con dos string(usuario y contraseña) que introducirá el usuario
  164.         FileInputStream fis = null;
  165.         ObjectInputStream ois = null;
  166.         Usuario u = null;
  167.         String user="";
  168.         String password="";
  169.         try{
  170.             fis = new FileInputStream("/Usuario/usuarios.bin");
  171.             ois = new ObjectInputStream(fis);
  172.             System.out.println("-- ACCESO AL SISTEMA --");
  173.             System.out.print("-- Introduce tu nombre de usuario: ");
  174.             user = sc.nextLine();
  175.             System.out.print("-- Introduce tu contraseña: ");
  176.             password = sc.nextLine();
  177.             while(true){ //voy leyendo el fichero usuario.bin y cargando objetos
  178.                 u = (Usuario) ois.readObject();
  179.                     if(u.getUser().equals(user) && u.getPassword().equals(password)){
  180.                         //si coinciden muestro el mensaje de bienvenida y llamo al método
  181.                         //que se encarga de crear el Log de usuario autorizados
  182.                         creaLogAutorizados(user);
  183.                         System.out.println("");
  184.                         System.out.println("**             ¡Bienvenido!              **");
  185.                         System.out.println("** Has accedido correctamente al sistema **");
  186.                     }else{
  187.                         //si no funciona muestro mensaje de error y llamo al método
  188.                         //que se encarga de crear el log de usuarios no autorizados
  189.                         System.out.println("¡ERROR! Acceso no permitido");
  190.                         creaLogNoAutorizados(user);
  191.                     }
  192.             }
  193.         }catch(FileNotFoundException e){
  194.             System.err.println(e.getMessage());
  195.         }catch(EOFException e){
  196.             System.err.println(e.getMessage());
  197.         }catch(ClassNotFoundException e){
  198.             System.err.println(e.getMessage());
  199.         }catch(IOException e){
  200.             System.err.println(e.getMessage());
  201.         }finally{
  202.             try{
  203.                 if(fis != null){
  204.                     fis.close();
  205.                 }
  206.                 if(ois != null){
  207.                     ois.close();
  208.                 }
  209.             }catch(IOException e){
  210.                 System.err.println(e.getMessage());
  211.             }
  212.         }
  213.     }
  214.  
  215.     public static void creaLogAutorizados(String u){
  216.         //Creo un fichero binario para el log al cual le viene como
  217.         //parámetro el nombre usuario utilizado al entrar en el sistema
  218.         FileOutputStream fos = null;
  219.         DataOutputStream dos = null;
  220.         // declaro las variables y las inicializo con los valores necesarios
  221.         // utilizando la clase Calendar
  222.         Calendar c = Calendar.getInstance();
  223.         int dia = c.get(Calendar.DAY_OF_MONTH);
  224.         int mes = c.get(Calendar.MONTH);
  225.         int anio = c.get(Calendar.YEAR);
  226.         int hora = c.get(Calendar.HOUR);
  227.         int minuto = c.get(Calendar.MINUTE);
  228.         int segundo = c.get(Calendar.SECOND);
  229.         try{
  230.             //voy escribiendo todos los datos en el fichero
  231.             fos = new FileOutputStream("/Log/logAccesoAutorizado.log",true);
  232.             dos = new DataOutputStream(fos);
  233.             dos.writeUTF(u);
  234.             dos.writeInt(dia);
  235.             dos.writeInt(mes);
  236.             dos.writeInt(anio);
  237.             dos.writeInt(hora);
  238.             dos.writeInt(minuto);
  239.             dos.writeInt(segundo);
  240.         }catch(FileNotFoundException e){
  241.             System.err.println(e.getMessage());
  242.         }catch(IOException e){
  243.             System.err.println(e.getMessage());
  244.         }finally{
  245.             try{
  246.                 if(fos != null){
  247.                     fos.close();
  248.                 }
  249.                 if(dos != null){
  250.                     dos.close();
  251.                 }
  252.             }catch(IOException e){
  253.                 System.err.println(e.getMessage());
  254.             }
  255.         }
  256.     }
  257.  
  258.     public static void creaLogNoAutorizados(String u){
  259.         //Exactamente igual que el método anterior solo que en otro fichero
  260.         FileOutputStream fos = null;
  261.         DataOutputStream dos = null;
  262.         Calendar c = Calendar.getInstance();
  263.         int dia = c.get(Calendar.DAY_OF_MONTH);
  264.         int mes = c.get(Calendar.MONTH);
  265.         int anio = c.get(Calendar.YEAR);
  266.         int hora = c.get(Calendar.HOUR);
  267.         int minuto = c.get(Calendar.MINUTE);
  268.         int segundo = c.get(Calendar.SECOND);
  269.         try{
  270.             fos = new FileOutputStream("/uLog/logAccesoNoAutorizado.log",true);
  271.             dos = new DataOutputStream(fos);
  272.             dos.writeUTF(u);
  273.             dos.writeInt(dia);
  274.             dos.writeInt(mes);
  275.             dos.writeInt(anio);
  276.             dos.writeInt(hora);
  277.             dos.writeInt(minuto);
  278.             dos.writeInt(segundo);
  279.         }catch(FileNotFoundException e){
  280.             System.err.println(e.getMessage());
  281.         }catch(IOException e){
  282.             System.err.println(e.getMessage());
  283.         }finally{
  284.             try{
  285.                 if(fos != null){
  286.                     fos.close();
  287.                 }
  288.                 if(dos != null){
  289.                     dos.close();
  290.                 }
  291.             }catch(IOException e){
  292.                 System.err.println(e.getMessage());
  293.             }
  294.         }
  295.     }
  296.  
  297.     public static void mostrarLogAutorizados(){
  298.         //Voy a ir leyendo el fichero binario
  299.         FileInputStream fis = null;
  300.         DataInputStream dis = null;
  301.         //declaro variables que utilizaré para recoger datos del fichero
  302.         String u;
  303.         int dia;
  304.         int mes;
  305.         int anio;
  306.         int hora;
  307.         int minuto;
  308.         int segundo;
  309.         try{
  310.             fis = new FileInputStream("/Log/logAccesoAutorizado.log");
  311.             dis = new DataInputStream(fis);
  312.             System.out.println("-- LOG DE ACCESOS AUTORIZADOS --");
  313.             while (true) {
  314.                 //Voy recorriendo el fichero y asignandole  a cada variable su valor
  315.                 //para finalmente mostrarlo por pantalla
  316.                 u = dis.readUTF();
  317.                 dia = dis.readInt();
  318.                 mes = dis.readInt();
  319.                 anio = dis.readInt();
  320.                 hora = dis.readInt();
  321.                 minuto = dis.readInt();
  322.                 segundo = dis.readInt();
  323.                 System.out.println("USUARIO: " + u + " FECHA: " + dia + "/" + mes +
  324.                                    "/" + anio + " HORA: " + hora + ":" + minuto + ":" + segundo);
  325.             }
  326.         }catch(FileNotFoundException e){
  327.             System.err.println(e.getMessage());
  328.         }catch(EOFException e){
  329.             System.err.println(e.getMessage());
  330.         }catch(IOException e){
  331.             System.err.println(e.getMessage());
  332.         }finally{
  333.             try{
  334.                 if(fis != null){
  335.                     fis.close();
  336.                 }
  337.                 if(dis != null){
  338.                     dis.close();
  339.                 }
  340.             }catch(IOException e){
  341.                 System.err.println(e.getMessage());
  342.             }
  343.         }
  344.     }
  345.  
  346.     public static void mostrarLogNoAutorizados(){
  347.         //Exactamente igual que el método anterior
  348.         FileInputStream fis = null;
  349.         DataInputStream dis = null;
  350.         String u;
  351.         int dia;
  352.         int mes;
  353.         int anio;
  354.         int hora;
  355.         int minuto;
  356.         int segundo;
  357.         try{
  358.             fis = new FileInputStream("/Log/logAccesoNoAutorizado.log");
  359.             dis = new DataInputStream(fis);
  360.             System.out.println("-- LOG DE ACCESOS NO AUTORIZADOS --");
  361.             while (true) {
  362.                 u = dis.readUTF();
  363.                 dia = dis.readInt();
  364.                 mes = dis.readInt();
  365.                 anio = dis.readInt();
  366.                 hora = dis.readInt();
  367.                 minuto = dis.readInt();
  368.                 segundo = dis.readInt();
  369.                 System.out.println("USUARIO: " + u + " FECHA: " + dia + "/" + mes +
  370.                                    "/" + anio + " HORA: " + hora + ":" + minuto + ":" + segundo);
  371.             }
  372.         }catch(FileNotFoundException e){
  373.             System.err.println(e.getMessage());
  374.         }catch(EOFException e){
  375.             System.err.println(e.getMessage());
  376.         }catch(IOException e){
  377.             System.err.println(e.getMessage());
  378.         }finally{
  379.             try{
  380.                 if(fis != null){
  381.                     fis.close();
  382.                 }
  383.                 if(dis != null){
  384.                     dis.close();
  385.                 }
  386.             }catch(IOException e){
  387.                 System.err.println(e.getMessage());
  388.             }
  389.         }
  390.     }
  391.    
  392.     public static int menu(){
  393.         int op;
  394.         System.out.println("***** MENÚ VALIDADOR DE USUARIOS *****");
  395.         System.out.println("1. Dar de alta un nuevo usuario");
  396.         System.out.println("2. Mostrar usuarios del sistema");
  397.         System.out.println("3. Entrar al sistema");
  398.         System.out.println("4. Mostrar el fichero 'LOG' de los usuarios autorizados");
  399.         System.out.println("5. Mostrar el fichero 'LOG' de los usuarios no autorizados");
  400.         System.out.println("6. Salir");
  401.         System.out.println("");
  402.         System.out.print("Elige una opción: ");
  403.         op = sc.nextInt();
  404.         sc.nextLine();
  405.         return op;
  406.     }
  407.    
  408. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement