ChangePassword method in Java - java

I'm working on a Java project, building a simple system, and it has some methods, one of them is "Change PassWord", I put the user's information (username & password) in a text file called ("Users.txt").
Now this is the description of the method:
boolean ChangePassWord(): Asks the user to enter old password for
verification, the user has at maximum three tries to enter correct old
password; if not the password will not be changed and a message Box
will be shown for the user. If user entered correct old password then
he is authenticated to changer his password and asked to enter new
password and confirming the new. Once if confirmed correctly the old
password will be changed to the new one and a message box will be
shown if wrong confirmation the old password will not be changed and a
message box will be shown.
I wrote this code:
boolean changePassword(){
String pass=JOptionPane.showInputDialog(null, "Enter old password: ", "Input", JOptionPane.QUESTION_MESSAGE);
if(pass.equals(Password)) {
String newpass=JOptionPane.showInputDialog(null,
"Enter new password: ", "Input", JOptionPane.QUESTION_MESSAGE);
String connewpass=JOptionPane.showInputDialog(null,
"Enter confirming new password: ", "Input",
JOptionPane.QUESTION_MESSAGE);
if(newpass.equals(connewpass)){
Password= newpass;
JOptionPane.showMessageDialog(null, "password changed ", "message",
JOptionPane.INFORMATION_MESSAGE);
return true;
}
else
JOptionPane.showMessageDialog(null, "Wrong Conferm ", "message",
JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "Wrong password ", "message",
JOptionPane.INFORMATION_MESSAGE);
return false;
}
but I think that it's wrong, and I need to use a loop I think.
I hope you help me!

A while loop is appropriate for your case. I will briefly explain how this while loop runs 3 times.
So, first n=3. The condition n-- > 0 means 2 things. Check if n is greater than zero and subtract the value of n by 1. These 2 things happen in that exact order.
So the condition checks that n is indeed greater than zero and enters the loop. At the same time n is also decreased by 1 and becomes 3-1=2.
This goes on 3 times. After the 3rd time, n becomes 0. And the condition 0 > 0 is false and therefore the while loop breaks.
boolean changePassword(){
String pass = ""; //get old password from user
int n = 3;
while (n-- > 0) {
if(pass.equals(Password)) {
String newPass = ""; // get new password from user
String conNewPass = ""; // confirm new password from user
if (newPass.equals(conNewPass)) {
Password = newPass;
// password changed
return true;
} else {
// wrong confirmation.. password not changed
return false;
}
}
else {
// tell user to enter the correct old password
pass = ""; // ask user for old password again
}
}
// show error message that user entered the old password 3 times incorrectly
// and return false
return false;
}

Related

In the code below the loop doesn't end even if I put the correct username

I was trying to build a simple UI where a user enters a username and if the username is xyz then the user will be shown "enter your password". If the password is xyz1234 then the user will be shown "please wait loading..." and the scanner exits. If the username was incorrect, I tried to code it in a way so that it keeps asking for the username until the correct username is entered.
Apparently, the first part of the code works, if the username is xyz, then the code works correctly and displays what i want it to. However if the username is wrong in the first attempt and right in the second attempt, it still continues to show "incorrect username" instead of showing "enter the password".
The code is shown below:
import java.util.Scanner;
class User_Authentication
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter your Username");
String username=in.nextLine();
if(username.equals("xyz"))
{
System.out.println("Enter the Password");
String password=in.nextLine();
if(password.equals("xyz1234"))
{
System.exit(0);
System.out.println("Welcome");
System.out.println("Please wait while the system is loading....");
}
else
{
System.out.println("Your system has been locked for security reasons.");
System.out.println("Please contact an administrator to reset the password");
System.out.println("Any attempt to break in the computer will result in self destruction.");
System.exit(0);
}
}
else
{
do
{
if(username.equals("xyz"))
{
break;
}
System.out.println("Incorrect username");
System.out.println("Please try again");
in.nextLine();
}
while((username.equals("xyz"))==false);
}
}
} ```
Your saying in.nextLine() in your do-while loop, rather than username = in.nextLine()
Replace that and it should work, but overall you're do-while loop needs some work, it's relatively messy. Here's how I would approach it.
do {
System.out.println("Incorrect username");
System.out.println("Please try again");
username = in.nextLine();
} while(username.equals("xyz") == false);

How to verify OTP in Java using simple loop?

I'm a Java beginner and my project consists of creating a simple program to register users for an alumni center. The process creates an ID and then provides the new user with an OTP. Next is the login (Enter ID:, Enter OTP: ).
My OTP verification method is not working. It seems to be a problem with the IF.equals declaration, the process jumps straight to the ELSE condition.
Any suggestions why?
Here is my code:
class Main {
static NewRegandLogin newRegAndLogin = new NewRegandLogin(null, null, null, null, null, null);
static ArrayList<NewRegandLogin> loginInformation = new ArrayList<>();
public static void main(String[] args) {
System.out.println(" WELCOME TO THE ALUMNI SHE-CODES SYSTEM ");
System.out.println("_________________________________\n - New Alumni registration - \n");
System.out.println("");
newRegAndLogin.registerNewGrad();
System.out.println();
System.out.println("_________________________________");
System.out.println();
System.out.println("Your new Alumni ID is: " + newRegAndLogin.getAlumniId());
System.out.println();
System.out.println("Your temporary password is:");
System.out.println(newRegAndLogin.oTp(8));
loginInformation.add(newRegAndLogin);
System.out.println("_________________________________");
System.out.println("_________________________________\n - Alumni Login - \n");
System.out.println("");
newRegAndLogin.login();
System.out.println("");
System.out.println("Please make a list of completed Courses: -->Enter 'S' to stop adding courses<--");
newRegAndLogin.setAlumniCourses();
System.out.println("_________________________________");
newRegAndLogin.setLinkedInPage();
loginInformation.add(newRegAndLogin);
//printAlumniProfile();
System.out.println("_________________________________");
newRegAndLogin.jobOffer();
}
void login() {
System.out.print("ID: ");
alumniIdImput = scanner.nextLine();
idVerification();
do {
System.out.println("Password (OTP if logging in for the first time): ");
passwordImput = scanner.nextLine();
oTpFromImput = passwordImput.toCharArray();
oTpVerification();
} while (isPasswordCorrect=false);
void oTpVerification() {
isPasswordCorrect = false;
if (oTpFromImput.equals(oTp(8))) {
isPasswordCorrect = true;
System.out.println("Logging In.....");
}else {
isPasswordCorrect = false;
System.out.println("Incorrect password.\nPlease enter valid password: 8 alpha numeric
characters(Aa,123,#,#,$,%)");
}
}
This is the oTp method
char[] oTp (int length) {
String capitalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String smallChars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!##$%^&*_-=+/.?<>";
String values = capitalChars + smallChars + numbers + symbols;
Random oneTimePassword = new Random();
char[] password = new char[length];
for(int i = 0; i<length;i++) {
password[i] = values.charAt(oneTimePassword.nextInt(values.length()));
}
return password;
}
It seems you built a guessing game, not an OTP verification code.
You first read the OTP from user, and only then randomly generate one to copare to it.
Basically, you code expects the user to guess a random 8 character password that has not been created you, which is basically impossible...
You need to generate to OTP first, show it to the user, then ask them to input it.
I see your logic code is generate OTP code after User input. It seem so wierd bro.
Whenever you call oTp(8) function will generate new OTP.
Use should generate OTP first then store somewhere, then User input and compare it.
You need to store the generated otp somewhere. Then compare it with the input otp. Right now you are comparing it with the otp(8). And otp(8) always returns a new otp.

Why will my continue statement not restart my while loop?

I am trying to complete an authentication program for my final project. I am checking for user authentication, if the user info doesn't match the credentials file, the output tells them this and then prompts for username and password while increment an attemptCounter. The only portion I am experiencing an issue with is when I test and incorrect attempt followed by a correct attempt, the while loop will not restart my authentication procedure, instead it simple says incorrect login again. Why isn't my continue statement restarting my while loop iteration?
I tired looking around for this answer on the forum and food nothing specific to my issue. I tried moving my conditional statement as well to see if it was in the wrong spot for my continue to work but it fixed nothing. Compiler says both of my continue statements are unnecessary.
//prompting user for username
System.out.println("Please enter your username (\"L\" to logout \"Q\" to quit): ");
username = scnr.nextLine();
//evaluating if user wants to quit immediately
if(username.equals("Q")) {
System.exit(0);
}
//prompting user for password and storing to password field
System.out.println("Please enter your password: ");
password = scnr.nextLine();
System.out.print("\n");
//while loop that contains the authentication and authorization logic
while (!username.equals("Q") && attemptCounter < 2){
//calling of hashInput method of MD5Hash class to return the hashed user password
userHashedPassword = userHash.hashInput(password);
//while loop to open the credentials for authentication comparison
while (cfScnr.hasNextLine()) {
//assigning the files scanned next line to a field for comparison
line = cfScnr.nextLine();
//conditional statement to determine if username and password are contained on the line
//will break file loop as soon as line contains the user's username and password
//statement logic used to return the role string and remove extra characters and white space
if (line.contains(username) && line.contains(userHashedPassword)) {
dqLocation = line.lastIndexOf('"');
role = line.substring(dqLocation);
role = role.replaceAll("\\s+", "");
role = role.replace("\"", "");
break;
}
}
//conditional statement used to determine if previous loops condtional statement was meant
//if it wasn't this condition will inform the user of incorrect username and/or password
//inform them of attempts remaining and prompt them for a new username and password while
//tracking the attempts and it they want to quit. If Q isn't entered main while loop will restart authentication
if (role == null){
attemptCounter++;
System.out.println("Username or password incorrect. " + (3 - attemptCounter) + " attempts remaining.");
System.out.println("Please enter your username (\"L\" to logout \"Q\" to quit): ");
username = scnr.nextLine();
if(username.equals("Q")) {
System.exit(0);
}
System.out.println("Please enter your password: ");
password = scnr.nextLine();
continue;
}
//this conditional statement runs only when the user is authenticated
else {
//creating new file object and scanner object to scan the role file
File rFile = new File("src\\zooauthenticationsystem\\" + role + ".txt");
Scanner rfScnr = new Scanner(rFile);
//while loop to parse through the role file and output the lines of the file to the console
while (rfScnr.hasNextLine()){
rolePrint = rfScnr.nextLine();
System.out.println(rolePrint);
}
//prompting user if they would like to logout or simply quit the program
System.out.println("\nPress \"L\" to logout and \"Q\" to quit.");
userDecision = scnr.nextLine();
//conditional statement to determine their input, and resetting role to null to reset authentication loop conditional statements, restarts main while loop
if (userDecision.equals("L")){
System.out.println("Please enter your username: ");
username = scnr.nextLine();
if(username.equals("Q")) {
System.exit(0);
}
System.out.println("Please enter your password: ");
password = scnr.nextLine();
System.out.print("\n");
role = null;
continue;
}
Let's get rid of most of your code, let's format the code better, and let's leave only the control structures to see what the continue statements are doing:
while (!username.equals("Q") && attemptCounter < 2) {
userHashedPassword = userHash.hashInput(password);
while (cfScnr.hasNextLine()) {
line = cfScnr.nextLine();
if (line.contains(username) && line.contains(userHashedPassword)) {
// ... do some stuff
break;
}
}
if (role == null) {
// ... do some stuff
continue; // **** (A) ****
} else {
// ... do some stuff
if (userDecision.equals("L")){
// ... do some stuff
continue; // **** (B) ****
}
}
}
If line (A) is reached, you're in the if (roll == null) block, the else will never be entered, and the while loop will repeat regardless of the continue statement making continue unnecessary and distracting.
Likewise if line (B) is reached, you're in the last control block of the while loop, and so the loop will continue regardless of the continue statement making continue unnecessary and distracting.

Problem with record existence + text field criteria

Basically, a have a sign-up interface THAT should empty fileds and certain conditions and if record exist in data basewhere first it checks if text fields are empty as written below :
private void confirmActionPerformed(java.awt.event.ActionEvent evt) {
// String f= "jdbc:derby://localhost:1527/BStest";
String name=username.getText();
String gender=null;
String passw=String.valueOf(pass.getPassword());
String repassw=String.valueOf(repass.getPassword());
String phone2=phone.getText();
String emaill=email.getText();
boolean checkage=false,checknum=false,checkcap=false,checklaw=false,checkemail=false,checkdomain=false;
boolean checklen=false,checkbfat=false,checkpass=false,checkchar=false,checkgender=false;
boolean checkempty=true;
if(name.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add a username!");}
if(passw.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add a Password!");}
if(!repassw.equals(passw)){//confirmed password is the same for password
checkempty=false;
JOptionPane.showMessageDialog(null,"Type password Again!");
}
if(phone2.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add Phone number !");
}
if(emaill.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add email please !");
}
if (!m.isSelected()&& !female.isSelected()){//no gender selected
checkempty=false;
JOptionPane.showMessageDialog(null,"Choose a gender !!");}
else if (m.isSelected()&& female.isSelected()){//both selected it shoud be only one
checkempty=false;
JOptionPane.showMessageDialog(null,"Select only One !!");}
if(age.getText().isEmpty()){//is age text field has no input
checkempty=false;
JOptionPane.showMessageDialog(null,"Enter your age !!");}
Secondly checks the criteria for each text field as indicated in the comments below
if (m.isSelected()){// is female or male selected
checkgender=true;
gender="Male";
}
else if (female.isSelected()){
checkgender=true;
gender="Female";
}
int agee =Integer.parseInt(age.getText());
char c,c2=emaill.charAt(0);
String zereofive=phone2.substring(0, 2);//start with 05
String bfat = emaill.substring(0,emaill .indexOf("#"));//digits berfore #
String domain = emaill.substring(emaill .indexOf("#") + 1);//check domain
if(Character.isLetter(c2))//is first char off email iis letter
checkchar=true;
else
JOptionPane.showMessageDialog(null,"Emails only start with letters");
if (phone2.length()==10 && zereofive.equals("05"))//check length of phone number
checklen=true;
else
JOptionPane.showMessageDialog(null,"enter 10 digits for the phone number and starts with 05");
if(bfat.length()>=6 || bfat.length()<=15){//check digits before #
checkemail=true;
}
if(domain.equals("gmail.com") || domain.equals("hotmail.com")){//check domain of email
checkdomain=true;
}
else
JOptionPane.showMessageDialog(null,"Email domain is wrong");
if(agee>=18)//only can register in 18 or above
checkage=true;
else
JOptionPane.showMessageDialog(null,"You can't register because you are under 18. ");
if(passw.length()>7){// password at least 8 digit at least one captial and one small letter
checklen=true;
for (int i=0;i<passw.length();i++){
c=passw.charAt(i);
if(Character.isDigit(c))
checknum=true;
else if (Character.isUpperCase(c))
checkcap=true;
else if (Character.isLowerCase(c))
checklaw=true;
if(checknum && checkcap && checklaw )
checkpass=true;
}}
if(checkpass)//check of all 3 crietria of pass word is coorrect
checkpass=true;
else
JOptionPane.showMessageDialog(null,"password must be at least 8 digits \n at least 1 Upper Case letter \n at least 1 Lower Case letter \n at least 1 number \n");
and lastly stores in the database if criteria is meet and record is not exists
PreparedStatement reg,exist;
String query="INSERT INTO customer (Cu_name, Cu_password, Cu_age, Cu_gender, Cu_email, Cu_phone) VALUES (?, ?, ?, ?, ?, ?)";//enter user info in database
String record_exists="SELECT * FROM customer where Cu_name=? and Cu_password= ? and Cu_age=? and Cu_gender=? and Cu_email=? and Cu_phone=?";
try{
String f= "jdbc:derby://localhost:1527/BStest";
Connection connection = DriverManager.getConnection(
f, "meme", "Moudhi102");
reg=connection.prepareStatement(query);
exist=connection.prepareStatement(record_exists);
reg.setString(1, name);
reg.setString(2, passw);
reg.setInt(3, agee);
reg.setString(4, gender);
reg.setString(5, emaill);
reg.setString(6, phone2);
exist.setString(1, name);
exist.setString(2, passw);
exist.setInt(3, agee);
exist.setString(4, gender);
exist.setString(5, emaill);
exist.setString(6, phone2);
rs=exist.executeQuery();
if(rs==null){
if(checkpass &&checkage && !checkdomain && !checkemail && !checklen && checkchar && !checkgender && checkempty ){//if all criteria justified then add it to database
reg.executeUpdate();
JOptionPane.showMessageDialog(null,"Complete! new user added !! ");
}
}else//else it can't be added
{
JOptionPane.showMessageDialog(null, "Record already exists");
}
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex);
}
the problem is it doesn't show a message if record already exists in database and if I entered empty text in age + phone + email it shows the message that it is empty but in the NetBeans itself shows an error message in the output area like below
at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at event_system.Sign_up.confirmActionPerformed(Sign_up.java:275)
at event_system.Sign_up.access$000(Sign_up.java:20)
at event_system.Sign_up$1.actionPerformed(Sign_up.java:70)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
and doesn't do the coding part of these three fields and show their messages even for password if criteria is not meet and other field inputs are ok is shows a continuous message of record exists and Can't register check/fill you information.Please help me i'm stuck and can't figure it out
Deal with your exception first before even considereing to deal with your other problems since it will prevent the other portions of your code to be run from the point of exception and therefore be the root cause to all your problems at this time.
You can not pass a Null String ("") to the Integer#parseInt() method:
int agee = Integer.parseInt(age.getText());
If the Text Field that is to contain an age is empty then the JTextField#getText() method will return a Null String (""). If you supply this to the Integer#parseInt() method (as you've done in the above code) or anything other than an integer value then a NumberFormatException is generated. You need to take care of this possible condition and the use of a Ternary Operator (aka Conditional Operator) may be all you need:
int agee = age.getText().trim().equals("") ? 0 : Integer.parseInt(age.getText().trim());
This however doesn't cover the fact that a alpha character might accidently be supplied within the Age text field. To cover that problem it may be just better to do:
String theAge = age.trim().getText();
int agee = 0;
// Regular Expression used to ensure a Integer
// Numerical String value was supplied.
if (theAge.matches("\\d+")) {
agee = Integer.parseInt(theAge);
}
In the above line of code, IF the Age text-field contains nothing or blank spaces then the agee variable is supplied a integer 0 value ELSE the Integer.parseInt() method is used with the contents of the Text Field to fill the agee variable.
On a side note:
You utilize a lot of boolean flags for each of your text fields so as to ensure validity and other things. From what I can see you actually don't need any of them since you are checking all fields and your requirements are that all those fields actually be filled:
boolean checkage=false, checknum=false, checkcap=false, checklaw=false,
checkemail=false,checkdomain=false;
boolean checklen=false, checkbfat=false, checkpass=false, checkchar=false,
checkgender=false;
boolean checkempty=true;
I would get rid of all of them and and not use a flag at all. If at any time within your code any one of your Text Fields does not meet validity within the confirmActionPerformed() event then nothing should be read from or written to the database. As the fields are checked for validity and any of those fields fail you simply need to display the fact via Message Box then when the User selects the OK button we set focus on the Text Field currently being checked (age.requestFocus();) then exit the event with a return; statement. Database code can never be reached unless all your text fields passes validity. Your event code might look like this:
private void confirmActionPerformed(java.awt.event.ActionEvent evt) {
// String f= "jdbc:derby://localhost:1527/BStest";
String name = username.getText().trim();
String gender = null;
String passw = String.valueOf(pass.getPassword());
String repassw = String.valueOf(repass.getPassword());
String phone2 = phone.getText().trim();
String emaill = email.getText().trim();
// NAME
//is Name text field empty
if (name.isEmpty()) {
JOptionPane.showMessageDialog(null, "Add a username!");
username.requestFocus();
return;
}
// PASSWORD
//is Password field empty
if (passw.isEmpty()) {
JOptionPane.showMessageDialog(null, "Add a Password!");
pass.requestFocus();
return;
}
/* A Regular Expression is used here to ensure your desired
password rules apply - Minimum of 8 characters in length,
at least 1 Uppercase Letter, at least 1 Lowercase letter,
at least 1 digit. */
if (!passw.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$")) {
JOptionPane.showMessageDialog(null, "Password must be:\n\n"
+ "- At least 8 characters in length,\n"
+ "- Contain at least 1 Uppercase letter,\n"
+ "- Contain at least 1 Lowercase letter,\n"
+ "- Contain at least 1 number.");
pass.requestFocus();
return;
}
// confirmed password is the same for password
if (!repassw.equals(passw)) {
JOptionPane.showMessageDialog(null, "Type password Again!");
repass.requestFocus();
return;
}
// PHONE
//is phone text field empty
if (phone2.isEmpty()) {//is text field empty
JOptionPane.showMessageDialog(null, "Add Phone number !");
phone.requestFocus();
return;
}
// starts with 05
String zereofive = phone2.substring(0, 2);
// check length of phone number
if (phone2.length() != 10 && !zereofive.equals("05")) {
JOptionPane.showMessageDialog(null, "enter 10 digits for the phone number and starts with 05");
phone.requestFocus();
return;
}
// E-MAIL
//is E-Mail text field empty
if (emaill.isEmpty()) {
JOptionPane.showMessageDialog(null, "Add email please !");
email.requestFocus();
return;
}
// E-Mail
char c, c2 = emaill.charAt(0);
String bfat = emaill.substring(0, emaill.indexOf("#"));//digits berfore #
String domain = emaill.substring(emaill.indexOf("#") + 1);//check domain
// is first char off email a letter
if (!Character.isLetter(c2)) {
JOptionPane.showMessageDialog(null, "Emails can only start with letters!");
email.requestFocus();
return;
}
//check digits before #
if (bfat.length() < 6 || bfat.length() > 15) {
JOptionPane.showMessageDialog(null, "Invalid digits in Email address!");
email.requestFocus();
return;
}
//check domain of email
if (!domain.equals("gmail.com") && !domain.equals("hotmail.com")) {
JOptionPane.showMessageDialog(null, "Email domain is wrong!");
email.requestFocus();
return;
}
// GENDER
//no gender selected
if (!m.isSelected() && !female.isSelected()) {
JOptionPane.showMessageDialog(null, "Choose a Gender!!");
return;
}
//both Genders are selected where it shoud be only one
else if (m.isSelected() && female.isSelected()) {
JOptionPane.showMessageDialog(null, "Select only One Gender!!");
return;
}
// is female or male selected
if (m.isSelected()) {
gender = "Male";
}
else if (female.isSelected()) {
gender = "Female";
}
// AGE
//is Age text field empty
String theAge = age.trim().getText();
if (theAge.isEmpty()) {
JOptionPane.showMessageDialog(null, "Enter your age !!");
age.requestFocus();
return;
}
int agee = 0; // Default
// Regular Expression used to ensure a Integer
// Numerical String value was supplied.
if (theAge.matches("\\d+")) {
agee = Integer.parseInt(theAge);
}
// only 18 + can register
if (agee < 18) {
JOptionPane.showMessageDialog(null, "You can't register because you are under 18!");
age.requestFocus();
return;
}
// DATABASE
Connection connection = null;
PreparedStatement reg, exist;
ResultSet rs = null;
String query = "INSERT INTO customer (Cu_name, Cu_password, Cu_age, Cu_gender, Cu_email, Cu_phone) VALUES (?, ?, ?, ?, ?, ?)";//enter user info in database
String record_exists = "SELECT * FROM customer where Cu_name=? and Cu_password= ? and Cu_age=? and Cu_gender=? and Cu_email=? and Cu_phone=?";
try {
String f = "jdbc:derby://localhost:1527/BStest";
connection = DriverManager.getConnection(f, "meme", "Moudhi102");
reg = connection.prepareStatement(query);
exist = connection.prepareStatement(record_exists);
reg.setString(1, name);
reg.setString(2, passw);
reg.setInt(3, agee);
reg.setString(4, gender);
reg.setString(5, emaill);
reg.setString(6, phone2);
exist.setString(1, name);
exist.setString(2, passw);
exist.setInt(3, agee);
exist.setString(4, gender);
exist.setString(5, emaill);
exist.setString(6, phone2);
rs = exist.executeQuery();
if (rs == null) {
reg.executeUpdate();
JOptionPane.showMessageDialog(null, "Complete! new user added !! ");
}
// User Already Exists In Database
else {
JOptionPane.showMessageDialog(null, "User already exists");
}
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
finally {
if (reg != null) {
reg.close();
}
if (rs != null) {
rs.close();
}
if (connection != null) {
connection.close();
}
}
}
Age may not necessarily be a good piece of criteria to use in your query WHERE clause when checking database records for a duplicate record of a particular User. It only enforces the fact that each record is only valid for a single year. Things change and Age, E-Mails, Phone Numbers, etc are some of those things that can change often. There is obviously nothing wrong with the concept if only the Name and Password are used for access validity (which should suffice for most cases) and the remaining criteria is merely used for indicating that updating is required to the User data account.
You should consider Supplied Passwords to be hashed and it is the hash that is stored in database. When a User supplies a password then that password is hashed and compared to a hash already stored in database. No one, including yourself should ever know what the password truly is. Only the User should ever know what the password might be. jBCrypt works pretty good for this. To hash a password using this library:
Imports:
import org.mindrot.jbcrypt.BCrypt;
import static org.mindrot.jbcrypt.BCrypt.hashpw;
A Class Member Varaible:
// Define the BCrypt WORKLOAD to use when generating
// password hashes. 10-31 is a valid value.
private static final int WORKLOAD = 12;
To Hash a plaintext password so as to store in database:
/**
* This method can be used to generate a string representing an account
* password suitable for storing in a database. It will be an OpenBSD-style
* crypt(3) formatted hash string of length=60 The BCrypt WORKLOAD is
* specified in the above static variable, a value from 10 to 31. A WORKLOAD
* of 12 is a very reasonably safe default. This automatically handles
* secure 128-bit salt generation and storage within the hash.
*
* #param password_plaintext The account's plaintext password as provided
* during account creation, or when changing an
* account's password.
*
* #return String - a string of length 60 that is the bcrypt hashed password
* in crypt(3) format.
*/
public static String hashPassword(String password_plaintext) {
String salt = BCrypt.gensalt(WORKLOAD);
String hashedPassword = hashpw(password_plaintext, salt);
return hashedPassword;
}
To check a plaintext password with a stored hash from database:
/**
* This method can be used to verify a computed hash from a plaintext (e.g.
* during a login request) with that of a stored hash from a database. The
* password hash from the database must be passed as the second argument.
*
* #param passwordAsPlainText The accounts plaintext password, as provided
* during a login request
*
* #param storedEncryption The accounts stored password hash, retrieved
* from the authorization database
*
* #return boolean - true if the password matches the password of the stored
* hash, false otherwise
*/
/*
public static boolean checkPassword(String passwordAsPlainText, String storedEncryption) {
boolean passwordVerification;
if (null == storedEncryption || !storedEncryption.startsWith("$2a$")) {
throw new java.lang.IllegalArgumentException(
"Invalid encryption provided for comparison");
}
passwordVerification = checkpw(passwordAsPlainText, storedEncryption);
return passwordVerification;
}

JOptionaPane Inputdialogbox and buttons

The below code is working perfecly
String input = JOptionPane.showInputDialog(null, "Enter Input",
"Dialog title",JOptionPane.QUESTION_MESSAGE);
Now I have Ok and Cancel buttons. I want to do something like
if(OK is selected){
String input1 = input
do something with input1
}
else if (cancel is selected){
System.dispose();
}
I'm clueless about what to write inside if condition. I know that for ShowOptionDialog I can get an int of selected option and use it but for inputdialog Im not sure how I can get both the selected option and input text.
Could you please help me
So the JavaDocs say
Returns:
user's input, or null meaning the user canceled the input
That mean that something like
String input = JOptionPane.showInputDialog(null, "Enter Input",
"Dialog title",JOptionPane.QUESTION_MESSAGE);
if (input != null) {
// User accepted
} else {
// User cancelled
}
Should work...

Categories