Advertisement
brainfrz

LoginFileIO

Mar 8th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 35.49 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("\nYou have successfully logged out.\n");
  200.  
  201.                     }//end if anyone's logged in
  202.                     break;
  203.  
  204.                 default:
  205.                     throw new UnsupportedOperationException("Unsupported menu option was selected.");
  206.  
  207.             }//END SWITCH
  208.  
  209.             //Get new menu option
  210.             menuOption = menuPrompt();
  211.  
  212.             //IF (new menu option was to exit) THEN
  213.             if (menuOption == MENU_OPTION_EXIT)
  214.             {
  215.                 //Save all password changes to the logins file and update log file
  216.                 exit(loginsFilename, loginPairs, logFilename, loginLog);
  217.             }
  218.  
  219.         }//END WHILE
  220.  
  221.     }//end class main
  222.  
  223.     /**********************************************************************************************
  224.      * Method Name    : FileIO - Read Logins
  225.      * Author         : Terry Weiss
  226.      * Date           : March 4, 2016
  227.      * Course/Section : CSC264 - 001
  228.      * Program Description: This method loads all the usernames and passwords from a file. This
  229.      *     method does not verify if the file exists or if it's formatted correctly. All login
  230.      *     info should be formatted as `NAME PASSWORD` with one space between. There should only
  231.      *     one ID/password pair per line.
  232.      *
  233.      * BEGIN Read Logins
  234.      *     Init logins to empty array list
  235.      *     Open the input stream for reading logins file
  236.      *     WHILE (there are more lines in the file)
  237.      *         Add the line to the list, splitting the username and password
  238.      *     END WHILE
  239.      *     Close file reader
  240.      *     Return logins
  241.      * END Read Logins
  242.      **********************************************************************************************/
  243.      private static ArrayList<String[]> readLogins(String filename) throws IOException
  244.      {
  245.         //Local constants
  246.  
  247.         //Local variables
  248.         ArrayList<String[]> logins;     //List of username and password pairs
  249.         BufferedReader bFile;           //File reader reading the logins file
  250.         String loginLine;               //Current line being read from the file
  251.  
  252.         /*******************************  Start Read Logins Method  *******************************/
  253.  
  254.         //Init logins to empty array list
  255.         logins = new ArrayList<String[]>();
  256.  
  257.         //Open the input stream for reading logins file
  258.         bFile  = new BufferedReader(new FileReader(filename));
  259.  
  260.         //Get first line of logins file
  261.         loginLine = bFile.readLine();
  262.  
  263.         //WHILE (there are more lines in the file)
  264.         while (loginLine != null)
  265.         {
  266.             //Add the line to the list, splitting the username and password
  267.             logins.add(loginLine.split(" "));
  268.  
  269.             //Get the next line from the logins file
  270.             loginLine = bFile.readLine();
  271.  
  272.         }//end while there are more lines
  273.  
  274.         //Close file reader
  275.         bFile.close();
  276.  
  277.         //Return success
  278.         return logins;
  279.  
  280.      }//end method Read Logins
  281.  
  282.     /**********************************************************************************************
  283.      * Method Name    : FileIO - Menu Prompt
  284.      * Author         : Terry Weiss
  285.      * Date           : March 4, 2016
  286.      * Course/Section : CSC264 - 001
  287.      * Program Description: This method displays the menu options and prompts the user for their
  288.      *     menu option.
  289.      *
  290.      * BEGIN Menu Prompt
  291.      *     Display menu title
  292.      *     Display menu options
  293.      *     Prompt user for option
  294.      *     WHILE (option is out of range)
  295.      *         Display error message about out of range
  296.      *         Prompt user for option
  297.      *     END WHILE
  298.      *     Return menu option
  299.      * END Menu Prompt
  300.      **********************************************************************************************/
  301.     private static int menuPrompt()
  302.     {
  303.         //Local constants
  304.         final int OPTION_PAD   = 31;        //Character padding for menu options
  305.         final int PROMPT_PAD   = 18;        //Character padding for menu prompt
  306.  
  307.         final int FIRST_OPTION = 1;         //Value of first menu option
  308.         final int LAST_OPTION  = 4;         //Value of last menu option
  309.  
  310.  
  311.         //Local variables
  312.         int option;                         //User's selected menu option
  313.  
  314.         Library64 clear = new Library64();  //Library utility that clears the screen
  315.  
  316.         /*******************************  Start Menu Prompt Method  *******************************/
  317.  
  318.         //Display menu title
  319.         System.out.println("\n" + Console.center("Login System") + "\n");
  320.  
  321.         //Display menu options
  322.         System.out.println(Console.padLeft(OPTION_PAD, "1. Log in"));
  323.         System.out.println(Console.padLeft(OPTION_PAD, "2. Change password"));
  324.         System.out.println(Console.padLeft(OPTION_PAD, "3. Log out"));
  325.         System.out.println(Console.padLeft(OPTION_PAD, "4. Exit"));
  326.  
  327.         //Prompt user for option
  328.         System.out.print(Console.padLeft(PROMPT_PAD, "Please choose a menu option: "));
  329.         option = Keyboard.readInt();
  330.  
  331.         //WHILE (option is out of range)
  332.         while (option < FIRST_OPTION || option > LAST_OPTION)
  333.         {
  334.             //Display error message about out of range
  335.             System.out.print("Invalid option. ");
  336.  
  337.             //Prompt user for option
  338.             System.out.print("Choose a menu option: ");
  339.             option = Keyboard.readInt();
  340.  
  341.         }//end while (option is out of range)
  342.  
  343.         //return menu option
  344.         return option;
  345.  
  346.     }//end class menu prompt
  347.  
  348.     /**********************************************************************************************
  349.      * Method Name    : FileIO - Prompt Filename
  350.      * Author         : Terry Weiss
  351.      * Date           : March 4, 2016
  352.      * Course/Section : CSC264 - 001
  353.      * Program Description: This method prompts for a filename. If the original filename is empty
  354.      *     or just spaces, they are given an error message and prompted again. After the first
  355.      *     time, the trailing whitespace of the prompt message is removed to avoid overflowing the
  356.      *     line as easily with the error message.
  357.      *
  358.      * BEGIN Prompt Filename
  359.      *     Prompt user for a filename
  360.      *     WHILE (filename is empty)
  361.      *         Display error message about invalid filename
  362.      *         Prompt user for a filename
  363.      *     END WHILE
  364.      *     Return filename
  365.      * END Prompt Filename
  366.      **********************************************************************************************/
  367.     private static String promptFilename(int pad, String prompt)
  368.     {
  369.         //Local constants
  370.  
  371.         //Local variables
  372.         String filename;        //New filename
  373.  
  374.         /*****************************  Start Prompt Filename Method  *****************************/
  375.  
  376.         //Prompt user for a filename
  377.         System.out.print(Console.padLeft(pad, prompt));
  378.         filename = Keyboard.readString().trim();
  379.  
  380.         //WHILE (filename is empty)
  381.         while (filename.isEmpty())
  382.         {
  383.             //Display error message about invalid filename
  384.             System.out.print(Console.padLeft(pad, "Invalid filename. "));
  385.  
  386.             //Prompt user for a filename
  387.             System.out.print(prompt.trim() + " ");  //Replaces original trailing space with 1 space
  388.             filename = Keyboard.readString();
  389.         }
  390.  
  391.         //Return filename
  392.         return filename;
  393.  
  394.     }//end method prompt filename
  395.  
  396.     /**********************************************************************************************
  397.      * Method Name    : FileIO - File Exists
  398.      * Author         : Terry Weiss
  399.      * Date           : March 4, 2016
  400.      * Course/Section : CSC264 - 001
  401.      * Program Description: This method confirms if a file exists.
  402.      *
  403.      * BEGIN File Exists
  404.      *     Create new file object and check if it exists
  405.      * END File Exists
  406.      **********************************************************************************************/
  407.     private static boolean fileExists(String filename)
  408.     {
  409.         //Local constants
  410.  
  411.         //Local variables
  412.  
  413.         /*******************************  Start File Exists Method  *******************************/
  414.  
  415.         //Create new file object and check if it exists
  416.         return (new File(filename).exists());
  417.  
  418.     }//end method file exists
  419.  
  420.     /**********************************************************************************************
  421.      * Method Name    : FileIO - Attempt Login
  422.      * Author         : Terry Weiss
  423.      * Date           : March 4, 2016
  424.      * Course/Section : CSC264 - 001
  425.      * Program Description: This method attempts to log in a user. The user is prompted for a
  426.      *     username and password. If the username isn't found, the login fails. Otherwise, the
  427.      *     user is prompted for their password. If the password doesn't match the username's
  428.      *     password, the login also fails. If the login fails, a login array with an empty
  429.      *     username and password is returned. Otherwise, a login array with the matching username
  430.      *     and password is returned, and the login is written to the log file. If the login is
  431.      *     successful, the username and time stamp will be added to the given log ArrayList.
  432.      *
  433.      * BEGIN Attempt Login
  434.      *     Init index to 0
  435.      *     Prompt username
  436.      *     WHILE (username is empty)
  437.      *         Display invalid username and reprompt
  438.      *     END WHILE
  439.      *     WHILE (the username doesn't match AND there are more login pairs) //find username's index
  440.      *         Increment index
  441.      *     END WHILE
  442.      *     IF (username was found) THEN
  443.      *         Init attempts to 0
  444.      *         Prompt password
  445.      *         WHILE (more attempts are left AND password doesn't match)
  446.      *             Increment attempt
  447.      *             Display error message and reprompt
  448.      *         END WHILE
  449.      *         IF (password attempt matches real password) THEN
  450.      *             Set login's password to password
  451.      *             Set login's username to username
  452.      *             Add username to log
  453.      *             Display successful login
  454.      *         END IF
  455.      *     ELSE
  456.      *         Display username doesn't exist
  457.      *     END IF
  458.      * END Attempt Login
  459.      **********************************************************************************************/
  460.     private static String[] attemptLogin(ArrayList<String[]> pairs, ArrayList<String> log)
  461.     {
  462.         //Local constants
  463.         final int LOGIN_FIELDS    = 2;      //Number of fields returned (currently id & passwd)
  464.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  465.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  466.         final int MAX_ATTEMPTS    = 2;      //Additional attempts after initial password failure
  467.  
  468.         final int PROMPT_PAD = 30;          //Character pad for prompt
  469.  
  470.         //Local variables
  471.         int index;                          //Current index of login pair
  472.         int attempts;                       //Number of additional attempts for correct password
  473.         String username;                    //User's username
  474.         String passwordAttempt;             //User's password attempt
  475.         String password;                    //Username's real password
  476.         String[] login;                     //User's login info
  477.         String logLine;                     //Read username and password
  478.  
  479.         /******************************  Start Attempt Login Method  ******************************/
  480.  
  481.         //Init index to 0
  482.         index = 0;
  483.  
  484.         //Init login to an empty username and password
  485.         login = new String[LOGIN_FIELDS];
  486.         login[LOGIN_USERNAME] = "";
  487.         login[LOGIN_USERNAME] = "";
  488.  
  489.         //Prompt for a username
  490.         System.out.print(Console.padLeft(PROMPT_PAD, "Enter your username: "));
  491.         username = Keyboard.readString().trim();
  492.  
  493.         //WHILE (username is empty)
  494.         while (username.isEmpty())
  495.         {
  496.             //Display invalid username and reprompt
  497.             System.out.print(Console.padLeft(PROMPT_PAD, "Invalid username. Enter your username: "));
  498.             username = Keyboard.readString().trim();
  499.         }
  500.  
  501.         /*
  502.          * This is to find the username's index if it exists. If it doesn't exist, index will end
  503.          * up equaling the array list's size.
  504.          */
  505.         //WHILE (there are more login pairs AND the username doesn't match)
  506.         while (index < pairs.size() && !pairs.get(index)[LOGIN_USERNAME].equalsIgnoreCase(username))
  507.         {
  508.             //Increment index
  509.             index++;
  510.         }
  511.  
  512.         //IF (username was found) THEN
  513.         if (index < pairs.size())
  514.         {
  515.             //Init attempts to 0
  516.             attempts = 0;
  517.  
  518.             //Prompt password
  519.             System.out.print(Console.padLeft(PROMPT_PAD, "Enter your password: "));
  520.             password = Keyboard.readString();
  521.  
  522.             //WHILE (more attempts are left AND password doesn't match)
  523.             while (!pairs.get(index)[LOGIN_PASSWORD].equals(password) && attempts < MAX_ATTEMPTS)
  524.             {
  525.                 //Increment attempt
  526.                 attempts++;
  527.  
  528.                 //Display error message and reprompt
  529.                 System.out.print(Console.padLeft(PROMPT_PAD,
  530.                                                  "Invalid password. Please enter your password: "));
  531.                 password = Keyboard.readString();
  532.  
  533.             }//end while
  534.  
  535.             //IF (password attempt matches real password) THEN
  536.             if (pairs.get(index)[LOGIN_PASSWORD].equals(password))
  537.             {
  538.                 //Set login's password to password
  539.                 login[LOGIN_USERNAME] = username;
  540.  
  541.                 //Set login's username to username
  542.                 login[LOGIN_PASSWORD] = password;
  543.  
  544.                 //Add username to log
  545.                 log.add(String.format("%-20s    %s", username, new Date()));
  546.  
  547.                 //Display successful login
  548.                 System.out.println("\n" + Console.center("Welcome back, " + username + "!"));
  549.  
  550.             }//end if password matches
  551.         }//end if username was found
  552.  
  553.         //ELSE (username wasn't found)
  554.         else
  555.         {
  556.             //Display message that username wasn't found.
  557.             System.out.println(Console.padLeft(PROMPT_PAD, "Username doesn't exist!"));
  558.         }
  559.  
  560.         //Return login
  561.         return login;
  562.  
  563.     }//end method attempt login
  564.  
  565.     /**********************************************************************************************
  566.      * Method Name    : FileIO - Change Password
  567.      * Author         : Terry Weiss
  568.      * Date           : March 4, 2016
  569.      * Course/Section : CSC264 - 001
  570.      * Program Description: This method changes the password of the current login if someone is
  571.      *     currently logged in. A success or failure message is printed to the console based on
  572.      *     if anyone is logged in. Passwords must have at least 5 characters to be valid. A user
  573.      *     must confirm their current password before being able to change their password.
  574.      *
  575.      * BEGIN Change Password
  576.      *     IF (no one is logged in) THEN
  577.      *         Display error message
  578.      *     ELSE
  579.      *         Prompt for current password
  580.      *         IF (password doesn't match) THEN
  581.      *             Display error
  582.      *         ELSE
  583.      *             Store index of current login info
  584.      *             Prompt for new password
  585.      *             WHILE (password is too short)
  586.      *                 Reprompt for new password
  587.      *             END WHILE
  588.      *             Set login info's password to entered password
  589.      *             Replace index with new login info
  590.      *             Display success message
  591.      *         END IF
  592.      *     END IF
  593.      * END Change Password
  594.      **********************************************************************************************/
  595.     public static void changePassword(ArrayList<String[]> loginPairs, String[] loginInfo)
  596.     {
  597.         //Local constants
  598.         final boolean APPEND      = true;   //Append to a file when writing
  599.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  600.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  601.         final int PAD             = 18;     //Character padding for output
  602.         final int MIN_LENGTH      = 5;      //Minimum password length
  603.  
  604.         //Local variables
  605.         BufferedWriter writer;              //Utility object writes to file writer
  606.         boolean confirmed;                  //Whether current password was confirmed
  607.         int index;                          //Index of login
  608.         String passwordAttempt;             //User's attempt to confirm password
  609.         String newPassword;                 //User's new password
  610.  
  611.         /*****************************  Start Change Password Method  *****************************/
  612.  
  613.         //IF (no one is logged in) THEN
  614.         if (loginInfo[LOGIN_USERNAME] == null || loginInfo[LOGIN_USERNAME].isEmpty())
  615.         {
  616.             //Display error message
  617.             System.out.println(Console.padLeft(PAD, "Please log in to change your password.\n"));
  618.         }
  619.        
  620.         //ELSE (someone is logged in)
  621.         else
  622.         {
  623.             //Prompt for current password
  624.             System.out.print(Console.padLeft(PAD, "Enter current password: "));
  625.             passwordAttempt = Keyboard.readString();
  626.            
  627.             //IF (password doesn't match) THEN
  628.             if (!passwordAttempt.equals(loginInfo[LOGIN_PASSWORD]))
  629.             {
  630.                 //Display error
  631.                 System.out.println(Console.padLeft(PAD, "Incorrect password.\n"));
  632.             }
  633.            
  634.             //ELSE (password matches)
  635.             else
  636.             {
  637.  
  638.                 //Store index of current login info
  639.                 index = getIndex(loginPairs, loginInfo);
  640.  
  641.                 //Prompt for new password
  642.                 System.out.print(Console.padLeft(PAD, "Enter new password: "));
  643.                 newPassword = Keyboard.readString();
  644.  
  645.                 //WHILE (password is too short)
  646.                 while (newPassword.length() < MIN_LENGTH)
  647.                 {
  648.                     //Reprompt for new password
  649.                     System.out.print(Console.padLeft(PAD, "Enter new password (min "
  650.                                                                 + MIN_LENGTH + " characters): "));
  651.                     newPassword = Keyboard.readString();
  652.  
  653.                 }//end while password is too short
  654.  
  655.                 //Set login info's password to entered password
  656.                 loginInfo[LOGIN_PASSWORD] = newPassword;
  657.  
  658.                 //Replace index with new login info
  659.                 loginPairs.set(index, loginInfo);
  660.                
  661.                 //Display success message
  662.                 System.out.println(Console.padLeft(PAD, "Password changed successfully!\n"));
  663.  
  664.             }//end if password matches
  665.         }//end if someone is logged in
  666.  
  667.     }//end method change password
  668.  
  669.     /**********************************************************************************************
  670.      * Method Name    : FileIO - Get Index
  671.      * Author         : Terry Weiss
  672.      * Date           : March 4, 2016
  673.      * Course/Section : CSC264 - 001
  674.      * Program Description: This method gets the index of a given login in the login list. A
  675.      *     login matches with a case insensitive username and case sensitive password.
  676.      *
  677.      * BEGIN Get Index
  678.      *     Init found to false
  679.      *     Init index to 0
  680.      *     WHILE (there are more logins AND login wasn't found)
  681.      *         IF (username/password matches current pair's username/password)
  682.      *             Set found to true
  683.      *         ELSE
  684.      *             Increment index
  685.      *         END IF
  686.      *     END WHILE
  687.      *     IF (login wasn't found) THEN
  688.      *         Set index to not found
  689.      *     END IF
  690.      *     Return index
  691.      * END Get Index
  692.      **********************************************************************************************/
  693.     private static int getIndex(ArrayList<String[]> loginPairs, String[] loginInfo)
  694.     {
  695.         //Local constants
  696.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  697.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  698.         final int NOT_FOUND       = -1;     //Index if login wasn't found
  699.  
  700.         //Local variables
  701.         boolean found;      //Whether login was found
  702.         int index;          //Index of login
  703.  
  704.         /*******************************  Start File Exists Method  *******************************/
  705.  
  706.         //Init found to false
  707.         found = false;
  708.  
  709.         //Init index to 0
  710.         index = 0;
  711.  
  712.         //WHILE (there are more logins AND login wasn't found)
  713.         while (index < loginPairs.size() && !found)
  714.         {
  715.             //IF (username/password matches current pair's username/password)
  716.             if (loginPairs.get(index)[LOGIN_USERNAME].equalsIgnoreCase(loginInfo[LOGIN_USERNAME])
  717.                     && loginPairs.get(index)[LOGIN_PASSWORD].equals(loginInfo[LOGIN_PASSWORD]))
  718.             {
  719.                 //Set found to true
  720.                 found = true;
  721.             }
  722.            
  723.             //ELSE username/passwords don't match
  724.             else
  725.             {
  726.                 //Increment index
  727.                 index++;
  728.  
  729.             }//end if username/password matches
  730.         }//end while more logins and not found
  731.  
  732.         //IF (login wasn't found) THEN
  733.         if (!found)
  734.         {
  735.             //Set index to not found
  736.             index = NOT_FOUND;
  737.         }
  738.  
  739.         //Return index
  740.         return index;
  741.  
  742.     }//end method file exists
  743.  
  744.     /**********************************************************************************************
  745.      * Method Name    : FileIO - Exit
  746.      * Author         : Terry Weiss
  747.      * Date           : March 4, 2016
  748.      * Course/Section : CSC264 - 001
  749.      * Program Description: This method saves the new login info and log to their files before
  750.      *     the program exits.
  751.      *
  752.      * BEGIN Exit
  753.      *     Init empty writer
  754.      *     TRY to write the pairs
  755.      *         Open writer to write logins info back to file
  756.      *         FOR (each login pair)
  757.      *             Write username and password to the file with a space between them
  758.      *         END FOR
  759.      *     CATCH (IO exception)
  760.      *         Display unable to write to logins file
  761.      *     FINALLY
  762.      *         Flush writer
  763.      *         Close writer
  764.      *     END TRY-CATCH-FINALLY
  765.      *     TRY to write the log
  766.      *         IF (log file exists) THEN
  767.      *             Open writer to append log back to file
  768.      *         ELSE
  769.      *             Open writer to write log back to file
  770.      *         END IF
  771.      *         FOR (each log entry)
  772.      *             Write the log entry to log file
  773.      *         END FOR
  774.      *     CATCH (IO Exception)
  775.      *         Display unable to write to log file
  776.      *     FINALLY
  777.      *         Flush writer
  778.      *         Close writer
  779.      *     END TRY-CATCH-FINALLY
  780.      * END Exit
  781.      **********************************************************************************************/
  782.     private static void exit(String loginsFilename, ArrayList<String[]> pairs, String logFilename,
  783.                                 ArrayList<String> log)
  784.             throws IOException
  785.     {
  786.         //Local constants
  787.         final boolean APPEND      = true;   //Append to a file when writing
  788.         final int LOGIN_USERNAME  = 0;      //Username index in login info
  789.         final int LOGIN_PASSWORD  = 1;      //Password index in login info
  790.         final int PAD             = 18;     //Character padding for output
  791.  
  792.         //Local variables
  793.         BufferedWriter writer;              //Utility object writes to file writer
  794.  
  795.         /**********************************  Start Exit Method  ***********************************/
  796.  
  797.         //Init empty writer
  798.         writer = null;
  799.  
  800.         //TRY to write the pairs
  801.         try
  802.         {
  803.             //Open writer to write logins info back to file
  804.             writer = new BufferedWriter(new FileWriter(loginsFilename));
  805.  
  806.             //FOR (each login pair)
  807.             for (String[] pair : pairs)
  808.             {
  809.                 //Write username and password to the file with a space between them
  810.                 writer.write(pair[LOGIN_USERNAME] + " " + pair[LOGIN_PASSWORD] + "\n");
  811.             }
  812.         }
  813.  
  814.         //CATCH (IO exception)
  815.         catch (IOException e)
  816.         {
  817.             //Display unable to write to logins file
  818.             System.out.println(Console.center("!! UNABLE TO WRITE TO LOGINS FILE !!"));
  819.         }
  820.  
  821.         //FINALLY
  822.         finally
  823.         {
  824.             //Flush writer
  825.             writer.flush();
  826.  
  827.             //Close writer
  828.             writer.close();
  829.         }//end try-catch-finally writing to logins info file
  830.  
  831.  
  832.         //TRY to write the log
  833.         try
  834.         {
  835.             //IF (log file exists) THEN
  836.             if (fileExists(logFilename))
  837.             {
  838.                 //Open writer to append log back to file
  839.                 writer = new BufferedWriter(new FileWriter(logFilename, APPEND));
  840.             }
  841.  
  842.             //ELSE (log file doesn't exist)
  843.             else
  844.             {
  845.                 //Open writer to write log back to file
  846.                 writer = new BufferedWriter(new FileWriter(logFilename));
  847.             }//end if log file exists
  848.  
  849.             //FOR (each log entry)
  850.             for (String entry : log)
  851.             {
  852.                 //Write the log entry to log file
  853.                 writer.write(entry + "\n");
  854.             }//end for each log entry
  855.         }
  856.  
  857.         //CATCH (IO Exception)
  858.         catch (IOException e)
  859.         {
  860.             //Display unable to write to log file
  861.             System.out.println(Console.center("!! UNABLE TO WRITE TO LOG FILE !!"));
  862.         }
  863.  
  864.         //FINALLY
  865.         finally
  866.         {
  867.             //Flush writer
  868.             writer.flush();
  869.  
  870.             //Close writer
  871.             writer.close();
  872.         }//end try-catch-finally writing to log file
  873.  
  874.     }//end method exit
  875.  
  876. }//end class File IO
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement