This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Okay, so I even printed out the values of the variables that will be compared to the username and password.
Username luke
Password: password
Username Attempt: luke
Password Attempt: [C#5e15c325
But I'm attempting to input 'password'.... The JPasswordField holds a character array, so I have to use the 'toCharArray' when comparing the char [] 'passwordAttempt' and the String 'pass' that holds the password that is held in a file. Maybe this is why the password attempt is some strange value?
Here's the code of the login() function:
public void login() {
//booleans for error-handling and user authentication
boolean usersInDatabase = true;
boolean userAuthentication = false;
boolean passwordAuthentication = false;
//create the data reader
try {
reader = new Scanner(user1); //user1 is a file
} catch (FileNotFoundException noUsers) {
JOptionPane.showMessageDialog(window, "No users in the database");
usersInDatabase = false;
}
//variables
String user = ""; //variables that will hold the file data which has the
String pass = ""; //username and password
try {
user = reader.nextLine();
pass = reader.nextLine();
}
//you can skip through the error-handling
catch (NoSuchElementException noUsers) {
JOptionPane.showMessageDialog(window, "No users in the database");
usersInDatabase = false;
}
if (usersInDatabase)
{
String userAttempt = usernameField.getText();
String message = ""; //message to display if authentication is unsuccessful
char[] passwordAttempt = passwordField.getPassword();
//okay -- important stuff
//username authentication
if (userAttempt == user) {
userAuthentication = true;
}
else
message += "Incorrect Username -- ";
//password authentication
if (passwordAttempt == pass.toCharArray()) { //check to see if the input matches the string (a character array) that has the value of the file
passwordAuthentication = true;
}
else
message += "Incorrect Password";
if (passwordAuthentication == true && userAuthentication == true)
{
JOptionPane.showMessageDialog(window, "Authorization Successful");
cards.show(cardPanel, "documents");
}
else if(passwordAuthentication == false && userAuthentication == false)
JOptionPane.showMessageDialog(window, message);
//to print out the values for debugging
System.out.println("Username " + user + "\nPassword: " + pass + "\nUsername Attempt: " + userAttempt + "\nPassword Attempt: " + passwordAttempt);
}
}
passwordAttempt == pass.toCharArray()
You cannot compare arrays like this in Java.
Use
Arrays.equals(passwordAttempt, pass.toCharArray());
Or convert them to Strings and compare those (also not by using ==!)
passwordAttemptString.equals(pass);
Related
I got a list(Employees) of employees(object of class Employee) and I try to iterate over that list so I can validate the entered information otherwise rise a message error, It does validate the information and logins in when right information but it raises an error in all others employees checked existent in the list.
String username = FieldUsername.getText();
String password = FieldPassword.getText();
Iterator<Employee> i = Employees.iterator();
while (i.hasNext()) {
Employee o = i.next();
if (o.getName().equals(username) & o.getPassword().equals(password)) {
if (o.getJob().equals("President")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserPresident uno = new UserPresident();
uno.show();
this.dispose();
} else if (o.getJob().equals("Manager")) {
if (o.getArea().equals("Production")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserProductionManager uno = new UserProductionManager();
uno.show();
}else if(o.getArea().equals("Marketing")){
JOptionPane.showMessageDialog(null, "Welcome");
UserMarketingManager uno = new UserMarketingManager();
uno.show();
}else{
JOptionPane.showMessageDialog(null, "Welcome");
UserHRManager uno = new UserHRManager();
uno.show();
}
} else {
JOptionPane.showMessageDialog(null, "Bienvenido");
UserEmployee uno = new UserEmployee();
uno.show();
}
} else {
JOptionPane.showMessageDialog(null, "Username or password is incorrect!");
FieldUsername.setText("");
FieldPassword.setText("");
}
}
Your code will go through each and every employee even if it is correct login it continues to look for another employee to match, you need to make it print Username or password is incorrect! after the loop is done and it hasn't found a match, you could do this by adding a boolean value before the loop and if a correct user was found then change the boolean to not print the Username or password is incorrect!, a simple example:
String username = FieldUsername.getText();
String password = FieldPassword.getText();
Iterator<Employee> i = Employees.iterator();
boolean isCorrectLoginFound = false // Checks for correct login
while (i.hasNext()) {
Employee o = i.next();
if (o.getName().equals(username) && o.getPassword().equals(password)) {
isCorrectLoginFound = true;
if (o.getJob().equals("President")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserPresident uno = new UserPresident();
uno.show();
this.dispose();
break;
} else if (o.getJob().equals("Manager")) {
if (o.getArea().equals("Production")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserProductionManager uno = new UserProductionManager();
uno.show();
break;
}else if(o.getArea().equals("Marketing")){
JOptionPane.showMessageDialog(null, "Welcome");
UserMarketingManager uno = new UserMarketingManager();
uno.show();
break;
}else{
JOptionPane.showMessageDialog(null, "Welcome");
UserHRManager uno = new UserHRManager();
uno.show();
break;
}
} else {
JOptionPane.showMessageDialog(null, "Bienvenido");
UserEmployee uno = new UserEmployee();
uno.show();
break;
}
}
}
if (!isCorrectLoginFound) {
JOptionPane.showMessageDialog(null, "Username or password is incorrect!");
FieldUsername.setText("");
FieldPassword.setText("");
}
hello i am having a problem when trying to catch tokens from a html form , the form have 3 tokens to fill, password, repeatpassword and email the email token are giving me problems, if i fill an email short like 123#hotmail.com it work fine, but if i fill b0rtzito#hotmail.com it dont work and i dont know the reason, i tried with many combinations unssuccessfull, maybe someone can point me , thanks in advance.
if (command.startsWith("PasswordCreate2"))
{
StringTokenizer create = new StringTokenizer(command, " ");
String pass = null, repeat = null, email = null;
create.nextToken();
if (create.hasMoreTokens())
{
pass = create.nextToken();
}
if (create.hasMoreTokens())
{
repeat = create.nextToken();
}
if (create.hasMoreTokens())
{
email = create.nextToken();
}
if (!((pass == null) || (repeat == null) || (email == null)))
{
if (!pass.equals(repeat))
{
player.sendMessage("The password doesn't match with the repeated one!");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
if (pass.length() < 3)
{
player.sendMessage("The password is shorter than 3 chars! Please try with a longer one.");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
if (pass.length() > 30)
{
player.sendMessage("The password is longer than 30 chars! Please try with a shorter one.");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
if (!(email.contains("#") || email.contains(".")))
{
player.sendMessage("please fill a valid email record you may need it to recover your account.");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
PlayerSecondPassword.onCreate2(player, pass, email);
}
else
{
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
player.sendMessage("Please fill all of the fields before continuing.");
return false;
}
i always get the return "Please fill all of the fields before continuing"
Thanks for looking. I'm having an issue with getting my database and connection to match passwords. MySQL and my java md5s are the same, but when I check to see if it's equal in comparing, it says they're not the same. I'm not really sure what I'm doing wrong here.
For example, here are the generated MD5's for both:
MySQL: 798da231909aa3645eced61dde9f9bfa
Java: 798da231909aa3645eced61dde9f9bfa
So, I'm not sure why they wouldn't be equal when I check.
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
/**
* Created by Ohlaph on 8/29/2015.
*/
public class Conn {
private Connection con = null;
private String JDBC = "com.mysql.jdbc.Driver";
private String username = "root", password = "password";
private Statement statement;
private ResultSet rs;
private String user_name, user_password;
private String dbname = "jdbc:mysql://localhost/thon";
public Conn(String user, String password) {
this.user_name = user;
this.user_password = MD5(password);
}
public void Connect() throws Exception {
try {
Class.forName(JDBC);
con = DriverManager.getConnection("jdbc:mysql://localhost/thon", username, password);
statement = con.createStatement();
} catch (Exception e) {
System.out.println(e);
System.out.println("Failure");
}
}//end CONNECT()
public boolean checkIt() throws Exception {
String check = "select * from users";
try {
rs = statement.executeQuery(check);
while (rs.next()) {
String usr = rs.getString("nickname");
String pwd = rs.getString("password");
System.out.println("user name " + usr + ", Password " + pwd);
if (user_name.equals(usr) && user_password.equals(pwd)) {
System.out.println("Access Granted");
return true;
} else {
System.out.println("Access Denied");
return false;
}
}
} catch (Exception e) {
System.out.println("Error " + e);
}
con.close();
return false;
}//end checkIt()
public static String MD5( String source ) {
try {
MessageDigest md = MessageDigest.getInstance( "MD5" );
byte[] bytes = md.digest( source.getBytes("UTF-8") );
return getString( bytes );
} catch( Exception e ) {
e.printStackTrace();
return null;
}
}//end MD5()
private static String getString( byte[] bytes ) {
StringBuffer sb = new StringBuffer();
for( int i=0; i<bytes.length; i++ )
{
byte b = bytes[ i ];
String hex = Integer.toHexString((int) 0x00FF & b);
if (hex.length() == 1)
{
sb.append("0");
}
sb.append( hex );
}
return sb.toString();
}// end getString()
}//end Conn.java
The line user_password = MD5(user_password); is inside the while loop, so it will MD5 the value on first user record, then MD5 the already MD5'd value on the second user record, and so on, so that by the time you get to the user in question you have a very mangled value.
Maybe it would be better to do the MD5 in the constructor.
Unrelated, but instead of querying the entire user table every time, you should use something like:
String sql = "select password from users where nickname = ?";
and use a PreparedStatement to set the marker value (?).
Update
Your error is that you do the System.out.println("Access Denied"); return false; inside the loop, so the loop never gets to look at the second record.
Adding where nickname = ? to the SQL would help fix that, since only one record would be returned (assuming nickname is unique), but the loop logic is still flawed.
I am trying to show a messagebox when either the username or password textbox is empty but when I run the project the only textbox showing is "JOptionPane.showMessageDialog(null,"Your Username or Password is incorrect");" Please help and Thank You!
private void jButton1ActionPerformed(ActionEvent evt) {
String user=txtUsername.getText();
char[] pass=txtPassword.getPassword();
if(user == null) {
JOptionPane.showMessageDialog(null,"Username Field is empty");
} else if(pass==null) {
JOptionPane.showMessageDialog(null,"Password Field is empty");
} else {
String sql="select * from account where username=? and password=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1,txtUsername.getText());
pst.setString(2,txtPassword.getText());
rs=pst.executeQuery();
if (rs.next()) {
GridlockMain a=new GridlockMain();
a.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,"Your Username or Password is incorrect");
txtUsername.setText(null);
txtPassword.setText(null);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e);
}
}
}
JTextField.getText() does not return null if you keep it empty. Try to check value using isEmpty method at if condition.
String user=txtUsername.getText();// It return empty String ""
// even no data is entered.
if(user.isEmpty){
JOptionPane.showMessageDialog(null,"Username Field is empty");
}
......
try this..
if(!user.length() > 0){
JOptionPane.showMessageDialog(null,"Username Field is empty");
}
else if(!pass.length > 0){
JOptionPane.showMessageDialog(null,"Password Field is empty");
}
I also struggled with the text Validation process. I found a very easy way to test this. Here, instead of using JOptionPane to show a message to the user, I just didn't allow them to enter, or press the button. Here's my code:
//Validate whether user Has input some information:
if(UserNameTA.getText() == null || UserNameTA.getText().trim().isEmpty())
{
btnEnter.setEnabled(false);
}
else
{
//Make a new JFrame for login
new ProfileHome().setVisible(true);
frame.dispose();
}
btnEnter.setEnabled(true);
I hope this at least guides you to your success.
It returns an empty string "" compare the
StringUtils.isEmpty(txtUsername.getText())
String user = txtUsername.getText();
String pw = txtPassword.getText();
if(user.isEmpty() || (pw.isEmpty()))
{
JOptionPane.showMessageDialog(null, "Your Username or Password is incorrect" );
}
else
{
//proceed to query
if (user.length() == 0) {
JOptionPane.showMessageDialog(null, "Username Field is empty");
} else if (pass.length() == 0) {
JOptionPane.showMessageDialog(null, "Password Field is empty");
}
So I am creating a program called RegisterandLogin, which basically you have to enter a username, password and re-enter-password in order to create a new account.
Validation of users and passwords can be done using:
1.A user name you typed in during registration can not be the same as any
of the 5 names in username.txt.
2.Also the user name has to be between 5 and 8 characters without any numbers (i.e., the user name can be only [A-Z] or [a-z] but not any digits like [0-9]).
3.A password is also between 5 and 8 characters, with numbers allowed (so 12345 and abcde are both valid passwords).
4.The retyped password must be the same as password, otherwise, an error message is output after hitting the Register button.
When a user name passes the 5 to 8 characters validity check, user name does not exist
in username.txt, and Password passes the validity check, the new user name is added
to username.txt.
So I already created the username.txt with five names. However, the problem I have is I am not sure how to read the username.txt file so it can check whether the username has been used or not.
Code here, little long , any help will be appreciate.
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class RegisterandLogin extends JFrame {
// variables for Sign up screen
private JPanel suP;
private JLabel suName, suPW, suRetypePW;
private JTextField suNameText, suPWText, suRetypePWText;
private JButton suButton;
public RegisterandLogin ()
{
super ("Register and Login");
signupScreen();
}
public void signupScreen () {
suP = new JPanel ();
// suP.setSize(50, 60);
setLayout (new FlowLayout());
setContentPane (suP);
suName = new JLabel ("Name");
suNameText = new JTextField (10);
suPW = new JLabel ("Password");
suPWText = new JTextField (10);
suRetypePW = new JLabel ("Retype Password");
suRetypePWText = new JTextField (10);
suButton = new JButton ("Register");
suP.add (suName);
suP.add(suNameText);
suP.add(suPW);
suP.add (suPWText);
suP.add (suRetypePW);
suP.add (suRetypePWText);
suP.add(suButton);
suP.setVisible(true);
ButtonHandler handlersu = new ButtonHandler();
suButton.addActionListener(handlersu);
}
public void validatebyarray() {
String[] read1=null;
String[] read=null;
read1=files(read);
int minL = 5, maxL = 8;
String stName = suNameText.getText();//username
String stPW = suPWText.getText();//password
String stRePW = suRetypePWText.getText();//retype password
/******************************************************
* Validate user name *
******************************************************/
if(stName.length()< minL || stName.length() > maxL ) // Check username length
System.out.println ("User name must be between 5 and 8");
else
{
//check invalid characters in username
for (int i = 0 ; i < stName.length(); i ++) // Check for invalid character
if (!
((stName.charAt (i)>= 'A' && stName.charAt (i) <= 'Z') ||
(stName.charAt (i)>= 'a' && stName.charAt (i) <= 'z')))
{
System.out.println ("Username contains invalid character");
break;
}
// Match the names in the array (file or database)
// Note the logic below works but is NOT secure since it discloses
// information about user names.
boolean uNfound = false;
for (int j = 0; j < 4; j++)
if (read1[j].equals(stName))
{
System.out.println ("User name " + read1[j] + " already exits");
uNfound = true;
break;
}
//if (!uNfound)
// System.out.println ("User name " + stName + " created");
}
System.out.println ("After UN");
/******************************************************
* Validate password *
******************************************************/
if(stPW.length()< minL || stPW.length() > maxL ) // Check username length
System.out.println ("Password must be between 5 and 8");
else
{
//check invalid characters in username
for (int i = 0 ; i < stPW.length(); i ++) // Check for invalid character
if (!
((stPW.charAt (i)>= '0' && stPW.charAt (i) <= '9') ||
(stPW.charAt (i)>= 'A' && stPW.charAt (i) <= 'Z') ||
(stPW.charAt (i)>= 'a' && stPW.charAt (i) <= 'z')))
{
System.out.println ("Password contains invalid character");
break;
}
// Note stName replaced by stPW and stRePW;
// uN[] replaced by pN[]
boolean uNfound = false;
if (stPW.equals(stRePW))
{
System.out.println ("User name " + stName + " created");
uNfound = true;
}
if (!uNfound)
System.out.println ("Passwords does not match");
}
//System.out.println ("After UN again");
}
class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event){
if (event.getSource () == suButton){
System.out.println ("SU button in register screen hit");
validatebyarray();
}
}
}
public String[] files(String [] read)
{
try {
BufferedReader file1 = new BufferedReader(new FileReader("usernames.txt"));
// Scanner fileReaderScan=new Scanner(readTextFile);
//only want first 5 lines
for(int count=0;count<5;count++)
{
read[count] = file1.readLine(); //use readLine method
System.out.println(read[count]);
}
file1.close(); //close file
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("OOps");
}
return read;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RegisterandLogin rl = new RegisterandLogin ();
rl.setSize(200, 300);
rl.setVisible(true);
rl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You can do something like below in you read method
public String[] files()
throws FileNotFoundException
{
List<String> existingUsers = new ArrayList<String>();
File users = new File("username.txt");
Scanner sc = new Scanner(users);
while (sc.hasNext()) {
existingUsers.add(sc.nextLine());
}
return existingUsers.toArray(new String[existingUsers.size()]);
}
You could probably do this just using a BufferedReader as you've tried, but in the code you've written you've hardcoded the number of lines to read but the question talks about appending lines to the file.
I'd imagine you'd also want the file to contain the passwords (this is homework, in real life you never, ever store passwords) as presumably you're going to end up checking them too in some way. Given the restrictions you have to impose with regards to legal characters you can probably easily pick a separator so you can store a username and password per line in the file.
Since your use pattern is that you need to check existence efficiently a better data structure to use for the usernames would be a set, given than you'd want the passwords too, a map from username to password would be a good choice.
When using resources (such as files) it's best to close them using a finally block so that no matter what goes wrong you release your use of the resource.
So you'd end up with something like...
Map<String,String> loadUsersAndPasswords() {
Map<String,String> usernameToPassword = new HashMap<String,String>();
FileReader fr = new FileReader("usernames.txt");
try {
BufferedReader br = new BufferedReader(fr);
for (String line = br.readLine(); line != null; line = br.readLine()) {
int splitLocation = line.indexOf(":");
String username = line.substring(0, splitLocation);
String password = line.substring(splitLocation + 1);
usernameToPassword.put(username, password);
}
} finally {
fr.close();
}
return usernameToPassword;
}