SlideShare a Scribd company logo
1 of 32
Download to read offline
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

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

correct the error and add code same in the pic import jav.pdf
correct the error and add code same in the pic   import jav.pdfcorrect the error and add code same in the pic   import jav.pdf
correct the error and add code same in the pic import jav.pdfdevangmittal4
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfsudhirchourasia86
 
i need a output screen shot for this code import java-awt-BorderLayou.docx
i need a output  screen shot for this code import java-awt-BorderLayou.docxi need a output  screen shot for this code import java-awt-BorderLayou.docx
i need a output screen shot for this code import java-awt-BorderLayou.docxPaulntmMilleri
 
Mozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJSMozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJSRobert Nyman
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveepamspb
 
Creating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdfCreating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdfShaiAlmog1
 
Change password for weblogic users in obiee 11g
Change password for weblogic users in obiee 11gChange password for weblogic users in obiee 11g
Change password for weblogic users in obiee 11gRavi Kumar Lanke
 
Object Oriented Programming Session 4 part 2 Slides .pptx
Object Oriented Programming Session 4 part 2 Slides .pptxObject Oriented Programming Session 4 part 2 Slides .pptx
Object Oriented Programming Session 4 part 2 Slides .pptxr209777z
 
Christopher Latham Portfolio
Christopher Latham PortfolioChristopher Latham Portfolio
Christopher Latham Portfoliolathamcl
 
You can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenYou can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenanitramcroberts
 
100% Code Coverage - TDD mit Java EE
100% Code Coverage - TDD mit Java EE100% Code Coverage - TDD mit Java EE
100% Code Coverage - TDD mit Java EEStefan Macke
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfSakkaravarthiS1
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfmohammedfootwear
 
import java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdf
import java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdfimport java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdf
import java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdfanupambedcovers
 
React native app with type script tutorial
React native app with type script tutorialReact native app with type script tutorial
React native app with type script tutorialKaty Slemon
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 

Similar to PasswordCheckerGUI.javaimport javafx.application.Application; im.pdf (20)

correct the error and add code same in the pic import jav.pdf
correct the error and add code same in the pic   import jav.pdfcorrect the error and add code same in the pic   import jav.pdf
correct the error and add code same in the pic import jav.pdf
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
 
i need a output screen shot for this code import java-awt-BorderLayou.docx
i need a output  screen shot for this code import java-awt-BorderLayou.docxi need a output  screen shot for this code import java-awt-BorderLayou.docx
i need a output screen shot for this code import java-awt-BorderLayou.docx
 
Mozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJSMozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJS
 
Test automation
Test  automationTest  automation
Test automation
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
 
Creating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdfCreating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdf
 
Change password for weblogic users in obiee 11g
Change password for weblogic users in obiee 11gChange password for weblogic users in obiee 11g
Change password for weblogic users in obiee 11g
 
Test
TestTest
Test
 
Object Oriented Programming Session 4 part 2 Slides .pptx
Object Oriented Programming Session 4 part 2 Slides .pptxObject Oriented Programming Session 4 part 2 Slides .pptx
Object Oriented Programming Session 4 part 2 Slides .pptx
 
Christopher Latham Portfolio
Christopher Latham PortfolioChristopher Latham Portfolio
Christopher Latham Portfolio
 
You can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenYou can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commen
 
100% Code Coverage - TDD mit Java EE
100% Code Coverage - TDD mit Java EE100% Code Coverage - TDD mit Java EE
100% Code Coverage - TDD mit Java EE
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
 
From Swing to JavaFX
From Swing to JavaFXFrom Swing to JavaFX
From Swing to JavaFX
 
import java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdf
import java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdfimport java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdf
import java.awt.event.ActionEvent; import java.awt.event.ActionLis.pdf
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
 
React native app with type script tutorial
React native app with type script tutorialReact native app with type script tutorial
React native app with type script tutorial
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 

More from anjaniar7gallery

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

More from anjaniar7gallery (20)

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

Recently uploaded

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

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. } }