SlideShare a Scribd company logo
PasswordCheckerGUI.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.geometry.Insets;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class PasswordCheckerGUI extends Application {
Label passwordRulesLabel; // Declares variable to display the rules of setting a valid
password
Label passwordLabel; // Declares variable to hold the "Password" Label
Label retypePasswordLabel; // Declares variable to hold the "Re-type Password"
Label
TextField passwordTextField; // Declares variable to hold the "Password" entry textfield
TextField retypePasswordTextField; // Declares variable to hold the "Re-type Password"
entry textfield
Button checkPasswordButton; // Declares variable to hold the "Check Password" button
Button checkFilePasswordsButton; // Declares variable to hold the "Check Passwords in
File" button
Button exitButton; // Declares variable to hold the "Exit" button
// Creates an instance of the PasswordChecker class to use in order to validate the passwords
PasswordChecker check = new PasswordChecker();
@Override
public void start(Stage stage)
{
// Create the label that will display the rules of creating a password
passwordRulesLabel = new Label("Use the following rules when creating your passwords
"
+ "1. Length must be greater than 8 "
+ "2. Must contain at least one upper case alpha character "
+ "3. Must contain at least on lower case alpha character "
+ "4. Must contain at least one numeric character "
+ "5. May not have more than 2 of the same character in sequence ");
// Create the password and re-type password labels to let the user know where to enter their
desired password
passwordLabel = new Label("Password");
retypePasswordLabel = new Label("Re-typePassword");
// Create the textfields to allow the user to enter their desired password
passwordTextField = new TextField();
passwordTextField.setPrefWidth(210);
retypePasswordTextField = new TextField();
retypePasswordTextField.setPrefWidth(210);
// Create the buttons that will be used by the password application to perform its functions.
checkPasswordButton = new Button("_Check Password");
// Assign the C key as the mnemonic for the "Check Password" button
checkPasswordButton.setMnemonicParsing(true);
// Add a tooltip to the "Check Password" button
checkPasswordButton.setTooltip(new Tooltip("Click here to check if the desired password
is valid."));
checkPasswordButton.setPadding(new Insets(5, 18, 5, 18));
checkFilePasswordsButton = new Button("Check Passwo_rds in File");
// Assign the R key as the mnemonic for the "Check Passwords in File" button
checkFilePasswordsButton.setMnemonicParsing(true);
// Add a tooltip to the "Check Passwords in File" button
checkFilePasswordsButton.setTooltip(new Tooltip("Click here to select the file containing
the passwords."));
checkFilePasswordsButton.setPadding(new Insets(5, 18, 5, 18));
exitButton = new Button("_Exit");
// Assign the E key as the mnemonic for the "Exit" button
exitButton.setMnemonicParsing(true);
// Add a tooltip to the "Exit" button
exitButton.setTooltip(new Tooltip("Click here to exit."));
exitButton.setPadding(new Insets(5, 18, 5, 18));
// Sets event handlers on each button, which will perform different actions, depending on
which button the user clicks.
checkPasswordButton.setOnAction(new CheckPasswordButtonEventHandler());
checkFilePasswordsButton.setOnAction(new CheckFilePasswordsButtonEventHandler());
exitButton.setOnAction(new ExitButtonEventHandler());
// Create a horizontal box that will hold the "Password" label and textfield in one row
HBox passwordInput = new HBox(10);
passwordInput.setAlignment(Pos.CENTER);
passwordInput.getChildren().addAll(passwordLabel,passwordTextField);
// Create a horizontal box that will hold the "Re-type Password" label and textfield in one
row
HBox retypePasswordInput = new HBox(10);
retypePasswordInput.setAlignment(Pos.CENTER);
retypePasswordInput.getChildren().addAll(retypePasswordLabel,retypePasswordTextField);
// Create a verticle box, that will nest the passwordInput and retypePasswordInput panes on
top of each other.
VBox passwordInfoPane = new VBox(10);
passwordInfoPane.setPadding(new Insets(20, 0, 40, 0));
passwordInfoPane.setAlignment(Pos.CENTER);
// Add the buttons to the children of the buttonPane horizontal box
passwordInfoPane.getChildren().addAll(passwordInput,retypePasswordInput);
// Create a horizontal box, that will place all the buttons next to each other, that will be used
in the GUI.
HBox buttonPane = new HBox(25);
buttonPane.setAlignment(Pos.CENTER);
// Add the buttons to the children of the buttonPane horizontal box
buttonPane.getChildren().addAll(checkPasswordButton,checkFilePasswordsButton,exitButton);
// Create a vertical box that will nest the passwordRulesLabel on top, followed by the
passwordInfoPane, and then the buttonPane at the bottom.
VBox contentPane = new VBox(30);
contentPane.setAlignment(Pos.CENTER);
contentPane.setPadding(new Insets(15, 50, 10, 50));
contentPane.getChildren().addAll( passwordRulesLabel,passwordInfoPane, buttonPane);
// Create a BorderPane to place contentPane into the center of the GUI display.
// contentPane contains all the nested Hbox's and Vbox's that were created to properly
organize and display the contents of the GUI application.
BorderPane displayPane = new BorderPane();
// Place the contentPane in the center region of the BorderPane.
displayPane.setCenter(contentPane);
// Set displayPane as root of scene and set the scene on the stage
Scene scene = new Scene(displayPane);
stage.setTitle("Password Checker");
stage.setScene(scene);
stage.show();
}
// Will check to see if the password that is entered by the user is valid, and it will catch the
appropriate exception thrown if it's not.
class CheckPasswordButtonEventHandler implements EventHandler
{
@Override
public void handle(ActionEvent event)
{
String password = null;
String retypedPassword = null;
// Extract the password and retyped password from the input textfields
password = passwordTextField.getText().trim();
retypedPassword = retypePasswordTextField.getText().trim();
try
{
// If the password and re-typed passwords are not the same, then throw an
UnmatchedException.
if(!password.equals(retypedPassword))
{
UnmatchedException exception = new UnmatchedException ("The passwords do
not match");
throw exception;
}
// Use the object created from the instance of the PasswordChecker class to call the
isValidPassword method, and determine whether the password entered is valid or not.
// If the passwrod is not valid, then it will throw an exception.
check.isValidPassword(password);
// If no exception is thrown, then display to user that password is valid.
JOptionPane.showMessageDialog(null, "Password is valid", "Password Status",
JOptionPane.INFORMATION_MESSAGE);
}
// If the isValidPassword method from the PasswordChecker class throws a
UnmatchedException, then catch it and display the appropriate message.
catch (UnmatchedException exception)
{
JOptionPane.showMessageDialog(null, "UnmatchedException: The passwords do not
match.", "Password Status", JOptionPane.INFORMATION_MESSAGE);
exception.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
LengthException, then catch it and display the appropriate message.
catch (LengthException e) {
JOptionPane.showMessageDialog(null, "LengthException: The password must be at
least 8 characters long.", "Password Error", JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
NoDigitException, then catch it and display the appropriate message.
catch (NoDigitException e) {
JOptionPane.showMessageDialog(null, "NoDigitException: The password must
contain at least one digit.","Password Error", JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
NoUpperAlphaException, then catch it and display the appropriate message.
catch (NoUpperAlphaException e) {
JOptionPane.showMessageDialog(null, "NoUpperAlphaException: The password
must contain at least one uppercase alphabetic character.", "Password Error",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
NoLowerAlphaException, then catch it and display the appropriate message.
catch (NoLowerAlphaException e) {
JOptionPane.showMessageDialog(null, "NoLowerAlphaException: The password
must contain at least one lowercase alphabetic character.","Password Error",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
InvalidSequenceException, then catch it and display the appropriate message.
catch (InvalidSequenceException e) {
JOptionPane.showMessageDialog(null, "InvalidSequenceException: The password
cannot contain more than two of the same character in sequence.","Password Error",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
}
}
// It will check to see which passwords are invalid from the file that is read in, and also display
its error status.
class CheckFilePasswordsButtonEventHandler implements EventHandler
{
@Override
public void handle(ActionEvent event)
{
File selectedFile = null;
Scanner inputFile;
ArrayList passwordList = new ArrayList<>(); // Declares a String ArrayList to hold the
contents of the file being read.
ArrayList illegalList = new ArrayList<>(); // Declares a String ArrayList to hold all the
invalid passwords from the file that was read in.
// Will display a window box allowing the user to select a file from their computer to
open, in order to read its list of passwords.
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
selectedFile = fileChooser.getSelectedFile();
}
try
{
inputFile = new Scanner(selectedFile);
// Read each password, line by line from the .txt file into a String ArrayList
while (inputFile.hasNext())
{
passwordList.add(inputFile.nextLine());
}
illegalList = check.validPasswords(passwordList);
// A string that will display all the invalid passwords and their error status messages
one by one in a new row.
String illegal = "";
// Loop through the illegalList ArrayList and place each invalid password one by one
in a new row in the string.
for(int i =0; i < illegalList.size(); i++)
{
illegal += illegalList.get(i) + " ";
}
// Display a message to the user showing all the invalid passwords that were read from
the file, along with their error status message.
JOptionPane.showMessageDialog(null, illegal, "Illegal passwords",
JOptionPane.INFORMATION_MESSAGE);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
// Will exit the program, if user clicks the "Exit" button.
class ExitButtonEventHandler implements EventHandler
{
@Override
public void handle(ActionEvent event)
{
System.exit(0);
}
}
// Will launch the GUI for the PasswordChecker application.
public static void main(String[] args) {
launch(args);
}
}
PasswordChecker.java
import java.util.ArrayList;
public class PasswordChecker implements PasswordCheckerInterface {
private String password; // Will hold the string that is passed into the
isValidPassword method.
private ArrayList illegalPasswords; // Will hold the list of passwords that are found to be
invalid from the list that is passed into the validPasswords method.
public boolean isValidPassword (String passwordString) throws LengthException,
NoDigitException, NoUpperAlphaException, NoLowerAlphaException,
InvalidSequenceException
{
password = passwordString;
char ch = password.charAt(0);
// If the password is less than 8 characters, then throw the lengthException.
if( password.length() < 8)
{
throw new LengthException ("The password must be at least 8 characters long.");
}
// If the first character in the password is not a numeric character, then check to see if the
rest of the password contains at least one numeric character.
if(!Character.isDigit(ch))
{
// Set the initial value of hasDigit to be false
boolean hasDigit = false;
// Loop through the length of the password, and if there is a character that has a digit, then
the variable hasDigit will be true.
for (int i = 0; i < password.length(); i++)
{
ch = password.charAt(i);
if(Character.isDigit(ch))
{
hasDigit = true;
}
}
// If there is no digit, then throw the NoDigitException
if(!hasDigit)
{
throw new NoDigitException ("The password must contain at least one digit.");
}
}
// If the first character in the password is not upper case, then check to see if the rest of the
password contains at least one upper case letter.
if(!Character.isUpperCase(ch))
{
boolean hasUppercase = !password.equals(password.toLowerCase());
//If the password does not have uppercase, then throw the NoUpperAlphaException.
if(!hasUppercase)
{
throw new NoUpperAlphaException ("The password must contain at least one uppercase
alphabetic character.");
}
}
// If the first character in the password is not lower case, then check to see if the rest of the
password contains at least one lower case letter.
if(!Character.isLowerCase(ch))
{
boolean hasLowercase = !password.equals(password.toUpperCase());
if(!hasLowercase)
{
throw new NoLowerAlphaException ("The password must contain at least one
lowercase alphabetic character.");
}
}
// If the first character in the password is either a lower case, upper case, or numeric
character, then check to see if the password does not contain more than 2 of the same character
in sequence.
if(Character.isLowerCase(ch) || Character.isUpperCase(ch) || Character.isDigit(ch) )
{
for (int i = 0; i < password.length() - 2; i++)
{
if( (password.charAt(i) == password.charAt(i + 1)) && (password.charAt(i) ==
password.charAt(i+2)) )
{
throw new InvalidSequenceException ("The password cannot contain more than
two of the same character in sequence.");
}
}
}
return true;
}
/**
* Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid
passwords.
*/
public ArrayList validPasswords(ArrayList passwords)
{
// an ArrayList to hold all the invalid passwords found
illegalPasswords = new ArrayList();
String errorMessage = null;
for(int i = 0; i < passwords.size(); i++)
{
try
{
isValidPassword(passwords.get(i));
}
catch (LengthException e)
{
errorMessage = passwords.get(i) + " The password must be at least 8 characters
long.";
illegalPasswords.add(errorMessage);
}
catch (NoDigitException e) {
errorMessage = passwords.get(i) + " The password must contain at least one digit.";
illegalPasswords.add(errorMessage);
}
catch (NoUpperAlphaException e) {
errorMessage = passwords.get(i) + " The password must contain at least one
uppercase alphabetic character.";
illegalPasswords.add(errorMessage);
}
catch (NoLowerAlphaException e) {
errorMessage = passwords.get(i) + " The password must contain at least one
lowercase alphabetic character.";
illegalPasswords.add(errorMessage);
}
catch (InvalidSequenceException e) {
errorMessage = passwords.get(i) + " The password cannot contain more than two of
the same character in sequence.";
illegalPasswords.add(errorMessage);
}
}
//Return the ArrayList that contains all the invalid passwords only
return illegalPasswords;
}
}
PasswordCheckerInterface.java
import java.util.ArrayList;
public interface PasswordCheckerInterface {
/**
* Will check the validity of the password passed in, and returns true if the password is valid,
or throws an exception if invalid.
*/
public boolean isValidPassword (String passwordString) throws LengthException,
NoDigitException, NoUpperAlphaException, NoLowerAlphaException,
InvalidSequenceException;
/**
* Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid
passwords.
*/
public ArrayList validPasswords (ArrayList passwords);
}
NoDigitException.java
@SuppressWarnings("serial")
public class NoDigitException extends Exception {
public NoDigitException()
{
}
/**
* Constructor that will take in a message, which will be displayed if NoDigitException is
thrown.
*/
public NoDigitException(String message)
{
super(message);
}
}
LengthException.java
@SuppressWarnings("serial")
public class LengthException extends Exception
{
public LengthException()
{
}
/**
* Constructor that will take in a message, which will be displayed if LengthException is
thrown.
*/
public LengthException(String message)
{
super(message);
}
}
NoUpperAlphaException.java
@SuppressWarnings("serial")
public class NoUpperAlphaException extends Exception {
public NoUpperAlphaException()
{
}
/**
* Constructor that will take in a message, which will be displayed if NoUpperAlphaException
is thrown.
*/
public NoUpperAlphaException(String message)
{
super(message);
}
}
NoLowerAlphaException.java
@SuppressWarnings("serial")
public class NoLowerAlphaException extends Exception {
public NoLowerAlphaException()
{
}
/**
* Constructor that will take in a message, which will be displayed if NoLowerAlphaException
is thrown.
*/
public NoLowerAlphaException(String message)
{
super(message);
}
}
InvalidSequenceException.java
@SuppressWarnings("serial")
public class InvalidSequenceException extends Exception {
public InvalidSequenceException()
{
}
/**
* Constructor that will take in a message, which will be displayed if
InvalidSequenceException is thrown.
*/
public InvalidSequenceException(String message)
{
super(message);
}
}
Solution
PasswordCheckerGUI.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.geometry.Insets;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class PasswordCheckerGUI extends Application {
Label passwordRulesLabel; // Declares variable to display the rules of setting a valid
password
Label passwordLabel; // Declares variable to hold the "Password" Label
Label retypePasswordLabel; // Declares variable to hold the "Re-type Password"
Label
TextField passwordTextField; // Declares variable to hold the "Password" entry textfield
TextField retypePasswordTextField; // Declares variable to hold the "Re-type Password"
entry textfield
Button checkPasswordButton; // Declares variable to hold the "Check Password" button
Button checkFilePasswordsButton; // Declares variable to hold the "Check Passwords in
File" button
Button exitButton; // Declares variable to hold the "Exit" button
// Creates an instance of the PasswordChecker class to use in order to validate the passwords
PasswordChecker check = new PasswordChecker();
@Override
public void start(Stage stage)
{
// Create the label that will display the rules of creating a password
passwordRulesLabel = new Label("Use the following rules when creating your passwords
"
+ "1. Length must be greater than 8 "
+ "2. Must contain at least one upper case alpha character "
+ "3. Must contain at least on lower case alpha character "
+ "4. Must contain at least one numeric character "
+ "5. May not have more than 2 of the same character in sequence ");
// Create the password and re-type password labels to let the user know where to enter their
desired password
passwordLabel = new Label("Password");
retypePasswordLabel = new Label("Re-typePassword");
// Create the textfields to allow the user to enter their desired password
passwordTextField = new TextField();
passwordTextField.setPrefWidth(210);
retypePasswordTextField = new TextField();
retypePasswordTextField.setPrefWidth(210);
// Create the buttons that will be used by the password application to perform its functions.
checkPasswordButton = new Button("_Check Password");
// Assign the C key as the mnemonic for the "Check Password" button
checkPasswordButton.setMnemonicParsing(true);
// Add a tooltip to the "Check Password" button
checkPasswordButton.setTooltip(new Tooltip("Click here to check if the desired password
is valid."));
checkPasswordButton.setPadding(new Insets(5, 18, 5, 18));
checkFilePasswordsButton = new Button("Check Passwo_rds in File");
// Assign the R key as the mnemonic for the "Check Passwords in File" button
checkFilePasswordsButton.setMnemonicParsing(true);
// Add a tooltip to the "Check Passwords in File" button
checkFilePasswordsButton.setTooltip(new Tooltip("Click here to select the file containing
the passwords."));
checkFilePasswordsButton.setPadding(new Insets(5, 18, 5, 18));
exitButton = new Button("_Exit");
// Assign the E key as the mnemonic for the "Exit" button
exitButton.setMnemonicParsing(true);
// Add a tooltip to the "Exit" button
exitButton.setTooltip(new Tooltip("Click here to exit."));
exitButton.setPadding(new Insets(5, 18, 5, 18));
// Sets event handlers on each button, which will perform different actions, depending on
which button the user clicks.
checkPasswordButton.setOnAction(new CheckPasswordButtonEventHandler());
checkFilePasswordsButton.setOnAction(new CheckFilePasswordsButtonEventHandler());
exitButton.setOnAction(new ExitButtonEventHandler());
// Create a horizontal box that will hold the "Password" label and textfield in one row
HBox passwordInput = new HBox(10);
passwordInput.setAlignment(Pos.CENTER);
passwordInput.getChildren().addAll(passwordLabel,passwordTextField);
// Create a horizontal box that will hold the "Re-type Password" label and textfield in one
row
HBox retypePasswordInput = new HBox(10);
retypePasswordInput.setAlignment(Pos.CENTER);
retypePasswordInput.getChildren().addAll(retypePasswordLabel,retypePasswordTextField);
// Create a verticle box, that will nest the passwordInput and retypePasswordInput panes on
top of each other.
VBox passwordInfoPane = new VBox(10);
passwordInfoPane.setPadding(new Insets(20, 0, 40, 0));
passwordInfoPane.setAlignment(Pos.CENTER);
// Add the buttons to the children of the buttonPane horizontal box
passwordInfoPane.getChildren().addAll(passwordInput,retypePasswordInput);
// Create a horizontal box, that will place all the buttons next to each other, that will be used
in the GUI.
HBox buttonPane = new HBox(25);
buttonPane.setAlignment(Pos.CENTER);
// Add the buttons to the children of the buttonPane horizontal box
buttonPane.getChildren().addAll(checkPasswordButton,checkFilePasswordsButton,exitButton);
// Create a vertical box that will nest the passwordRulesLabel on top, followed by the
passwordInfoPane, and then the buttonPane at the bottom.
VBox contentPane = new VBox(30);
contentPane.setAlignment(Pos.CENTER);
contentPane.setPadding(new Insets(15, 50, 10, 50));
contentPane.getChildren().addAll( passwordRulesLabel,passwordInfoPane, buttonPane);
// Create a BorderPane to place contentPane into the center of the GUI display.
// contentPane contains all the nested Hbox's and Vbox's that were created to properly
organize and display the contents of the GUI application.
BorderPane displayPane = new BorderPane();
// Place the contentPane in the center region of the BorderPane.
displayPane.setCenter(contentPane);
// Set displayPane as root of scene and set the scene on the stage
Scene scene = new Scene(displayPane);
stage.setTitle("Password Checker");
stage.setScene(scene);
stage.show();
}
// Will check to see if the password that is entered by the user is valid, and it will catch the
appropriate exception thrown if it's not.
class CheckPasswordButtonEventHandler implements EventHandler
{
@Override
public void handle(ActionEvent event)
{
String password = null;
String retypedPassword = null;
// Extract the password and retyped password from the input textfields
password = passwordTextField.getText().trim();
retypedPassword = retypePasswordTextField.getText().trim();
try
{
// If the password and re-typed passwords are not the same, then throw an
UnmatchedException.
if(!password.equals(retypedPassword))
{
UnmatchedException exception = new UnmatchedException ("The passwords do
not match");
throw exception;
}
// Use the object created from the instance of the PasswordChecker class to call the
isValidPassword method, and determine whether the password entered is valid or not.
// If the passwrod is not valid, then it will throw an exception.
check.isValidPassword(password);
// If no exception is thrown, then display to user that password is valid.
JOptionPane.showMessageDialog(null, "Password is valid", "Password Status",
JOptionPane.INFORMATION_MESSAGE);
}
// If the isValidPassword method from the PasswordChecker class throws a
UnmatchedException, then catch it and display the appropriate message.
catch (UnmatchedException exception)
{
JOptionPane.showMessageDialog(null, "UnmatchedException: The passwords do not
match.", "Password Status", JOptionPane.INFORMATION_MESSAGE);
exception.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
LengthException, then catch it and display the appropriate message.
catch (LengthException e) {
JOptionPane.showMessageDialog(null, "LengthException: The password must be at
least 8 characters long.", "Password Error", JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
NoDigitException, then catch it and display the appropriate message.
catch (NoDigitException e) {
JOptionPane.showMessageDialog(null, "NoDigitException: The password must
contain at least one digit.","Password Error", JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
NoUpperAlphaException, then catch it and display the appropriate message.
catch (NoUpperAlphaException e) {
JOptionPane.showMessageDialog(null, "NoUpperAlphaException: The password
must contain at least one uppercase alphabetic character.", "Password Error",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
NoLowerAlphaException, then catch it and display the appropriate message.
catch (NoLowerAlphaException e) {
JOptionPane.showMessageDialog(null, "NoLowerAlphaException: The password
must contain at least one lowercase alphabetic character.","Password Error",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
// If the isValidPassword method from the PasswordChecker class throws a
InvalidSequenceException, then catch it and display the appropriate message.
catch (InvalidSequenceException e) {
JOptionPane.showMessageDialog(null, "InvalidSequenceException: The password
cannot contain more than two of the same character in sequence.","Password Error",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
}
}
// It will check to see which passwords are invalid from the file that is read in, and also display
its error status.
class CheckFilePasswordsButtonEventHandler implements EventHandler
{
@Override
public void handle(ActionEvent event)
{
File selectedFile = null;
Scanner inputFile;
ArrayList passwordList = new ArrayList<>(); // Declares a String ArrayList to hold the
contents of the file being read.
ArrayList illegalList = new ArrayList<>(); // Declares a String ArrayList to hold all the
invalid passwords from the file that was read in.
// Will display a window box allowing the user to select a file from their computer to
open, in order to read its list of passwords.
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
selectedFile = fileChooser.getSelectedFile();
}
try
{
inputFile = new Scanner(selectedFile);
// Read each password, line by line from the .txt file into a String ArrayList
while (inputFile.hasNext())
{
passwordList.add(inputFile.nextLine());
}
illegalList = check.validPasswords(passwordList);
// A string that will display all the invalid passwords and their error status messages
one by one in a new row.
String illegal = "";
// Loop through the illegalList ArrayList and place each invalid password one by one
in a new row in the string.
for(int i =0; i < illegalList.size(); i++)
{
illegal += illegalList.get(i) + " ";
}
// Display a message to the user showing all the invalid passwords that were read from
the file, along with their error status message.
JOptionPane.showMessageDialog(null, illegal, "Illegal passwords",
JOptionPane.INFORMATION_MESSAGE);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
// Will exit the program, if user clicks the "Exit" button.
class ExitButtonEventHandler implements EventHandler
{
@Override
public void handle(ActionEvent event)
{
System.exit(0);
}
}
// Will launch the GUI for the PasswordChecker application.
public static void main(String[] args) {
launch(args);
}
}
PasswordChecker.java
import java.util.ArrayList;
public class PasswordChecker implements PasswordCheckerInterface {
private String password; // Will hold the string that is passed into the
isValidPassword method.
private ArrayList illegalPasswords; // Will hold the list of passwords that are found to be
invalid from the list that is passed into the validPasswords method.
public boolean isValidPassword (String passwordString) throws LengthException,
NoDigitException, NoUpperAlphaException, NoLowerAlphaException,
InvalidSequenceException
{
password = passwordString;
char ch = password.charAt(0);
// If the password is less than 8 characters, then throw the lengthException.
if( password.length() < 8)
{
throw new LengthException ("The password must be at least 8 characters long.");
}
// If the first character in the password is not a numeric character, then check to see if the
rest of the password contains at least one numeric character.
if(!Character.isDigit(ch))
{
// Set the initial value of hasDigit to be false
boolean hasDigit = false;
// Loop through the length of the password, and if there is a character that has a digit, then
the variable hasDigit will be true.
for (int i = 0; i < password.length(); i++)
{
ch = password.charAt(i);
if(Character.isDigit(ch))
{
hasDigit = true;
}
}
// If there is no digit, then throw the NoDigitException
if(!hasDigit)
{
throw new NoDigitException ("The password must contain at least one digit.");
}
}
// If the first character in the password is not upper case, then check to see if the rest of the
password contains at least one upper case letter.
if(!Character.isUpperCase(ch))
{
boolean hasUppercase = !password.equals(password.toLowerCase());
//If the password does not have uppercase, then throw the NoUpperAlphaException.
if(!hasUppercase)
{
throw new NoUpperAlphaException ("The password must contain at least one uppercase
alphabetic character.");
}
}
// If the first character in the password is not lower case, then check to see if the rest of the
password contains at least one lower case letter.
if(!Character.isLowerCase(ch))
{
boolean hasLowercase = !password.equals(password.toUpperCase());
if(!hasLowercase)
{
throw new NoLowerAlphaException ("The password must contain at least one
lowercase alphabetic character.");
}
}
// If the first character in the password is either a lower case, upper case, or numeric
character, then check to see if the password does not contain more than 2 of the same character
in sequence.
if(Character.isLowerCase(ch) || Character.isUpperCase(ch) || Character.isDigit(ch) )
{
for (int i = 0; i < password.length() - 2; i++)
{
if( (password.charAt(i) == password.charAt(i + 1)) && (password.charAt(i) ==
password.charAt(i+2)) )
{
throw new InvalidSequenceException ("The password cannot contain more than
two of the same character in sequence.");
}
}
}
return true;
}
/**
* Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid
passwords.
*/
public ArrayList validPasswords(ArrayList passwords)
{
// an ArrayList to hold all the invalid passwords found
illegalPasswords = new ArrayList();
String errorMessage = null;
for(int i = 0; i < passwords.size(); i++)
{
try
{
isValidPassword(passwords.get(i));
}
catch (LengthException e)
{
errorMessage = passwords.get(i) + " The password must be at least 8 characters
long.";
illegalPasswords.add(errorMessage);
}
catch (NoDigitException e) {
errorMessage = passwords.get(i) + " The password must contain at least one digit.";
illegalPasswords.add(errorMessage);
}
catch (NoUpperAlphaException e) {
errorMessage = passwords.get(i) + " The password must contain at least one
uppercase alphabetic character.";
illegalPasswords.add(errorMessage);
}
catch (NoLowerAlphaException e) {
errorMessage = passwords.get(i) + " The password must contain at least one
lowercase alphabetic character.";
illegalPasswords.add(errorMessage);
}
catch (InvalidSequenceException e) {
errorMessage = passwords.get(i) + " The password cannot contain more than two of
the same character in sequence.";
illegalPasswords.add(errorMessage);
}
}
//Return the ArrayList that contains all the invalid passwords only
return illegalPasswords;
}
}
PasswordCheckerInterface.java
import java.util.ArrayList;
public interface PasswordCheckerInterface {
/**
* Will check the validity of the password passed in, and returns true if the password is valid,
or throws an exception if invalid.
*/
public boolean isValidPassword (String passwordString) throws LengthException,
NoDigitException, NoUpperAlphaException, NoLowerAlphaException,
InvalidSequenceException;
/**
* Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid
passwords.
*/
public ArrayList validPasswords (ArrayList passwords);
}
NoDigitException.java
@SuppressWarnings("serial")
public class NoDigitException extends Exception {
public NoDigitException()
{
}
/**
* Constructor that will take in a message, which will be displayed if NoDigitException is
thrown.
*/
public NoDigitException(String message)
{
super(message);
}
}
LengthException.java
@SuppressWarnings("serial")
public class LengthException extends Exception
{
public LengthException()
{
}
/**
* Constructor that will take in a message, which will be displayed if LengthException is
thrown.
*/
public LengthException(String message)
{
super(message);
}
}
NoUpperAlphaException.java
@SuppressWarnings("serial")
public class NoUpperAlphaException extends Exception {
public NoUpperAlphaException()
{
}
/**
* Constructor that will take in a message, which will be displayed if NoUpperAlphaException
is thrown.
*/
public NoUpperAlphaException(String message)
{
super(message);
}
}
NoLowerAlphaException.java
@SuppressWarnings("serial")
public class NoLowerAlphaException extends Exception {
public NoLowerAlphaException()
{
}
/**
* Constructor that will take in a message, which will be displayed if NoLowerAlphaException
is thrown.
*/
public NoLowerAlphaException(String message)
{
super(message);
}
}
InvalidSequenceException.java
@SuppressWarnings("serial")
public class InvalidSequenceException extends Exception {
public InvalidSequenceException()
{
}
/**
* Constructor that will take in a message, which will be displayed if
InvalidSequenceException is thrown.
*/
public InvalidSequenceException(String message)
{
super(message);
}
}

More Related Content

DOCX
Library management system
PDF
Program-a. library is importedimport java.awt.; import j.pdf
DOCX
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx
PDF
JPasswordA.javaimport javax.swing.; import java.awt.; imp.pdf
DOCX
FileWrite.javaFileWrite.java  To change this license header.docx
DOCX
New microsoft office word document
PDF
correct the error import javaxswingJFrame import javaxs.pdf
PDF
IP project for class 12 cbse
Library management system
Program-a. library is importedimport java.awt.; import j.pdf
20-Arid-850 Ali Haider Cheema BSSE(5A) Evening MPL Assignement 08.docx
JPasswordA.javaimport javax.swing.; import java.awt.; imp.pdf
FileWrite.javaFileWrite.java  To change this license header.docx
New microsoft office word document
correct the error import javaxswingJFrame import javaxs.pdf
IP project for class 12 cbse

More from anjaniar7gallery (20)

PDF
Will be uploaded soonSolutionWill be uploaded soon.pdf
PDF
yeah...it is... you are 100 rightSolutionyeah...it is... you.pdf
PDF
trying to upload imageSolutiontrying to upload image.pdf
PDF
This is social movement of British textile artisans in the early nin.pdf
PDF
TCP RFC 793 TCPIP (Transmission Control ProtocolInternet Proto.pdf
PDF
Please let me know if you need more clarification.final String pat.pdf
PDF
sec-BuLi can be prepared by the reaction of sec-butyl halideswith li.pdf
PDF
pH + pOH = 14 pOH = 4.5 [OH-] = 10-4.5Fe(OH)2 --- Fe2+ + 2 O.pdf
PDF
Node for list storage. class Ndd { int data; Ndd next; N.pdf
PDF
Laser ScanningLaser scanning is an emerging data acquisition techn.pdf
PDF
InternetService.java import java.text.DecimalFormat; import jav.pdf
PDF
Importance of planning to the practice of managementSolutionIm.pdf
PDF
Hardware refers to all of the physical parts of a computer system. F.pdf
PDF
Events after the reporting period are those events favorable and unf.pdf
PDF
D is correctSolutionD is correct.pdf
PDF
Cost centersCost centers are Centers that incur costs for operati.pdf
PDF
Calcium Phosphate is a slightly soluble salt. Here isthe equation fo.pdf
PDF
c.250Solutionc.250.pdf
PDF
#! usrbinpython def Flatten(list) newList = [] for i in ra.pdf
PDF
a) Two domains are OD1 and OD2 domains. The common function of OD1 a.pdf
Will be uploaded soonSolutionWill be uploaded soon.pdf
yeah...it is... you are 100 rightSolutionyeah...it is... you.pdf
trying to upload imageSolutiontrying to upload image.pdf
This is social movement of British textile artisans in the early nin.pdf
TCP RFC 793 TCPIP (Transmission Control ProtocolInternet Proto.pdf
Please let me know if you need more clarification.final String pat.pdf
sec-BuLi can be prepared by the reaction of sec-butyl halideswith li.pdf
pH + pOH = 14 pOH = 4.5 [OH-] = 10-4.5Fe(OH)2 --- Fe2+ + 2 O.pdf
Node for list storage. class Ndd { int data; Ndd next; N.pdf
Laser ScanningLaser scanning is an emerging data acquisition techn.pdf
InternetService.java import java.text.DecimalFormat; import jav.pdf
Importance of planning to the practice of managementSolutionIm.pdf
Hardware refers to all of the physical parts of a computer system. F.pdf
Events after the reporting period are those events favorable and unf.pdf
D is correctSolutionD is correct.pdf
Cost centersCost centers are Centers that incur costs for operati.pdf
Calcium Phosphate is a slightly soluble salt. Here isthe equation fo.pdf
c.250Solutionc.250.pdf
#! usrbinpython def Flatten(list) newList = [] for i in ra.pdf
a) Two domains are OD1 and OD2 domains. The common function of OD1 a.pdf
Ad

Recently uploaded (20)

PPTX
Cell Types and Its function , kingdom of life
PDF
Computing-Curriculum for Schools in Ghana
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Classroom Observation Tools for Teachers
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
Updated Idioms and Phrasal Verbs in English subject
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Cell Types and Its function , kingdom of life
Computing-Curriculum for Schools in Ghana
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Practical Manual AGRO-233 Principles and Practices of Natural Farming
LDMMIA Reiki Yoga Finals Review Spring Summer
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Anesthesia in Laparoscopic Surgery in India
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Weekly quiz Compilation Jan -July 25.pdf
Classroom Observation Tools for Teachers
STATICS OF THE RIGID BODIES Hibbelers.pdf
Microbial disease of the cardiovascular and lymphatic systems
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Complications of Minimal Access Surgery at WLH
Yogi Goddess Pres Conference Studio Updates
Updated Idioms and Phrasal Verbs in English subject
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Final Presentation General Medicine 03-08-2024.pptx
A systematic review of self-coping strategies used by university students to ...
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Ad

PasswordCheckerGUI.javaimport javafx.application.Application; im.pdf

  • 1. PasswordCheckerGUI.java import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.layout.HBox; import javafx.stage.Stage; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.geometry.Insets; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class PasswordCheckerGUI extends Application { Label passwordRulesLabel; // Declares variable to display the rules of setting a valid password Label passwordLabel; // Declares variable to hold the "Password" Label Label retypePasswordLabel; // Declares variable to hold the "Re-type Password" Label TextField passwordTextField; // Declares variable to hold the "Password" entry textfield TextField retypePasswordTextField; // Declares variable to hold the "Re-type Password" entry textfield Button checkPasswordButton; // Declares variable to hold the "Check Password" button Button checkFilePasswordsButton; // Declares variable to hold the "Check Passwords in
  • 2. File" button Button exitButton; // Declares variable to hold the "Exit" button // Creates an instance of the PasswordChecker class to use in order to validate the passwords PasswordChecker check = new PasswordChecker(); @Override public void start(Stage stage) { // Create the label that will display the rules of creating a password passwordRulesLabel = new Label("Use the following rules when creating your passwords " + "1. Length must be greater than 8 " + "2. Must contain at least one upper case alpha character " + "3. Must contain at least on lower case alpha character " + "4. Must contain at least one numeric character " + "5. May not have more than 2 of the same character in sequence "); // Create the password and re-type password labels to let the user know where to enter their desired password passwordLabel = new Label("Password"); retypePasswordLabel = new Label("Re-typePassword"); // Create the textfields to allow the user to enter their desired password passwordTextField = new TextField(); passwordTextField.setPrefWidth(210); retypePasswordTextField = new TextField(); retypePasswordTextField.setPrefWidth(210); // Create the buttons that will be used by the password application to perform its functions. checkPasswordButton = new Button("_Check Password");
  • 3. // Assign the C key as the mnemonic for the "Check Password" button checkPasswordButton.setMnemonicParsing(true); // Add a tooltip to the "Check Password" button checkPasswordButton.setTooltip(new Tooltip("Click here to check if the desired password is valid.")); checkPasswordButton.setPadding(new Insets(5, 18, 5, 18)); checkFilePasswordsButton = new Button("Check Passwo_rds in File"); // Assign the R key as the mnemonic for the "Check Passwords in File" button checkFilePasswordsButton.setMnemonicParsing(true); // Add a tooltip to the "Check Passwords in File" button checkFilePasswordsButton.setTooltip(new Tooltip("Click here to select the file containing the passwords.")); checkFilePasswordsButton.setPadding(new Insets(5, 18, 5, 18)); exitButton = new Button("_Exit"); // Assign the E key as the mnemonic for the "Exit" button exitButton.setMnemonicParsing(true); // Add a tooltip to the "Exit" button exitButton.setTooltip(new Tooltip("Click here to exit.")); exitButton.setPadding(new Insets(5, 18, 5, 18)); // Sets event handlers on each button, which will perform different actions, depending on which button the user clicks. checkPasswordButton.setOnAction(new CheckPasswordButtonEventHandler()); checkFilePasswordsButton.setOnAction(new CheckFilePasswordsButtonEventHandler()); exitButton.setOnAction(new ExitButtonEventHandler()); // Create a horizontal box that will hold the "Password" label and textfield in one row HBox passwordInput = new HBox(10); passwordInput.setAlignment(Pos.CENTER); passwordInput.getChildren().addAll(passwordLabel,passwordTextField); // Create a horizontal box that will hold the "Re-type Password" label and textfield in one row
  • 4. HBox retypePasswordInput = new HBox(10); retypePasswordInput.setAlignment(Pos.CENTER); retypePasswordInput.getChildren().addAll(retypePasswordLabel,retypePasswordTextField); // Create a verticle box, that will nest the passwordInput and retypePasswordInput panes on top of each other. VBox passwordInfoPane = new VBox(10); passwordInfoPane.setPadding(new Insets(20, 0, 40, 0)); passwordInfoPane.setAlignment(Pos.CENTER); // Add the buttons to the children of the buttonPane horizontal box passwordInfoPane.getChildren().addAll(passwordInput,retypePasswordInput); // Create a horizontal box, that will place all the buttons next to each other, that will be used in the GUI. HBox buttonPane = new HBox(25); buttonPane.setAlignment(Pos.CENTER); // Add the buttons to the children of the buttonPane horizontal box buttonPane.getChildren().addAll(checkPasswordButton,checkFilePasswordsButton,exitButton); // Create a vertical box that will nest the passwordRulesLabel on top, followed by the passwordInfoPane, and then the buttonPane at the bottom. VBox contentPane = new VBox(30); contentPane.setAlignment(Pos.CENTER); contentPane.setPadding(new Insets(15, 50, 10, 50)); contentPane.getChildren().addAll( passwordRulesLabel,passwordInfoPane, buttonPane); // Create a BorderPane to place contentPane into the center of the GUI display. // contentPane contains all the nested Hbox's and Vbox's that were created to properly organize and display the contents of the GUI application. BorderPane displayPane = new BorderPane(); // Place the contentPane in the center region of the BorderPane.
  • 5. displayPane.setCenter(contentPane); // Set displayPane as root of scene and set the scene on the stage Scene scene = new Scene(displayPane); stage.setTitle("Password Checker"); stage.setScene(scene); stage.show(); } // Will check to see if the password that is entered by the user is valid, and it will catch the appropriate exception thrown if it's not. class CheckPasswordButtonEventHandler implements EventHandler { @Override public void handle(ActionEvent event) { String password = null; String retypedPassword = null; // Extract the password and retyped password from the input textfields password = passwordTextField.getText().trim(); retypedPassword = retypePasswordTextField.getText().trim(); try { // If the password and re-typed passwords are not the same, then throw an UnmatchedException. if(!password.equals(retypedPassword)) { UnmatchedException exception = new UnmatchedException ("The passwords do not match"); throw exception; } // Use the object created from the instance of the PasswordChecker class to call the isValidPassword method, and determine whether the password entered is valid or not. // If the passwrod is not valid, then it will throw an exception.
  • 6. check.isValidPassword(password); // If no exception is thrown, then display to user that password is valid. JOptionPane.showMessageDialog(null, "Password is valid", "Password Status", JOptionPane.INFORMATION_MESSAGE); } // If the isValidPassword method from the PasswordChecker class throws a UnmatchedException, then catch it and display the appropriate message. catch (UnmatchedException exception) { JOptionPane.showMessageDialog(null, "UnmatchedException: The passwords do not match.", "Password Status", JOptionPane.INFORMATION_MESSAGE); exception.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a LengthException, then catch it and display the appropriate message. catch (LengthException e) { JOptionPane.showMessageDialog(null, "LengthException: The password must be at least 8 characters long.", "Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a NoDigitException, then catch it and display the appropriate message. catch (NoDigitException e) { JOptionPane.showMessageDialog(null, "NoDigitException: The password must contain at least one digit.","Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a NoUpperAlphaException, then catch it and display the appropriate message. catch (NoUpperAlphaException e) { JOptionPane.showMessageDialog(null, "NoUpperAlphaException: The password must contain at least one uppercase alphabetic character.", "Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace();
  • 7. } // If the isValidPassword method from the PasswordChecker class throws a NoLowerAlphaException, then catch it and display the appropriate message. catch (NoLowerAlphaException e) { JOptionPane.showMessageDialog(null, "NoLowerAlphaException: The password must contain at least one lowercase alphabetic character.","Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a InvalidSequenceException, then catch it and display the appropriate message. catch (InvalidSequenceException e) { JOptionPane.showMessageDialog(null, "InvalidSequenceException: The password cannot contain more than two of the same character in sequence.","Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } } } // It will check to see which passwords are invalid from the file that is read in, and also display its error status. class CheckFilePasswordsButtonEventHandler implements EventHandler { @Override public void handle(ActionEvent event) { File selectedFile = null; Scanner inputFile; ArrayList passwordList = new ArrayList<>(); // Declares a String ArrayList to hold the contents of the file being read. ArrayList illegalList = new ArrayList<>(); // Declares a String ArrayList to hold all the invalid passwords from the file that was read in. // Will display a window box allowing the user to select a file from their computer to
  • 8. open, in order to read its list of passwords. JFileChooser fileChooser = new JFileChooser(); int status = fileChooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } try { inputFile = new Scanner(selectedFile); // Read each password, line by line from the .txt file into a String ArrayList while (inputFile.hasNext()) { passwordList.add(inputFile.nextLine()); } illegalList = check.validPasswords(passwordList); // A string that will display all the invalid passwords and their error status messages one by one in a new row. String illegal = ""; // Loop through the illegalList ArrayList and place each invalid password one by one in a new row in the string. for(int i =0; i < illegalList.size(); i++) { illegal += illegalList.get(i) + " "; } // Display a message to the user showing all the invalid passwords that were read from the file, along with their error status message. JOptionPane.showMessageDialog(null, illegal, "Illegal passwords", JOptionPane.INFORMATION_MESSAGE);
  • 9. } catch (FileNotFoundException e) { e.printStackTrace(); } } } // Will exit the program, if user clicks the "Exit" button. class ExitButtonEventHandler implements EventHandler { @Override public void handle(ActionEvent event) { System.exit(0); } } // Will launch the GUI for the PasswordChecker application. public static void main(String[] args) { launch(args); } } PasswordChecker.java import java.util.ArrayList; public class PasswordChecker implements PasswordCheckerInterface { private String password; // Will hold the string that is passed into the isValidPassword method. private ArrayList illegalPasswords; // Will hold the list of passwords that are found to be invalid from the list that is passed into the validPasswords method. public boolean isValidPassword (String passwordString) throws LengthException, NoDigitException, NoUpperAlphaException, NoLowerAlphaException, InvalidSequenceException
  • 10. { password = passwordString; char ch = password.charAt(0); // If the password is less than 8 characters, then throw the lengthException. if( password.length() < 8) { throw new LengthException ("The password must be at least 8 characters long."); } // If the first character in the password is not a numeric character, then check to see if the rest of the password contains at least one numeric character. if(!Character.isDigit(ch)) { // Set the initial value of hasDigit to be false boolean hasDigit = false; // Loop through the length of the password, and if there is a character that has a digit, then the variable hasDigit will be true. for (int i = 0; i < password.length(); i++) { ch = password.charAt(i); if(Character.isDigit(ch)) { hasDigit = true; } } // If there is no digit, then throw the NoDigitException if(!hasDigit) { throw new NoDigitException ("The password must contain at least one digit."); } }
  • 11. // If the first character in the password is not upper case, then check to see if the rest of the password contains at least one upper case letter. if(!Character.isUpperCase(ch)) { boolean hasUppercase = !password.equals(password.toLowerCase()); //If the password does not have uppercase, then throw the NoUpperAlphaException. if(!hasUppercase) { throw new NoUpperAlphaException ("The password must contain at least one uppercase alphabetic character."); } } // If the first character in the password is not lower case, then check to see if the rest of the password contains at least one lower case letter. if(!Character.isLowerCase(ch)) { boolean hasLowercase = !password.equals(password.toUpperCase()); if(!hasLowercase) { throw new NoLowerAlphaException ("The password must contain at least one lowercase alphabetic character."); } } // If the first character in the password is either a lower case, upper case, or numeric character, then check to see if the password does not contain more than 2 of the same character in sequence. if(Character.isLowerCase(ch) || Character.isUpperCase(ch) || Character.isDigit(ch) ) { for (int i = 0; i < password.length() - 2; i++) { if( (password.charAt(i) == password.charAt(i + 1)) && (password.charAt(i) == password.charAt(i+2)) )
  • 12. { throw new InvalidSequenceException ("The password cannot contain more than two of the same character in sequence."); } } } return true; } /** * Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid passwords. */ public ArrayList validPasswords(ArrayList passwords) { // an ArrayList to hold all the invalid passwords found illegalPasswords = new ArrayList(); String errorMessage = null; for(int i = 0; i < passwords.size(); i++) { try { isValidPassword(passwords.get(i)); } catch (LengthException e) { errorMessage = passwords.get(i) + " The password must be at least 8 characters long."; illegalPasswords.add(errorMessage); } catch (NoDigitException e) { errorMessage = passwords.get(i) + " The password must contain at least one digit."; illegalPasswords.add(errorMessage); }
  • 13. catch (NoUpperAlphaException e) { errorMessage = passwords.get(i) + " The password must contain at least one uppercase alphabetic character."; illegalPasswords.add(errorMessage); } catch (NoLowerAlphaException e) { errorMessage = passwords.get(i) + " The password must contain at least one lowercase alphabetic character."; illegalPasswords.add(errorMessage); } catch (InvalidSequenceException e) { errorMessage = passwords.get(i) + " The password cannot contain more than two of the same character in sequence."; illegalPasswords.add(errorMessage); } } //Return the ArrayList that contains all the invalid passwords only return illegalPasswords; } } PasswordCheckerInterface.java import java.util.ArrayList; public interface PasswordCheckerInterface { /** * Will check the validity of the password passed in, and returns true if the password is valid, or throws an exception if invalid. */ public boolean isValidPassword (String passwordString) throws LengthException, NoDigitException, NoUpperAlphaException, NoLowerAlphaException, InvalidSequenceException; /** * Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid passwords.
  • 14. */ public ArrayList validPasswords (ArrayList passwords); } NoDigitException.java @SuppressWarnings("serial") public class NoDigitException extends Exception { public NoDigitException() { } /** * Constructor that will take in a message, which will be displayed if NoDigitException is thrown. */ public NoDigitException(String message) { super(message); } } LengthException.java @SuppressWarnings("serial") public class LengthException extends Exception { public LengthException() { } /** * Constructor that will take in a message, which will be displayed if LengthException is thrown. */ public LengthException(String message) { super(message);
  • 15. } } NoUpperAlphaException.java @SuppressWarnings("serial") public class NoUpperAlphaException extends Exception { public NoUpperAlphaException() { } /** * Constructor that will take in a message, which will be displayed if NoUpperAlphaException is thrown. */ public NoUpperAlphaException(String message) { super(message); } } NoLowerAlphaException.java @SuppressWarnings("serial") public class NoLowerAlphaException extends Exception { public NoLowerAlphaException() { } /** * Constructor that will take in a message, which will be displayed if NoLowerAlphaException is thrown. */ public NoLowerAlphaException(String message) { super(message); } }
  • 16. InvalidSequenceException.java @SuppressWarnings("serial") public class InvalidSequenceException extends Exception { public InvalidSequenceException() { } /** * Constructor that will take in a message, which will be displayed if InvalidSequenceException is thrown. */ public InvalidSequenceException(String message) { super(message); } } Solution PasswordCheckerGUI.java import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.layout.HBox; import javafx.stage.Stage; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.geometry.Insets;
  • 17. import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class PasswordCheckerGUI extends Application { Label passwordRulesLabel; // Declares variable to display the rules of setting a valid password Label passwordLabel; // Declares variable to hold the "Password" Label Label retypePasswordLabel; // Declares variable to hold the "Re-type Password" Label TextField passwordTextField; // Declares variable to hold the "Password" entry textfield TextField retypePasswordTextField; // Declares variable to hold the "Re-type Password" entry textfield Button checkPasswordButton; // Declares variable to hold the "Check Password" button Button checkFilePasswordsButton; // Declares variable to hold the "Check Passwords in File" button Button exitButton; // Declares variable to hold the "Exit" button // Creates an instance of the PasswordChecker class to use in order to validate the passwords PasswordChecker check = new PasswordChecker(); @Override public void start(Stage stage) { // Create the label that will display the rules of creating a password passwordRulesLabel = new Label("Use the following rules when creating your passwords " + "1. Length must be greater than 8 " + "2. Must contain at least one upper case alpha character " + "3. Must contain at least on lower case alpha character " + "4. Must contain at least one numeric character "
  • 18. + "5. May not have more than 2 of the same character in sequence "); // Create the password and re-type password labels to let the user know where to enter their desired password passwordLabel = new Label("Password"); retypePasswordLabel = new Label("Re-typePassword"); // Create the textfields to allow the user to enter their desired password passwordTextField = new TextField(); passwordTextField.setPrefWidth(210); retypePasswordTextField = new TextField(); retypePasswordTextField.setPrefWidth(210); // Create the buttons that will be used by the password application to perform its functions. checkPasswordButton = new Button("_Check Password"); // Assign the C key as the mnemonic for the "Check Password" button checkPasswordButton.setMnemonicParsing(true); // Add a tooltip to the "Check Password" button checkPasswordButton.setTooltip(new Tooltip("Click here to check if the desired password is valid.")); checkPasswordButton.setPadding(new Insets(5, 18, 5, 18)); checkFilePasswordsButton = new Button("Check Passwo_rds in File"); // Assign the R key as the mnemonic for the "Check Passwords in File" button checkFilePasswordsButton.setMnemonicParsing(true); // Add a tooltip to the "Check Passwords in File" button checkFilePasswordsButton.setTooltip(new Tooltip("Click here to select the file containing the passwords.")); checkFilePasswordsButton.setPadding(new Insets(5, 18, 5, 18)); exitButton = new Button("_Exit");
  • 19. // Assign the E key as the mnemonic for the "Exit" button exitButton.setMnemonicParsing(true); // Add a tooltip to the "Exit" button exitButton.setTooltip(new Tooltip("Click here to exit.")); exitButton.setPadding(new Insets(5, 18, 5, 18)); // Sets event handlers on each button, which will perform different actions, depending on which button the user clicks. checkPasswordButton.setOnAction(new CheckPasswordButtonEventHandler()); checkFilePasswordsButton.setOnAction(new CheckFilePasswordsButtonEventHandler()); exitButton.setOnAction(new ExitButtonEventHandler()); // Create a horizontal box that will hold the "Password" label and textfield in one row HBox passwordInput = new HBox(10); passwordInput.setAlignment(Pos.CENTER); passwordInput.getChildren().addAll(passwordLabel,passwordTextField); // Create a horizontal box that will hold the "Re-type Password" label and textfield in one row HBox retypePasswordInput = new HBox(10); retypePasswordInput.setAlignment(Pos.CENTER); retypePasswordInput.getChildren().addAll(retypePasswordLabel,retypePasswordTextField); // Create a verticle box, that will nest the passwordInput and retypePasswordInput panes on top of each other. VBox passwordInfoPane = new VBox(10); passwordInfoPane.setPadding(new Insets(20, 0, 40, 0)); passwordInfoPane.setAlignment(Pos.CENTER); // Add the buttons to the children of the buttonPane horizontal box passwordInfoPane.getChildren().addAll(passwordInput,retypePasswordInput); // Create a horizontal box, that will place all the buttons next to each other, that will be used in the GUI.
  • 20. HBox buttonPane = new HBox(25); buttonPane.setAlignment(Pos.CENTER); // Add the buttons to the children of the buttonPane horizontal box buttonPane.getChildren().addAll(checkPasswordButton,checkFilePasswordsButton,exitButton); // Create a vertical box that will nest the passwordRulesLabel on top, followed by the passwordInfoPane, and then the buttonPane at the bottom. VBox contentPane = new VBox(30); contentPane.setAlignment(Pos.CENTER); contentPane.setPadding(new Insets(15, 50, 10, 50)); contentPane.getChildren().addAll( passwordRulesLabel,passwordInfoPane, buttonPane); // Create a BorderPane to place contentPane into the center of the GUI display. // contentPane contains all the nested Hbox's and Vbox's that were created to properly organize and display the contents of the GUI application. BorderPane displayPane = new BorderPane(); // Place the contentPane in the center region of the BorderPane. displayPane.setCenter(contentPane); // Set displayPane as root of scene and set the scene on the stage Scene scene = new Scene(displayPane); stage.setTitle("Password Checker"); stage.setScene(scene); stage.show(); } // Will check to see if the password that is entered by the user is valid, and it will catch the appropriate exception thrown if it's not. class CheckPasswordButtonEventHandler implements EventHandler { @Override public void handle(ActionEvent event) { String password = null;
  • 21. String retypedPassword = null; // Extract the password and retyped password from the input textfields password = passwordTextField.getText().trim(); retypedPassword = retypePasswordTextField.getText().trim(); try { // If the password and re-typed passwords are not the same, then throw an UnmatchedException. if(!password.equals(retypedPassword)) { UnmatchedException exception = new UnmatchedException ("The passwords do not match"); throw exception; } // Use the object created from the instance of the PasswordChecker class to call the isValidPassword method, and determine whether the password entered is valid or not. // If the passwrod is not valid, then it will throw an exception. check.isValidPassword(password); // If no exception is thrown, then display to user that password is valid. JOptionPane.showMessageDialog(null, "Password is valid", "Password Status", JOptionPane.INFORMATION_MESSAGE); } // If the isValidPassword method from the PasswordChecker class throws a UnmatchedException, then catch it and display the appropriate message. catch (UnmatchedException exception) { JOptionPane.showMessageDialog(null, "UnmatchedException: The passwords do not match.", "Password Status", JOptionPane.INFORMATION_MESSAGE); exception.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a
  • 22. LengthException, then catch it and display the appropriate message. catch (LengthException e) { JOptionPane.showMessageDialog(null, "LengthException: The password must be at least 8 characters long.", "Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a NoDigitException, then catch it and display the appropriate message. catch (NoDigitException e) { JOptionPane.showMessageDialog(null, "NoDigitException: The password must contain at least one digit.","Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a NoUpperAlphaException, then catch it and display the appropriate message. catch (NoUpperAlphaException e) { JOptionPane.showMessageDialog(null, "NoUpperAlphaException: The password must contain at least one uppercase alphabetic character.", "Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a NoLowerAlphaException, then catch it and display the appropriate message. catch (NoLowerAlphaException e) { JOptionPane.showMessageDialog(null, "NoLowerAlphaException: The password must contain at least one lowercase alphabetic character.","Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace(); } // If the isValidPassword method from the PasswordChecker class throws a InvalidSequenceException, then catch it and display the appropriate message. catch (InvalidSequenceException e) { JOptionPane.showMessageDialog(null, "InvalidSequenceException: The password cannot contain more than two of the same character in sequence.","Password Error", JOptionPane.INFORMATION_MESSAGE); e.printStackTrace();
  • 23. } } } // It will check to see which passwords are invalid from the file that is read in, and also display its error status. class CheckFilePasswordsButtonEventHandler implements EventHandler { @Override public void handle(ActionEvent event) { File selectedFile = null; Scanner inputFile; ArrayList passwordList = new ArrayList<>(); // Declares a String ArrayList to hold the contents of the file being read. ArrayList illegalList = new ArrayList<>(); // Declares a String ArrayList to hold all the invalid passwords from the file that was read in. // Will display a window box allowing the user to select a file from their computer to open, in order to read its list of passwords. JFileChooser fileChooser = new JFileChooser(); int status = fileChooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } try { inputFile = new Scanner(selectedFile); // Read each password, line by line from the .txt file into a String ArrayList while (inputFile.hasNext()) {
  • 24. passwordList.add(inputFile.nextLine()); } illegalList = check.validPasswords(passwordList); // A string that will display all the invalid passwords and their error status messages one by one in a new row. String illegal = ""; // Loop through the illegalList ArrayList and place each invalid password one by one in a new row in the string. for(int i =0; i < illegalList.size(); i++) { illegal += illegalList.get(i) + " "; } // Display a message to the user showing all the invalid passwords that were read from the file, along with their error status message. JOptionPane.showMessageDialog(null, illegal, "Illegal passwords", JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException e) { e.printStackTrace(); } } } // Will exit the program, if user clicks the "Exit" button. class ExitButtonEventHandler implements EventHandler { @Override public void handle(ActionEvent event) { System.exit(0); } }
  • 25. // Will launch the GUI for the PasswordChecker application. public static void main(String[] args) { launch(args); } } PasswordChecker.java import java.util.ArrayList; public class PasswordChecker implements PasswordCheckerInterface { private String password; // Will hold the string that is passed into the isValidPassword method. private ArrayList illegalPasswords; // Will hold the list of passwords that are found to be invalid from the list that is passed into the validPasswords method. public boolean isValidPassword (String passwordString) throws LengthException, NoDigitException, NoUpperAlphaException, NoLowerAlphaException, InvalidSequenceException { password = passwordString; char ch = password.charAt(0); // If the password is less than 8 characters, then throw the lengthException. if( password.length() < 8) { throw new LengthException ("The password must be at least 8 characters long."); } // If the first character in the password is not a numeric character, then check to see if the rest of the password contains at least one numeric character. if(!Character.isDigit(ch)) { // Set the initial value of hasDigit to be false boolean hasDigit = false;
  • 26. // Loop through the length of the password, and if there is a character that has a digit, then the variable hasDigit will be true. for (int i = 0; i < password.length(); i++) { ch = password.charAt(i); if(Character.isDigit(ch)) { hasDigit = true; } } // If there is no digit, then throw the NoDigitException if(!hasDigit) { throw new NoDigitException ("The password must contain at least one digit."); } } // If the first character in the password is not upper case, then check to see if the rest of the password contains at least one upper case letter. if(!Character.isUpperCase(ch)) { boolean hasUppercase = !password.equals(password.toLowerCase()); //If the password does not have uppercase, then throw the NoUpperAlphaException. if(!hasUppercase) { throw new NoUpperAlphaException ("The password must contain at least one uppercase alphabetic character."); } } // If the first character in the password is not lower case, then check to see if the rest of the password contains at least one lower case letter.
  • 27. if(!Character.isLowerCase(ch)) { boolean hasLowercase = !password.equals(password.toUpperCase()); if(!hasLowercase) { throw new NoLowerAlphaException ("The password must contain at least one lowercase alphabetic character."); } } // If the first character in the password is either a lower case, upper case, or numeric character, then check to see if the password does not contain more than 2 of the same character in sequence. if(Character.isLowerCase(ch) || Character.isUpperCase(ch) || Character.isDigit(ch) ) { for (int i = 0; i < password.length() - 2; i++) { if( (password.charAt(i) == password.charAt(i + 1)) && (password.charAt(i) == password.charAt(i+2)) ) { throw new InvalidSequenceException ("The password cannot contain more than two of the same character in sequence."); } } } return true; } /** * Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid passwords. */ public ArrayList validPasswords(ArrayList passwords) { // an ArrayList to hold all the invalid passwords found illegalPasswords = new ArrayList();
  • 28. String errorMessage = null; for(int i = 0; i < passwords.size(); i++) { try { isValidPassword(passwords.get(i)); } catch (LengthException e) { errorMessage = passwords.get(i) + " The password must be at least 8 characters long."; illegalPasswords.add(errorMessage); } catch (NoDigitException e) { errorMessage = passwords.get(i) + " The password must contain at least one digit."; illegalPasswords.add(errorMessage); } catch (NoUpperAlphaException e) { errorMessage = passwords.get(i) + " The password must contain at least one uppercase alphabetic character."; illegalPasswords.add(errorMessage); } catch (NoLowerAlphaException e) { errorMessage = passwords.get(i) + " The password must contain at least one lowercase alphabetic character."; illegalPasswords.add(errorMessage); } catch (InvalidSequenceException e) { errorMessage = passwords.get(i) + " The password cannot contain more than two of the same character in sequence."; illegalPasswords.add(errorMessage); } }
  • 29. //Return the ArrayList that contains all the invalid passwords only return illegalPasswords; } } PasswordCheckerInterface.java import java.util.ArrayList; public interface PasswordCheckerInterface { /** * Will check the validity of the password passed in, and returns true if the password is valid, or throws an exception if invalid. */ public boolean isValidPassword (String passwordString) throws LengthException, NoDigitException, NoUpperAlphaException, NoLowerAlphaException, InvalidSequenceException; /** * Will check an ArrayList of passwords and returns an ArrayList with the status of any invalid passwords. */ public ArrayList validPasswords (ArrayList passwords); } NoDigitException.java @SuppressWarnings("serial") public class NoDigitException extends Exception { public NoDigitException() { } /** * Constructor that will take in a message, which will be displayed if NoDigitException is thrown. */ public NoDigitException(String message) {
  • 30. super(message); } } LengthException.java @SuppressWarnings("serial") public class LengthException extends Exception { public LengthException() { } /** * Constructor that will take in a message, which will be displayed if LengthException is thrown. */ public LengthException(String message) { super(message); } } NoUpperAlphaException.java @SuppressWarnings("serial") public class NoUpperAlphaException extends Exception { public NoUpperAlphaException() { } /** * Constructor that will take in a message, which will be displayed if NoUpperAlphaException is thrown. */ public NoUpperAlphaException(String message) {
  • 31. super(message); } } NoLowerAlphaException.java @SuppressWarnings("serial") public class NoLowerAlphaException extends Exception { public NoLowerAlphaException() { } /** * Constructor that will take in a message, which will be displayed if NoLowerAlphaException is thrown. */ public NoLowerAlphaException(String message) { super(message); } } InvalidSequenceException.java @SuppressWarnings("serial") public class InvalidSequenceException extends Exception { public InvalidSequenceException() { } /** * Constructor that will take in a message, which will be displayed if InvalidSequenceException is thrown. */ public InvalidSequenceException(String message) { super(message);
  • 32. } }