brainfrz

LoginFileIO2

Mar 8th, 2016
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 36.01 KB | None | 0 0
  1. /**************************************************************************************************
  2.  * Program Name   : File IO
  3.  * Author         : Terry Weiss
  4.  * Date           : March 4, 2016
  5.  * Course/Section : CSC264 - 001
  6.  * Program Description: This program allows the user to input usernames and passwords from a file,
  7.  *     and allows users to login and logout of the system. Also, once a user is logged in, they
  8.  *     are able to change their password. Only 1 user may be logged in at any time. Before
  9.  *     shutting the program down, write to a file all of the usernames that were logged in. The
  10.  *     program menu allows users to login, logout, change the password, or quit the program. The
  11.  *     user must enter their current password before they're able to change it. If the old
  12.  *     password is incorrect, they will receive an error. When the user changes their password,
  13.  *     the file is updated. If the user tries to log in while a user is already logged in, they
  14.  *     also get an error. All logins are logged in a separate file.
  15.  *
  16.  * Methods:
  17.  * -------
  18.  * Main               - Runs the transcript program
  19.  * Menu Prompt        - Displays menu and prompts option
  20.  * Prompt Filename    - Prompts for a filename
  21.  * Check File Exists  - Checks if a file already exists
  22.  **************************************************************************************************/
  23.  
  24. import java.util.ArrayList;
  25. import java.util.Date;
  26. import java.io.File;
  27. import java.io.FileReader;
  28. import java.io.BufferedReader;
  29. import java.io.FileNotFoundException;
  30. import java.io.FileWriter;
  31. import java.io.BufferedWriter;
  32. import java.io.IOException;
  33.  
  34. public class FileIOTTW
  35. {
  36.     /**********************************************************************************************
  37.      *============================================================================================*
  38.      *|  Class variables                                                                         |*
  39.      *============================================================================================*
  40.      **********************************************************************************************/
  41.  
  42.  
  43.     /**********************************************************************************************
  44.      *============================================================================================*
  45.      *|  Class methods                                                                           |*
  46.      *============================================================================================*
  47.      **********************************************************************************************/
  48.  
  49.     /**********************************************************************************************
  50.      * Method Name    : FileIO - Main
  51.      * Author         : Terry Weiss
  52.      * Date           : March 4, 2016
  53.      * Course/Section : CSC264 - 001
  54.      * Program Description: This method asks the user for the filenames of their id/password file
  55.      *     and log file. They are then given a menu to login, logout, change their password or
  56.      *     exit.
  57.      *
  58.      * BEGIN Main
  59.      *     Dispaly title for file setup
  60.      *     Prompt login file
  61.      *     WHILE (login file doesn't exist)
  62.      *         Display error that file doesn't exist
  63.      *         Prompt login file
  64.      *     END WHILE
  65.      *     Load login file
  66.      *     Prompt log file
  67.      *     Init login info to an empty username and password
  68.      *     Clear screen
  69.      *     Get menu option
  70.      *     WHILE (option isn't to exit)
  71.      *         SWITCH (option)
  72.      *             CASE login:      If no login, set login info to result of attempted log in
  73.      *                 IF (no one is already logged in) THEN
  74.      *                     Set login info to result of attempted login
  75.      *                 ELSE
  76.      *                     Display message that no one's logged in
  77.      *                 END IF
  78.      *             CASE password:   Run change password method
  79.      *             CASE logout:     Set username and password to empty strings and announce logout
  80.      *             DEFAULT:         Throw unsupported operation exception
  81.      *         END SWITCH
  82.      *         Get new menu option
  83.      *         IF (new menu option is to exit) THEN
  84.      *             Save all password changes to the logins file and update log file
  85.      *         END IF
  86.      *     END WHILE
  87.      * END Main
  88.      **********************************************************************************************/
  89.     public static void main(String[] args) throws IOException
  90.     {
  91.         //Local constants
  92.         final int FILENAME_PROMPT_PAD = 21;     //Character padding for filename prompts
  93.         final int PROMPT_PAD          = 18;     //Character padding for menu prompt
  94.  
  95.         final int MENU_OPTION_LOGIN  = 1;       //Menu option for logging in
  96.         final int MENU_OPTION_PASSWD = 2;       //Menu option for changing password
  97.         final int MENU_OPTION_LOGOUT = 3;       //Menu option for logging out
  98.         final int MENU_OPTION_EXIT   = 4;       //Menu option for exiting
  99.  
  100.         final int LOGIN_USERNAME = 0;           //Username value in login info
  101.         final int LOGIN_PASSWORD = 1;           //Password value in login info
  102.  
  103.         //Local variables
  104.         String loginsFilename;                  //File name of login info file
  105.         String logFilename;                     //File name of log file
  106.         int menuOption;                         //Menu option selected
  107.         String[] loginInfo;                     //Username and password of current login
  108.         ArrayList<String[]> loginPairs;         //List of ID and password pairs
  109.         ArrayList<String> loginLog;             //Log of all successful logins
  110.  
  111.         Library64 clear = new Library64();      //Library utility that clears the screen
  112.  
  113.         /**********************************  Start Main Method  ***********************************/
  114.  
  115.         //Dispaly title for file setup
  116.         System.out.println("\n" + Console.center("File Setup") + "\n");
  117.  
  118.         //Prompt login file
  119.         loginsFilename = promptFilename(FILENAME_PROMPT_PAD, "Enter login info file name: ");
  120.  
  121.         //WHILE (login file doesn't exist)
  122.         while (!fileExists(loginsFilename))
  123.         {
  124.             //Display error that file doesn't exist
  125.             System.out.println(Console.padLeft(FILENAME_PROMPT_PAD, "!! FILE DOESN'T EXIST !!"));
  126.  
  127.             //Prompt login file
  128.             loginsFilename = promptFilename(FILENAME_PROMPT_PAD, "Enter login info file name: ");
  129.  
  130.         }//end while
  131.  
  132.         //Load login file
  133.         loginPairs  = readLogins(loginsFilename);
  134.         System.out.println("\n" + Console.padLeft(FILENAME_PROMPT_PAD, "Loaded login info.\n"));
  135.  
  136.         //Prompt log file
  137.         logFilename = promptFilename(FILENAME_PROMPT_PAD, "Enter log file name:        ");
  138.  
  139.         //Init login log to empty array list
  140.         loginLog    = new ArrayList<String>();
  141.  
  142.         //Init login info to an empty username and password
  143.         loginInfo   = new String[2];
  144.  
  145.         //Clear screen
  146.         clear.clrscr();
  147.  
  148.         //Get menu option
  149.         menuOption = menuPrompt();
  150.  
  151.         //WHILE (option isn't to exit)
  152.         while (menuOption != MENU_OPTION_EXIT)
  153.         {
  154.             //SWITCH (option)
  155.             switch (menuOption)
  156.             {
  157.                 //CASE login:     If no one's logged in, set login info to result of attempted login
  158.                 case MENU_OPTION_LOGIN:
  159.  
  160.                     //IF (no one is already logged in) THEN
  161.                     if (loginInfo[LOGIN_USERNAME] == null || loginInfo[LOGIN_USERNAME].isEmpty())
  162.                     {
  163.                         //Set login info to result of attempted login
  164.                         loginInfo = attemptLogin(loginPairs, loginLog);
  165.                     }
  166.  
  167.                     //ELSE (someone is logged in)
  168.                     else
  169.                     {
  170.                         //Display someone is already logged in
  171.                         System.out.println(Console.padLeft(PROMPT_PAD,
  172.                                              loginInfo[LOGIN_USERNAME] + " is already logged in!"));
  173.  
  174.                     }//end if anyone's logged in
  175.                     break;
  176.  
  177.                 //CASE password:   Run change password method
  178.                 case MENU_OPTION_PASSWD:
  179.                     changePassword(loginPairs, loginInfo);
  180.                     break;
  181.  
  182.                 //CASE logout:     Set username and password to empty strings and announce logout
  183.                 case MENU_OPTION_LOGOUT:
  184.  
  185.                     //IF (no one is logged in) THEN
  186.                     if (loginInfo[LOGIN_USERNAME] == null || loginInfo[LOGIN_USERNAME].isEmpty())
  187.                     {
  188.                         System.out.println(Console.padLeft(PROMPT_PAD, "No one's logged in!"));
  189.                     }
  190.  
  191.                     //ELSE (someone's logged in)
  192.                     else
  193.                     {
  194.                         //Set all login info to empty strings
  195.                         loginInfo[LOGIN_USERNAME] = "";
  196.                         loginInfo[LOGIN_PASSWORD] = "";
  197.  
  198.                         //Display success message
  199.                         System.out.println("\n" + Console.padLeft(PROMPT_PAD,
  200.                                                             "You have successfully logged out.\n"));
  201.  
  202.                     }//end if anyone's logged in
  203.                     break;
  204.  
  205.                 default:
  206.                     throw new UnsupportedOperationException("Unsupported menu option was selected.");
  207.  
  208.             }//END SWITCH
  209.  
  210.             //Get new menu option
  211.             menuOption = menuPrompt();
  212.  
  213.             //IF (new menu option was to exit) THEN
  214.             if (menuOption == MENU_OPTION_EXIT)
  215.             {
  216.                 //Save all password changes to the logins file and update log file
  217.                 exit(loginsFilename, loginPairs, logFilename, loginLog);
  218.             }
  219.  
  220.         }//END WHILE
  221.  
  222.     }//end class main
  223.  
  224.     /**********************************************************************************************
  225.      * Method Name    : FileIO - Read Logins
  226.      * Author         : Terry Weiss
  227.      * Date           : March 4, 2016
  228.      * Course/Section : CSC264 - 001
  229.      * Program Description: This method loads all the usernames and passwords from a file. This
  230.      *     method does not verify if the file exists or if it's formatted correctly. All login
  231.      *     info should be formatted as `NAME PASSWORD` with one space between. There should only
  232.      *     one ID/password pair per line.
  233.      *
  234.      * BEGIN Read Logins
  235.      *     Init logins to empty array list
  236.      *     Open the input stream for reading logins file
  237.      *     WHILE (there are more lines in the file)
  238.      *         Add the line to the list, splitting the username and password
  239.      *     END WHILE
  240.      *     Close file reader
  241.      *     Return logins
  242.      * END Read Logins
  243.      **********************************************************************************************/
  244.      private static ArrayList<String[]> readLogins(String filename) throws IOException
  245.      {
  246.         //Local constants
  247.  
  248.         //Local variables
  249.         ArrayList<String[]> logins;     //List of username and password pairs
  250.         BufferedReader bFile;           //File reader reading the logins file
  251.         String loginLine;               //Current line being read from the file
  252.  
  253.         /*******************************  Start Read Logins Method  *******************************/
  254.  
  255.         //Init logins to empty array list
  256.         logins = new ArrayList<String[]>();
  257.  
  258.         //Open the input stream for reading logins file
  259.         bFile  = new BufferedReader(new FileReader(filename));
  260.  
  261.         //Get first line of logins file
  262.         loginLine = bFile.readLine();
  263.  
  264.         //WHILE (there are more lines in the file)
  265.         while (loginLine != null)
  266.         {
  267.             //Add the line to the list, splitting the username and password
  268.             logins.add(loginLine.split(" "));
  269.  
  270.             //Get the next line from the logins file
  271.             loginLine = bFile.readLine();
  272.  
  273.         }//end while there are more lines
  274.  
  275.         //Close file reader
  276.         bFile.close();
  277.  
  278.         //Return success
  279.         return logins;
  280.  
  281.      }//end method Read Logins
  282.  
  283.     /**********************************************************************************************
  284.      * Method Name    : FileIO - Menu Prompt
  285.      * Author         : Terry Weiss
  286.      * Date           : March 4, 2016
  287.      * Course/Section : CSC264 - 001
  288.      * Program Description: This method displays the menu options and prompts the user for their
  289.      *     menu option.
  290.      *
  291.      * BEGIN Menu Prompt
  292.      *     Display menu title
  293.      *     Display menu options
  294.      *     Prompt user for option
  295.      *     WHILE (option is out of range)
  296.      *         Display error message about out of range
  297.      *         Prompt user for option
  298.      *     END WHILE
  299.      *     Return menu option
  300.      * END Menu Prompt
  301.      **********************************************************************************************/
  302.     private static int menuPrompt()
  303.     {
  304.         //Local constants
  305.         final int OPTION_PAD   = 31;        //Character padding for menu options
  306.         final int PROMPT_PAD   = 18;        //Character padding for menu prompt
  307.  
  308.         final int FIRST_OPTION = 1;         //Value of first menu option
  309.         final int LAST_OPTION  = 4;         //Value of last menu option
  310.  
  311.  
  312.         //Local variables
  313.         int option;                         //User's selected menu option
  314.  
  315.         Library64 clear = new Library64();  //Library utility that clears the screen
  316.  
  317.         /*******************************  Start Menu Prompt Method  *******************************/
  318.  
  319.         //Display menu title
  320.         System.out.println("\n" + Console.center("Login System") + "\n");
  321.  
  322.         //Display menu options
  323.         System.out.println(Console.padLeft(OPTION_PAD, "1. Log in"));
  324.         System.out.println(Console.padLeft(OPTION_PAD, "2. Change password"));
  325.         System.out.println(Console.padLeft(OPTION_PAD, "3. Log out"));
  326.         System.out.println(Console.padLeft(OPTION_PAD, "4. Exit"));
  327.  
  328.         //Prompt user for option
  329.         System.out.print(Console.padLeft(PROMPT_PAD, "Please choose a menu option: "));
  330.         option = Keyboard.readInt();
  331.  
  332.         //WHILE (option is out of range)
  333.         while (option < FIRST_OPTION || option > LAST_OPTION)
  334.         {
  335.             //Display error message about out of range
  336.             System.out.print("Invalid option. ");
  337.  
  338.             //Prompt user for option
  339.             System.out.print("Choose a menu option: ");
  340.             option = Keyboard.readInt();
  341.  
  342.         }//end while (option is out of range)
  343.  
  344.         //return menu option
  345.         return option;
  346.  
  347.     }//end class menu prompt
  348.  
  349.     /**********************************************************************************************
  350.      * Method Name    : FileIO - Prompt Filename
  351.      * Author         : Terry Weiss
  352.      * Date           : March 4, 2016
  353.      * Course/Section : CSC264 - 001
  354.      * Program Description: This method prompts for a filename. If the original filename is empty
  355.      *     or just spaces, they are given an error message and prompted again. After the first
  356.      *     time, the trailing whitespace of the prompt message is removed to avoid overflowing the
  357.      *     line as easily with the error message.
  358.      *
  359.      * BEGIN Prompt Filename
  360.      *     Prompt user for a filename
  361.      *     WHILE (filename is empty)
  362.      *         Display error message about invalid filename
  363.      *         Prompt user for a filename
  364.      *     END WHILE
  365.      *     Return filename
  366.      * END Prompt Filename
  367.      **********************************************************************************************/
  368.     private static String promptFilename(int pad, String prompt)
  369.     {
  370.         //Local constants
  371.  
  372.         //Local variables
  373.         String filename;        //New filename
  374.  
  375.         /*****************************  Start Prompt Filename Method  *****************************/
  376.  
  377.         //Prompt user for a filename
  378.         System.out.print(Console.padLeft(pad, prompt));
  379.         filename = Keyboard.readString().trim();
  380.  
  381.         //WHILE (filename is empty)
  382.         while (filename.isEmpty())
  383.         {
  384.             //Display error message about invalid filename
  385.             System.out.print(Console.padLeft(pad, "Invalid filename. "));
  386.  
  387.             //Prompt user for a filename
  388.             System.out.print(prompt.trim() + " ");  //Replaces original trailing space with 1 space
  389.             filename = Keyboard.readString();
  390.         }
  391.  
  392.         //Return filename
  393.         return filename;
  394.  
  395.     }//end method prompt filename
  396.  
  397.     /**********************************************************************************************
  398.      * Method Name    : FileIO - File Exists
  399.      * Author         : Terry Weiss
  400.      * Date           : March 4, 2016
  401.      * Course/Section : CSC264 - 001
  402.      * Program Description: This method confirms if a file exists.
  403.      *
  404.      * BEGIN File Exists
  405.      *     Create new file object and check if it exists
  406.      * END File Exists
  407.      **********************************************************************************************/
  408.     private static boolean fileExists(String filename)
  409.     {
  410.         //Local constants
  411.  
  412.         //Local variables
  413.  
  414.         /*******************************  Start File Exists Method  *******************************/
  415.  
  416.         //Create new file object and check if it exists
  417.         return (new File(filename).exists());
  418.  
  419.     }//end method file exists
  420.  
  421.     /**********************************************************************************************
  422.      * Method Name    : FileIO - Attempt Login
  423.      * Author         : Terry Weiss
  424.      * Date           : March 4, 2016
  425.      * Course/Section : CSC264 - 001
  426.      * Program Description: This method attempts to log in a user. The user is prompted for a
  427.      *     username and password. If the username isn't found, the login fails. Otherwise, the
  428.      *     user is prompted for their password. If the password doesn't match the username's
  429.      *     password, the login also fails. If the login fails, a login array with an empty
  430.      *     username and password is returned. Otherwise, a login array with the matching username
  431.      *     and password is returned, and the login is written to the log file. If the login is
  432.      *     successful, the username and time stamp will be added to the given log ArrayList.
  433.      *
  434.      * BEGIN Attempt Login
  435.      *     Init index to 0
  436.      *     Prompt username
  437.      *     WHILE (username is empty)
  438.      *         Display invalid username and reprompt
  439.      *     END WHILE
  440.      *     WHILE (the username doesn't match AND there are more login pairs) //find username's index
  441.      *         Increment index
  442.      *     END WHILE
  443.      *     IF (username was found) THEN
  444.      *         Init attempts to 0
  445.      *         Prompt password
  446.      *         WHILE (more attempts are left AND password doesn't match)
  447.      *             Increment attempt
  448.      *             Display error message and reprompt
  449.      *         END WHILE
  450.      *         IF (password attempt matches real password) THEN
  451.      *             Set login's password to password
  452.      *             Set login's username to username
  453.      *             Add username to log
  454.      *             Display successful login
  455.      *         END IF
  456.      *     ELSE
  457.      *         Display username doesn't exist
  458.      *     END IF
  459.      * END Attempt Login
  460.      **********************************************************************************************/
  461.     private static String[] attemptLogin(ArrayList<String[]> pairs, ArrayList<String> log)
  462.     {
  463.         //Local constants
  464.         final int LOGIN_FIELDS    = 2;      //Number of fields returned (currently id & passwd)
  465.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  466.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  467.         final int MAX_ATTEMPTS    = 2;      //Additional attempts after initial password failure
  468.  
  469.         final int PROMPT_PAD = 30;          //Character pad for prompt
  470.  
  471.         //Local variables
  472.         int index;                          //Current index of login pair
  473.         int attempts;                       //Number of additional attempts for correct password
  474.         String username;                    //User's username
  475.         String passwordAttempt;             //User's password attempt
  476.         String password;                    //Username's real password
  477.         String[] login;                     //User's login info
  478.         String logLine;                     //Read username and password
  479.  
  480.         /******************************  Start Attempt Login Method  ******************************/
  481.  
  482.         //Init index to 0
  483.         index = 0;
  484.  
  485.         //Init login to an empty username and password
  486.         login = new String[LOGIN_FIELDS];
  487.         login[LOGIN_USERNAME] = "";
  488.         login[LOGIN_USERNAME] = "";
  489.  
  490.         //Prompt for a username
  491.         System.out.print(Console.padLeft(PROMPT_PAD, "Enter your username: "));
  492.         username = Keyboard.readString().trim();
  493.  
  494.         //WHILE (username is empty)
  495.         while (username.isEmpty())
  496.         {
  497.             //Display invalid username and reprompt
  498.             System.out.print(Console.padLeft(PROMPT_PAD, "Invalid username. Enter your username: "));
  499.             username = Keyboard.readString().trim();
  500.         }
  501.  
  502.         /*
  503.          * This is to find the username's index if it exists. If it doesn't exist, index will end
  504.          * up equaling the array list's size.
  505.          */
  506.         //WHILE (there are more login pairs AND the username doesn't match)
  507.         while (index < pairs.size() && !pairs.get(index)[LOGIN_USERNAME].equalsIgnoreCase(username))
  508.         {
  509.             //Increment index
  510.             index++;
  511.         }
  512.  
  513.         //IF (username was found) THEN
  514.         if (index < pairs.size())
  515.         {
  516.             //Init attempts to 0
  517.             attempts = 0;
  518.  
  519.             //Prompt password
  520.             System.out.print(Console.padLeft(PROMPT_PAD, "Enter your password: "));
  521.             password = Keyboard.readString();
  522.  
  523.             //WHILE (more attempts are left AND password doesn't match)
  524.             while (!pairs.get(index)[LOGIN_PASSWORD].equals(password) && attempts < MAX_ATTEMPTS)
  525.             {
  526.                 //Increment attempt
  527.                 attempts++;
  528.  
  529.                 //Display error message and reprompt
  530.                 System.out.print(Console.padLeft(PROMPT_PAD,
  531.                                                  "Invalid password. Please enter your password: "));
  532.                 password = Keyboard.readString();
  533.  
  534.             }//end while
  535.  
  536.             //IF (password attempt matches real password) THEN
  537.             if (pairs.get(index)[LOGIN_PASSWORD].equals(password))
  538.             {
  539.                 //Set login's password to password
  540.                 login[LOGIN_USERNAME] = username;
  541.  
  542.                 //Set login's username to username
  543.                 login[LOGIN_PASSWORD] = password;
  544.  
  545.                 //Add username to log
  546.                 log.add(String.format("%-20s    %s", username, new Date()));
  547.  
  548.                 //Display successful login
  549.                 System.out.println("\n" + Console.center("Welcome back, " + username + "!"));
  550.  
  551.             }//end if password matches
  552.         }//end if username was found
  553.  
  554.         //ELSE (username wasn't found)
  555.         else
  556.         {
  557.             //Display message that username wasn't found.
  558.             System.out.println(Console.padLeft(PROMPT_PAD, "Username doesn't exist!"));
  559.         }
  560.  
  561.         //Return login
  562.         return login;
  563.  
  564.     }//end method attempt login
  565.  
  566.     /**********************************************************************************************
  567.      * Method Name    : FileIO - Change Password
  568.      * Author         : Terry Weiss
  569.      * Date           : March 4, 2016
  570.      * Course/Section : CSC264 - 001
  571.      * Program Description: This method changes the password of the current login if someone is
  572.      *     currently logged in. A success or failure message is printed to the console based on
  573.      *     if anyone is logged in. Passwords must have at least 5 characters to be valid. A user
  574.      *     must confirm their current password before being able to change their password.
  575.      *
  576.      * BEGIN Change Password
  577.      *     IF (no one is logged in) THEN
  578.      *         Display error message
  579.      *     ELSE
  580.      *         Prompt for current password
  581.      *         IF (password doesn't match) THEN
  582.      *             Display error
  583.      *         ELSE
  584.      *             Store index of current login info
  585.      *             Prompt for new password
  586.      *             WHILE (password is too short)
  587.      *                 Reprompt for new password
  588.      *             END WHILE
  589.      *             Set login info's password to entered password
  590.      *             Create temporary login info
  591.      *             Replace index with temporary login info
  592.      *             Display success message
  593.      *         END IF
  594.      *     END IF
  595.      * END Change Password
  596.      **********************************************************************************************/
  597.     public static void changePassword(ArrayList<String[]> loginPairs, String[] loginInfo)
  598.     {
  599.         //Local constants
  600.         final boolean APPEND      = true;   //Append to a file when writing
  601.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  602.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  603.         final int LOGIN_FIELDS    = 2;      //Number of login fields saved
  604.         final int PAD             = 18;     //Character padding for output
  605.         final int MIN_LENGTH      = 5;      //Minimum password length
  606.  
  607.         //Local variables
  608.         BufferedWriter writer;              //Utility object writes to file writer
  609.         boolean confirmed;                  //Whether current password was confirmed
  610.         int index;                          //Index of login
  611.         String passwordAttempt;             //User's attempt to confirm password
  612.         String newPassword;                 //User's new password
  613.         String[] temp;                      //Temporary login info
  614.  
  615.         /*****************************  Start Change Password Method  *****************************/
  616.  
  617.         //IF (no one is logged in) THEN
  618.         if (loginInfo[LOGIN_USERNAME] == null || loginInfo[LOGIN_USERNAME].isEmpty())
  619.         {
  620.             //Display error message
  621.             System.out.println(Console.padLeft(PAD, "Please log in to change your password.\n"));
  622.         }
  623.        
  624.         //ELSE (someone is logged in)
  625.         else
  626.         {
  627.             //Prompt for current password
  628.             System.out.print(Console.padLeft(PAD, "Enter current password: "));
  629.             passwordAttempt = Keyboard.readString();
  630.            
  631.             //IF (password doesn't match) THEN
  632.             if (!passwordAttempt.equals(loginInfo[LOGIN_PASSWORD]))
  633.             {
  634.                 //Display error
  635.                 System.out.println(Console.padLeft(PAD, "Incorrect password.\n"));
  636.             }
  637.            
  638.             //ELSE (password matches)
  639.             else
  640.             {
  641.  
  642.                 //Store index of current login info
  643.                 index = getIndex(loginPairs, loginInfo);
  644.  
  645.                 //Prompt for new password
  646.                 System.out.print(Console.padLeft(PAD, "Enter new password:     "));
  647.                 newPassword = Keyboard.readString();
  648.  
  649.                 //WHILE (password is too short)
  650.                 while (newPassword.length() < MIN_LENGTH)
  651.                 {
  652.                     //Reprompt for new password
  653.                     System.out.print(Console.padLeft(PAD, "Enter new password (min "
  654.                                                                 + MIN_LENGTH + " characters): "));
  655.                     newPassword = Keyboard.readString();
  656.  
  657.                 }//end while password is too short
  658.  
  659.                 //Set login info's password to entered password
  660.                 loginInfo[LOGIN_PASSWORD] = newPassword;
  661.  
  662.                 //Create temporary login info
  663.                 temp = new String[LOGIN_FIELDS];
  664.                 temp[LOGIN_USERNAME] = loginInfo[LOGIN_USERNAME];
  665.                 temp[LOGIN_PASSWORD] = newPassword;
  666.                
  667.                 //Replace index with temporary login info
  668.                 loginPairs.set(index, temp);
  669.                
  670.                 //Display success message
  671.                 System.out.println(Console.padLeft(PAD, "Password changed successfully!\n"));
  672.  
  673.             }//end if password matches
  674.         }//end if someone is logged in
  675.  
  676.     }//end method change password
  677.  
  678.     /**********************************************************************************************
  679.      * Method Name    : FileIO - Get Index
  680.      * Author         : Terry Weiss
  681.      * Date           : March 4, 2016
  682.      * Course/Section : CSC264 - 001
  683.      * Program Description: This method gets the index of a given login in the login list. A
  684.      *     login matches with a case insensitive username and case sensitive password.
  685.      *
  686.      * BEGIN Get Index
  687.      *     Init found to false
  688.      *     Init index to 0
  689.      *     WHILE (there are more logins AND login wasn't found)
  690.      *         IF (username/password matches current pair's username/password)
  691.      *             Set found to true
  692.      *         ELSE
  693.      *             Increment index
  694.      *         END IF
  695.      *     END WHILE
  696.      *     IF (login wasn't found) THEN
  697.      *         Set index to not found
  698.      *     END IF
  699.      *     Return index
  700.      * END Get Index
  701.      **********************************************************************************************/
  702.     private static int getIndex(ArrayList<String[]> loginPairs, String[] loginInfo)
  703.     {
  704.         //Local constants
  705.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  706.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  707.         final int NOT_FOUND       = -1;     //Index if login wasn't found
  708.  
  709.         //Local variables
  710.         boolean found;      //Whether login was found
  711.         int index;          //Index of login
  712.  
  713.         /*******************************  Start File Exists Method  *******************************/
  714.  
  715.         //Init found to false
  716.         found = false;
  717.  
  718.         //Init index to 0
  719.         index = 0;
  720.  
  721.         //WHILE (there are more logins AND login wasn't found)
  722.         while (index < loginPairs.size() && !found)
  723.         {
  724.             //IF (username/password matches current pair's username/password)
  725.             if (loginPairs.get(index)[LOGIN_USERNAME].equalsIgnoreCase(loginInfo[LOGIN_USERNAME])
  726.                     && loginPairs.get(index)[LOGIN_PASSWORD].equals(loginInfo[LOGIN_PASSWORD]))
  727.             {
  728.                 //Set found to true
  729.                 found = true;
  730.             }
  731.            
  732.             //ELSE username/passwords don't match
  733.             else
  734.             {
  735.                 //Increment index
  736.                 index++;
  737.  
  738.             }//end if username/password matches
  739.         }//end while more logins and not found
  740.  
  741.         //IF (login wasn't found) THEN
  742.         if (!found)
  743.         {
  744.             //Set index to not found
  745.             index = NOT_FOUND;
  746.         }
  747.  
  748.         //Return index
  749.         return index;
  750.  
  751.     }//end method file exists
  752.  
  753.     /**********************************************************************************************
  754.      * Method Name    : FileIO - Exit
  755.      * Author         : Terry Weiss
  756.      * Date           : March 4, 2016
  757.      * Course/Section : CSC264 - 001
  758.      * Program Description: This method saves the new login info and log to their files before
  759.      *     the program exits.
  760.      *
  761.      * BEGIN Exit
  762.      *     Init empty writer
  763.      *     TRY to write the pairs
  764.      *         Open writer to write logins info back to file
  765.      *         FOR (each login pair)
  766.      *             Write username and password to the file with a space between them
  767.      *         END FOR
  768.      *     CATCH (IO exception)
  769.      *         Display unable to write to logins file
  770.      *     FINALLY
  771.      *         Flush writer
  772.      *         Close writer
  773.      *     END TRY-CATCH-FINALLY
  774.      *     TRY to write the log
  775.      *         IF (log file exists) THEN
  776.      *             Open writer to append log back to file
  777.      *         ELSE
  778.      *             Open writer to write log back to file
  779.      *         END IF
  780.      *         FOR (each log entry)
  781.      *             Write the log entry to log file
  782.      *         END FOR
  783.      *     CATCH (IO Exception)
  784.      *         Display unable to write to log file
  785.      *     FINALLY
  786.      *         Flush writer
  787.      *         Close writer
  788.      *     END TRY-CATCH-FINALLY
  789.      * END Exit
  790.      **********************************************************************************************/
  791.     private static void exit(String loginsFilename, ArrayList<String[]> pairs, String logFilename,
  792.                                 ArrayList<String> log)
  793.             throws IOException
  794.     {
  795.         //Local constants
  796.         final boolean APPEND      = true;   //Append to a file when writing
  797.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  798.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  799.         final int PAD             = 18;     //Character padding for output
  800.  
  801.         //Local variables
  802.         BufferedWriter writer;              //Utility object writes to file writer
  803.  
  804.         /**********************************  Start Exit Method  ***********************************/
  805.  
  806.         //Init empty writer
  807.         writer = null;
  808.  
  809.         //TRY to write the pairs
  810.         try
  811.         {
  812.             //Open writer to write logins info back to file
  813.             writer = new BufferedWriter(new FileWriter(loginsFilename));
  814.  
  815.             //FOR (each login pair)
  816.             for (String[] pair : pairs)
  817.             {
  818.                 //Write username and password to the file with a space between them
  819.                 writer.write(pair[LOGIN_USERNAME] + " " + pair[LOGIN_PASSWORD] + "\n");
  820.             }
  821.         }
  822.  
  823.         //CATCH (IO exception)
  824.         catch (IOException e)
  825.         {
  826.             //Display unable to write to logins file
  827.             System.out.println(Console.center("!! UNABLE TO WRITE TO LOGINS FILE !!"));
  828.         }
  829.  
  830.         //FINALLY
  831.         finally
  832.         {
  833.             //Flush writer
  834.             writer.flush();
  835.  
  836.             //Close writer
  837.             writer.close();
  838.         }//end try-catch-finally writing to logins info file
  839.  
  840.  
  841.         //TRY to write the log
  842.         try
  843.         {
  844.             //IF (log file exists) THEN
  845.             if (fileExists(logFilename))
  846.             {
  847.                 //Open writer to append log back to file
  848.                 writer = new BufferedWriter(new FileWriter(logFilename, APPEND));
  849.             }
  850.  
  851.             //ELSE (log file doesn't exist)
  852.             else
  853.             {
  854.                 //Open writer to write log back to file
  855.                 writer = new BufferedWriter(new FileWriter(logFilename));
  856.             }//end if log file exists
  857.  
  858.             //FOR (each log entry)
  859.             for (String entry : log)
  860.             {
  861.                 //Write the log entry to log file
  862.                 writer.write(entry + "\n");
  863.             }//end for each log entry
  864.         }
  865.  
  866.         //CATCH (IO Exception)
  867.         catch (IOException e)
  868.         {
  869.             //Display unable to write to log file
  870.             System.out.println(Console.center("!! UNABLE TO WRITE TO LOG FILE !!"));
  871.         }
  872.  
  873.         //FINALLY
  874.         finally
  875.         {
  876.             //Flush writer
  877.             writer.flush();
  878.  
  879.             //Close writer
  880.             writer.close();
  881.         }//end try-catch-finally writing to log file
  882.  
  883.     }//end method exit
  884.  
  885. }//end class File IO
Advertisement
Add Comment
Please, Sign In to add comment