Password popup not closing program if cancel is pressed - java

I am trying to make a password protected program. I can't seem to get my program to close if the person hits cancel. I also have another question. If my program is a jar file would System.exit(0); close it?
String password = JOptionPane.showInputDialog(gameWindow,"Please enter the password.","Security Alert",JOptionPane.WARNING_MESSAGE);
if (password.equalsIgnoreCase("password")) {
} else {
System.exit(0);
}

You are getting Null Pointer Exception.
Do the following for your if statement.
if (password != null && password.equalsIgnoreCase("password")) {
} else {
System.exit(0);
}
When you do cancel password is set to null (same if you just exit), so you need to check for that, because otherwise your program crashes.

Related

Two if statement is executed in java code

Im currently trying to do a validation for staff login form. but i realized in my validation output that whenever i enter a value to the username text field, it still pops up the message "please enter your username" then the "invalid credentials"message box. Here is my code down below :
String username = usernameTxt.getText();
String password = passwordTxt.getText();
if (username.contains(""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Username Credentials.");
}
else if (password.contains (""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Password Credentials.");
}
else if (password.contains ("") && (username.contains("")))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Login Credentials.");
}
if ((username.contains("staff") && password.contains ("pass")))
{
JOptionPane.showMessageDialog(null,"Login Successfull","Success",JOptionPane.INFORMATION_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
staffdashboard sd = new staffdashboard();
sd.setVisible(true);
this.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Login Details","Login Error",JOptionPane.ERROR_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
}
enter user message box
invalid login details message box
What am i missing out and how do stop the form to output 2 message box at once?
The problem is in the first if statement: username.contains("")
Each String contains empty String.
You should replace it with if("".equals(username))
Or use StringUtils.isBlank(username);
And the same for all the contains("")
#Naya's answer is correct, however you may want to remove any empty spaces assuming they are not allowed as valid input, so :
if (username.trim().equals("")) ...
else if (password.trim.equals("")) ...
...

else statement still runs even when else if condtions pass

I'm having issues getting my if else statement to work correctly, here I have a login in form that uses values from a database. The statement for the Employee role works fine but even if the else if statement passes the else statement still runs.
If it helps the dialog box appears twice if the Customer statement passes and three time if the else runs by itself. I apologize if my code format is off I'm new at posting code here.
private void jBtnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// action performed when the login button is pressed
// variables that will contain the row entries to the login data base (user name)
String userNameDb = "";
roleDb = rs.getString("role");
//database connection code
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("//database directory");
st=con.createStatement();
//selects entries from the userName password and role row from the user table
rs=st.executeQuery("Select userName, role From tblUser ;");
//loops through the table entires
while(rs.next())
{
//assigns database entry to variables
userNameDb = rs.getString("userName");
roleDb = rs.getString("role");
if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
//if the users input and role match the data base for an customer send them to the selection form
else if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
else
{
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
catch(Exception ex)
{
System.out.println("" + ex);
}
}
}
The problem is that your while loop is coded wrong as your "Login failed" JOptionPane else block shouldn't be within the while loop. Instead declare a boolean value before the loop, set it to false, check if the username/password are found within the that loop, and if so, set the boolean to true. Then after the loop check the boolean value, and if false, show the error message.
To see why, use a debugger to run through the code to see why it's behaving the way it's behaving. More importantly, learn the "rubber duck" debugging technique where you walk through your code mentally or on paper, telling the duck what each line of code should be doing.
To illustrate, your code is behaving something like the code below where a boolean array is mimicking your password username check. Of course, you'd be using a while loop, not a for loop, but this was used here to make the example simpler:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
for (boolean loopItem : loopItems) {
if (loopItem) {
break;
} else {
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
Assume that the password/username only matches on the 4th try (forth item is true), then for each failed check, the JOptionPane will show a failed login. What you want instead is something like:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
boolean userFound = false;
// you'll of course be using a while loop here
for (boolean loopItem : loopItems) {
if (loopItem) {
userFound = true;
// do something with user data
break;
}
}
if (!userFound) {
JOptionPane.showMessageDialog(null, "Login failed");
}
}

Java Swing Dialog issue

When pressed the "Inregistrare" button a dialog pops, requesting the user to enter a password (set to "qwerty"). I want it keep displaying dialogs until the password is correct. The method is the following:
private void ItemInregistrareActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane dialog = new JOptionPane();
dialog.setWantsInput(true);
dialog.showInputDialog("Password please:");
while(dialog.getInputValue()!="qwerty")
dialog.showInputDialog("Mai baga o fisa.");
ItemInregistrare.setEnabled(false);
ItemOpen.setEnabled(true);
ItemSave.setEnabled(true);
}
The problem is it never gets out of the while, even if the password is correct. Any tips?
JOptionPane.showInputDialog is a static method and does not need any instance of JOptionPane. Moreover, it already returns the entered value or null if user pressed Cancel. So you don't need to call dialog.getInputValue().
You could try something like this:
String pwd;
do {
pwd = JOptionPane.showInputDialog("Password please:");
} while (pwd != null && !pwd.equals("qwerty"));
if (pwd == null) {
JOptionPane.showMessageDialog(null, "You pressed cancel");
} else {
JOptionPane.showMessageDialog(null, "Password is correct");
}
Try using
!dialog.getInputValue().equals("qwerty")
to compare strings

AssertTrue in try/catch

Please what exactly am i doing wrong.
I have checked and checked but all to no avail.
I have also checked previous code but I am not getting an error so my code works fine but just slight error somewhere.
The code is running fine and assertTrue is behaving as expected but when I put it in the try/catch, I only get the log in the catch block, even when text was found.
I believe that if the assertTrue found the text, it should go to the next line of code in the try block and pass the test rather than the catch block. Don't get me wrong, I am not getting any error just that it's printing out the wrong message.
Code below including print out message in console.
public boolean verifyTextPresent(String value) throws Exception {
Thread.sleep(5000);
try{
boolean txtFound = driver.getPageSource().contains(value);
log.log(value + " : text Found, .......continue");
return txtFound;
}catch(Exception e)
{
log.log(value + " :NOT Found, check element again ot Contact developer.");
return false;
}
}
public static void verifySignOutBtn() throws Exception
{
log.header("VERIFY IF SIGN_OUT EXIST AND CLICKABLE.........");
callMethod.myAccountPageNative(CONSTANTElements.SIGN_IN_LINK);
Thread.sleep(2000);
log.header("LOCATE SIGN_OUT BTN, AND CLICK ......");
callMethod.elementPresent_Click(By.cssSelector(CONSTANTElements.SIGN_OUT_BTN));
Thread.sleep(4000);
log.header("VERIFY SIGN_OUT NAVIGATES TO HOME PAGE WHEN CLICKED......");
try{
Assert.assertTrue(callMethod.verifyTextPresent("SIGN IN"), "SIGN IN");
log.log("User Successfully Signed Out.......");
log.log("Test Passed!...");
//callMethod.close();
}
catch(Throwable e)
{
log.log("User NOT Successfully Signed Out.... Contact developer.");
log.log("Test Failed!...");
//callMethod.close();
}
callMethod.close();
}
}
Msg in console:
SIGN IN : text Found, .......continue
User NOT Successfully Signed Out.... Contact developer.
Test Failed!...
The confusing part is that why is it printing out the catch block instead of the next line in the try block?
Shouldn't it be the other way around?
Assert.assertTrue("Message if it is false", callMethod.verifyTextPresent("SIGN IN"));
The only possible explanation is that verifyTextPresent(String value) returns false (you never actually check the value of boolean txtFound) and assertTrue fails (throwing an AssertionError which is not handled well in your catch block). To find out, replace this
log.log(value + " : text Found, .......continue");
for example with this line
log.log(value + " : text Found, ......." + txtFound);
or just print the stacktrace in catch block.

Displaying LDAP errors in UI

Currently I have code that is used to change a password that is stored on an LDAP server. I am using a boolean variable to store the result if the update was successful or not, thereafter I check if the update failed via an if statement and I display an error message.
The issue I'm facing is how can I display more specific errors in the UI if the password change fails?
For example:
The existing password is invalid
The username is incorrect
The account has been locked
If someone could please advise on what could be a nice and tidy solution to my problem. Below is a snippet of the reset password method:
boolean passwordReset = this.userManagement.update(this.username, this.resetPassword, this.resetOldPassword);
if(!passwordReset){
super.addMessage(FacesMessage.SEVERITY_ERROR,super.getResource("password.error"), super.getResource("user.password.change.error"));
} else {
super.addMessage(FacesMessage.SEVERITY_INFO,super.getResource("change.password.head"), super.getResource("password.changed.success"));
}
I think you should modify the userManagement.update method to raise an exception in case of error. So depending on the error it could throw InvalidPasswordException, UsernameException, BlockedAccoutException, etc. or just throw an only exception with a custom message.
In any case, first you need to collect this information from the ldap operation.
Example code:
try {
this.userManagement.update(this.username, this.resetPassword, this.resetOldPassword);
} catch(InvalidPasswordException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource("password.error"), super.getResource("user.password.change.error"));
} catch(UsernameException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource("username.error"), super.getResource("user.name.error"));
} catch(BlockedAccoutException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource("blockaccount.error"), super.getResource(blockaccount.error"));
}
Or:
try {
this.userManagement.update(this.username, this.resetPassword, this.resetOldPassword);
} catch(UpdateUserException e) {
super.addMessage(FacesMessage.SEVERITY_ERROR, super.getResource(e.getErrorCode()));
}
The problem with the first approach is that you have to create several (or a lot) of classes.
This doesn't happen with the second option, but you need a way to get the proper error message. You may add an error type/code to the exception.

Categories