Comparing input from Scanner with key and value from HashMap - java

I'm creating an app in which I need to create account and log into first.
I thought that I can use HashMap for it, where login is my key and password is my value.
Unfortunately, I've got problem with log into account that I've created.
Here is class with methods that take responsible for log. There is problem with checkIfLoginDataIsIncorrect
void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
if (loginDetails.containsKey(login)
&& loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
Main.java:
AccountMaker accountMaker = new AccountMaker();
AccountLogger accountLogger = new AccountLogger();
//I'VE WRITTEN IT JUST FOR CHECK:
HashMap<String, String> loginDetails = accountMaker.getLoginDetails();
loginDetails.put("lala","papa");
[...]
case 2:
while (loopIsTrue) {
accountLogger.inputLoginAndPassword();
if(!accountLogger.checkIfLoginDataIsIncorrect()) {
loopIsTrue = false;
} else {
loopIsTrue = true;
}
}
break;
AccountMaker.java:
public class AccountMaker {
private HashMap<String, String> loginDetails = new HashMap<>();
private String login, password;
private Scanner input = new Scanner(System.in);
[...]
HashMap<String, String> getLoginDetails() {
return loginDetails;
}
}
AccountLogger.java:
public class AccountLogger {
private AccountMaker accountMaker = new AccountMaker();
private Scanner input = new Scanner(System.in);
private HashMap<String, String> loginDetails = accountMaker.getLoginDetails();
private String login, password;
void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
//I'VE WRITTEN IT JUST FOR CHECK
System.out.println(login);
System.out.println(password);
///
if (loginDetails.containsKey(login) && loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
}
For example, if I write loginDetails.put("lala","papa"); and then I want to log into this acc program says Bad login or password.

The issue you're running into is you're polling the wrong HashMap
Create AccountMaker
The AccountMaker makes a new HashMap
Create 'AccountLogger'
The AccountLogger makes a new AccountMaker
The AccountMaker makes a new HashMap
We end up with two different instances of AccountMaker, and their different HashMaps
Try using the same AccountMaker that your AccountLogger uses, or pass it to the constructor
Using constructor:
//Main.java
AccountMaker accountMaker = new AccountMaker();
AccountLogger accountLogger = new AccountLogger(accountMaker);
//AccountLogger.java
class AccountLogger
{
private AccountMaker accountMaker;
public AccountLogger(AccountMaker maker)
{
accountMaker = maker;
}
}
Getting the same AccountMaker:
//Main.java
AccountLogger accountLogger = new AccountLogger();
AccountMaker accountMaker = accountLogger.getAccountMaker();
//AccountLogger.java
public AccountMaker getAccountMaker()
{
return accountMaker;
}

I am trying to understand your problem and have written below sample program to meet your requirement. Compare your code and see if you can fix your issue. If not, can you modify below code and let me know where it is failing.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Testlogin {
static Scanner input = new Scanner(System.in);
static Map<String, String> loginDetails = new HashMap<String, String>();
static String login,password;
static void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
if (loginDetails.containsKey(login)
&& loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
loginDetails.put("lala", "papa");
inputLoginAndPassword();
boolean loopIsTrue =true;
Testlogin testlogin = new Testlogin();
while (loopIsTrue) {
// Testlogin.inputLoginAndPassword();
System.out.println("You have entered login = "+login);
System.out.println("You have entered password = "+password);
if(!testlogin.checkIfLoginDataIsIncorrect()) {
loopIsTrue = false;
} else {
inputLoginAndPassword(); // bad login detected so asking for correct details again.
loopIsTrue = true;
//
}
}
//break;
}
}

Related

Why does my recursive method make my program throw an InvalidClassException?

In my program, I have a FacebookUser class that has an ArrayList of all of that user's friends. All of those friends may also have friends. I am using recursion to get a new ArrayList that contains all of the user's friends and all of the user's friends' friends and so on. I also serialized the FacebookUser class so I can save the data. Without the new recursive method, I can serialize without error and the data persists over executions. With the recursive method, though, I get an InvalidClassException. It shows that the exception is at the line that uses the ObjectInputStream to get the FacebookUser from memory.
I'm not understanding why the new method is causing the exception to be thrown from another method. I believe the problem lies only in the FacebookUser.java class (since getRecommendations is recursive method) but I thought it'd be best to also show the UserAccount.java class since the former extends the latter. Any help will be appreciated. Thank you.
Execution:
Exception in thread "main" java.io.InvalidClassException: FacebookUser; local class incompatible: stream classdesc serialVersionUID = 4110981517967863740, local class serialVersionUID = 5032562666539812166
at java.base/java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.base/java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject0(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject(Unknown Source)
at FacebookUser.readFile(FacebookUser.java:157)
at DriverClass.main(DriverClass.java:12)
FacebookUser.Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class FacebookUser extends UserAccount implements Serializable{
private String passwordHint;
private ArrayList<FacebookUser> friends;
public FacebookUser(String username, String password) {
super(username, password);
friends = new ArrayList<FacebookUser>();
}
#Override
public void getPasswordHelp() {
System.out.println("Password Hint: " + passwordHint);
}
public void getPasswordHelp(String username) {
if (friends.size() == 0) {
System.out.println("There is no user with that username.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
friends.get(i).getPasswordHelp();
break;
}
if (i == friends.size() - 1) {
System.out.println("There is no user with that username.");
break;
}
}
}
}
void setPasswordHint(String hint) {
passwordHint = hint;
}
void friend(FacebookUser newFriend) {
if (friends.contains(newFriend)) {
System.out.println("That person is already your friend.");
} else {
friends.add(newFriend);
}
}
void friend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("That person is already your friend.");
break;
}
if (i == friends.size() - 1) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
break;
}
}
}
}
void defriend(FacebookUser formerFriend) {
if (friends.contains(formerFriend)) {
friends.remove(formerFriend);
} else {
System.out.println("That person is not your friend.");
}
}
void defriend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("That person is not your friend.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("Password for " + username + ": ");
String passw = s.nextLine();
if (friends.get(i).getPassword().equals(passw)) {
friends.remove(i);
break;
} else {
System.out.println("Incorrect Password");
break;
}
}
if (i == friends.size() - 1) {
System.out.println("That person is not your friend.");
break;
}
}
}
}
ArrayList<FacebookUser> getRecommendations(FacebookUser friend) {
ArrayList<FacebookUser> recFriends = new ArrayList<FacebookUser>();
for (int i = 0; i < friend.getFriends().size(); i++) {
for (int j = 0; j < recFriends.size(); j++) {
for (int k = 0; k < recFriends.size(); k++) {
if (recFriends.get(j).equals(recFriends.get(k))) {
recFriends.remove(j); // This removes any duplicate friends so there won't be an infinite loop.
break;
}
}
}
recFriends.addAll(friend.getFriends().get(i).getRecommendations(friend)); // This adds the friends' friends' friends and so on into the ArrayList.
}
return recFriends;
}
ArrayList<FacebookUser> getFriends() {
ArrayList<FacebookUser> friendsCopy = new ArrayList<FacebookUser>();
for (int i = 0; i < friends.size(); i++) {
friendsCopy.add(friends.get(i));
}
Collections.sort(friendsCopy, new Comparator<FacebookUser>() {
#Override
public int compare(FacebookUser fb1, FacebookUser fb2) {
return fb1.toString().compareToIgnoreCase(fb2.toString());
}
});
return friendsCopy;
}
public static void writeToFile(FacebookUser facebookUser) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("FacebookUser.bin"));
oos.writeObject(facebookUser); // This saves the data.
}
public static FacebookUser readFile() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("FacebookUser.bin"));
FacebookUser facebookUser = (FacebookUser) ois.readObject(); // This reads in the data which is called in the DriverClass class line 12.
return facebookUser;
}
}
UserAccount.java
import java.io.Serializable;
public abstract class UserAccount implements Serializable{
private String username;
private String password;
private boolean active;
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
active = true;
}
public boolean checkPassword(String password) {
if (password.equals(this.password)) {
return true;
} else {
return false;
}
}
public void deactivateAccount() {
active = false;
}
public String getPassword() {
return password;
}
public String toString() {
return username;
}
public boolean checkActive() {
if (active == true) {
return true;
} else {
return false;
}
}
public abstract void getPasswordHelp();
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAccount other = (UserAccount) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
DriverClass.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class DriverClass {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int choice = 0;
String username;
FacebookUser fu0;
try {
fu0 = FacebookUser.readFile();
} catch (FileNotFoundException e) {
fu0 = new FacebookUser("Robert", "password1");
}
while (choice != 5) {
System.out.println(
"1. List Users \n2. Add a User \n3. Delete a User \n4. Get Password Hint \n5. Get Recommendations \n6. Quit");
Scanner s = new Scanner(System.in);
choice = s.nextInt();
switch (choice) {
case 1:
System.out.println(fu0.getFriends());
break;
case 2:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.friend(username);
break;
case 3:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.defriend(username);
break;
case 4:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.getPasswordHelp(username);
break;
case 5:
System.out.println(fu0.getRecommendations(fu0));
break;
case 6:
FacebookUser.writeToFile(fu0);
break;
}
}
}
}
The exception suggests that the SerialVersionUID the JVM generated differs for some instances of the FacebookUser object. If you make your class implement Serializable, it is highly recommended that you explicitly declare the SerialVersionUID variable to avoid exceptions like these.
So in the FacebookUser class you should declare a variable like this:
private static final long serialVersionUID = 42L;
See this answer for more details.

NullPointerException on a static attribute

I am creating a simple login program in java. Here is the code i have so far.
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class PasswordProgram {
public static String user;
public String password;
public static boolean part1Finish = false;
public File file = new File("D:/file.txt");
public FileWriter UsernameWrite;
public char[] user1;
public void part1() {
System.out.println("Please create an account: ");
Scanner input = new Scanner(System. in );
System.out.println("Type in a username: ");
String user = input.next();
System.out.println("Type in a Password: ");
String password = input.next();
try {
UsernameWrite = new FileWriter(file);
UsernameWrite.write(user);
UsernameWrite.write(password);
System.out.println(user);
UsernameWrite.close();
part1Finish = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void part2() {
Scanner scan = new Scanner(System. in );
System.out.println("Please confirm your username: ");
String usercheck = scan.next();
int PassAttempts = 5;
int UserAttempts = 5;
user1 = user.toCharArray();
user1 = password.toCharArray();
char[] usernamecheck = java.util.Arrays.copyOfRange(user1, 0, user.length());
System.out.println(usernamecheck);
do {
if (usercheck.equals(usernamecheck)) {
while (PassAttempts > 0) {
System.out.println("Please confirm your password: ");
String passcheck = scan.next();
if (passcheck.equals(password)) {
System.out.println("Thank You ");
} else if (passcheck != password && PassAttempts > 0) {
PassAttempts--;
System.out.println("That is incorrect. Please Try Again");
passcheck = scan.nextLine();
} else {
System.out.println("You have run out of Password Attempts");
break;
}
}
} else if (usercheck != user && UserAttempts > 0) {
UserAttempts--;
System.out.println("That is an incorrect username. Please Try Again");
usercheck = scan.nextLine();
} else {
System.out.println("You have run out of Username Attempts");
break;
}
} while (UserAttempts > 0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PasswordProgram login = new PasswordProgram();
login.part1();
if (part1Finish == true) {
login.part2();
}
}
}
The problem i am getting is in the method part2. Here when I try to add the username that was saved under the variable user into a character array to use it as a range I get the error NullPointerException.
After investigating i see that when running part2 the value of user is null and therefore I get the error.
Is there a way I could do this through the FileReader method instead or how can i fix the current error I am getting ? Thank you.
Because the static field user is never assigned in part1, you get a NullPointerException when you try to use it in part2.
There are also other issues in the posted code:
why there is a file involved is unclear
you use != with String, for example in passcheck != password
you use equals between String and char[] in usercheck.equals(usernamecheck)
passcheck is assagned but never used
local variables (because of their names) are hiding some fields
UsernameWrite and UserAttempts have non conventional names (should be usernameWrite and userAttempts
You have two user variables declared, one which is static and has global scope, another which is local to part1(). When part2() is attempting to access user, it is using the static declaration, which is null. Your modifications to user in part1() are done to the local variable.
This is something called variable shadowing and should be avoided at all costs.
See the below example:
class Ideone
{
static String bla = "test1";
public static void myMethod() {
String bla = "test2";
System.out.println(bla);
}
public static void main (String[] args) throws java.lang.Exception
{
myMethod();
System.out.println(bla);
}
}
It outputs:
test2
test1

DeSerialized Object containing ArrayList has all null values

Hopefully someone can provide some insight on this issue. I have created an instance of an object that contains an ArrayList of information (username, password, password hint). I am trying to serialize the object. It looks like it is serializing properly, but when I restart the project to deserialize, it returns null values in the ArrayList. Why is it returning null values for the ArrayList objects?
Driver Class:
import java.io.Serializable;
public class TestingDriver implements Serializable{
private static final long serialVersionUID = 12345L;
private static TestingAccount users = new TestingAccount();
public static void main(String[] args) {
int foreverLoop = 0;
users = DeSerialize.main();
while (foreverLoop < 1) {
int selection = users.displayMainMenu();
if (selection == 1) {
users.listUsers();
}
else if (selection == 2) {
users.addUser();
}
else if (selection == 3) {
users.deleteUser();
}
else if (selection == 4) {
users.getPasswordHint();
}
else if (selection == 5) {
Serialize.main(users);
System.exit(0);
}
else {
System.out.println("That option does not exist. Please try again.");
}
}
}
}
TestingUser Class (objects of this class will populate the ArrayList):
import java.io.Serializable;
public class TestingUser extends UserAccount implements Serializable, Comparable <TestingUser> {
private static final long serialVersionUID = 12345L;
public TestingUser(String username, String password, String passwordHint) {
super(username, password, passwordHint);
}
public TestingUser() {
}
#Override
public void getPasswordHelp() {
System.out.println("");
System.out.println("Password hint: " + passwordHint);
System.out.println("");
}
#Override
public int compareTo(TestingUser otherAccount) {
if (this.username.compareToIgnoreCase(otherAccount.username) < 0) {
return -1;
}
else if (this.username.compareToIgnoreCase(otherAccount.username) > 0) {
return 1;
}
else {
return 0;
}
}
}
TestingAccount class (calling this class creates an object that contains the ArrayList):
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Scanner;
public class TestingAccount implements Serializable {
private static final long serialVersionUID = 12345L;
public ArrayList<TestingUser> userList;
private String username;
private String password;
private String passwordHint;
public TestingAccount() {
userList = new ArrayList<TestingUser>();
}
public void listUsers() {
for (int i=0; i<this.userList.size(); i++) {
System.out.println(this.userList.get(i));
}
}
#SuppressWarnings("resource")
public void addUser() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a username: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
System.out.println("This user already exists.");
}
else {
System.out.println("Please enter a password: ");
password = input.next();
System.out.println("Please enter a password hint: ");
passwordHint = input.next();
tempAccount.password = password;
tempAccount.passwordHint = passwordHint;
this.userList.add(tempAccount);
System.out.println("Account " + tempAccount.username + " has been added.");
}
}
#SuppressWarnings("resource")
public void deleteUser() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the username to be deleted: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
int actIndex = this.userList.indexOf(tempAccount);
System.out.println("Please enter the password: ");
password = input.next();
tempAccount.password = password;
boolean passwordGood = this.userList.get(actIndex).CheckPassword(tempAccount);
int accountIndex = this.userList.indexOf(tempAccount);
tempAccount = this.userList.get(accountIndex);
if (passwordGood == true) {
this.userList.remove(actIndex);
System.out.println("The account has been deleted.");
}
else {
System.out.println("The password is not correct.");
}
}
else {
System.out.println("The account does not exist.");
}
}
#SuppressWarnings("resource")
public void getPasswordHint() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a username: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
int actIndex = this.userList.indexOf(tempAccount);
tempAccount = this.userList.get(actIndex);
System.out.println("The password hint isL: " + tempAccount.passwordHint);
}
else {
System.out.println("The account does not exist.");
}
}
#SuppressWarnings({ "resource" })
public int displayMainMenu() {
int selection = 0;
Scanner input = new Scanner(System.in);
System.out.println("");
System.out.println("System Menu:");
System.out.println("1. List Users");
System.out.println("2. Add User");
System.out.println("3. Delete User");
System.out.println("4. Get Password Hint");
System.out.println("5. Quit");
System.out.println("");
System.out.println("What would you like to do?");
selection = input.nextInt();
return selection;
}
}
Serialize class:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Serialize {
public static void main(TestingAccount users) {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("serialize"));
oos.writeObject(users);
oos.close();
} catch (FileNotFoundException e1) {
System.err.println("File not found.");
} catch (IOException e2) {
System.err.println("Unable to serialize.");
e2.printStackTrace();
}
}
}
Deserialize class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeSerialize {
public static TestingAccount main() {
TestingAccount deSerialize = null;
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("serialize"));
deSerialize = (TestingAccount) ois.readObject();
ois.close();
} catch (FileNotFoundException e1) {
System.err.println("Unable to open file.");
} catch (IOException e2) {
System.err.println("Could not de-serialize.");
e2.printStackTrace();
} catch (ClassNotFoundException e3) {
System.err.println("Could not cast to class TestingAccount.");
}
return deSerialize;
}
}
It looks like UserAccount isn'tSerializable. So when you serialize the derived TestingUser class, none of the UserAccount data gets serialized. See Object Serialization Specification #2.1.13(a). TestingUser doesn't have any instance state of its own to serialize.
The solution is to make UserAccount implement Serializable.
Not sure why this comes as a surprise.

Java : Simple Loop

Here is a simple version without any loops. How can I make it loop like "Wrong password. Try again." until user puts the right password instead stopping the program
(or give them 3 chances before it stops)?
import java.util.Scanner;
public class helloworld2
{
public static void main(String[] arg)
{
Scanner q = new Scanner(System.in);
long Pass;
boolean auth = true;
System.out.println("Enter Password :");
Pass = q.nextLong();
if ( Pass != 1234 )
{
System.out.println("Wrong Password!");
auth = false;
}
else
{
System.out.println("Password Confirmed.");
auth = true;
}
if (auth) {
////blablabla
}
else
{
return;
}
}
}
public class helloworld2
{
public static void main(String[] arg)
{
Scanner q = new Scanner(System.in);
long Pass;
boolean auth = true;
boolean rightPassword = false;
while(!rightPassword){//repeat until passwort is correct
System.out.println("Enter Password :");
Pass = q.nextLong();
if ( Pass != 1234 )
{
System.out.println("Wrong Password!");
auth = false;
}
else
{
rightPassword = true;//let the loop finish
System.out.println("Password Confirmed.");
auth = true;
}
}
// Here do what you want to do
//because here the user has entered a right password
}
}

How to hold multiple usernames and passwords in properties file

I have a properties file that holds username and password which I use in my java program however I am not being able to store more than one username and password like I do in database and just select where username and password match the many rows in the database. I imagine I need to have a two-dimensional array stored in the file holding usernames and corresponding passwords but I've failed to figure out how to do it and neither has google given me a way to hold a two-dimensional array in a file yet. Here are the key/value pairs for my username and password in the file
`password=k
username=k`
And here is the code that reads them and compares with what the user inserts
`String usr = userfield.getText();
String pwd = new String(pwdfield.getPassword());
Properties config = new Properties();
InputStream is;
try {
is = new FileInputStream("config.properties");
config.load(is);
if (usr.toString().equals(config.getProperty("user").toString()) && pwd.toString().equals(config.getProperty("pass").toString())) {
new DocMenu();
lgFrame.dispose();
} else {
JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);
}
is.close();
} catch (Exception ex) {
System.out.println(ex);
ex.printStackTrace();
}`
Could someone please tell me how to change the properties file and the code so that I am able to have multiple usernames and passwords in the file to grant access to any user as long as their username and password exist.
If you store the property name as a concatenation of some key with the username, and the password as the value like this;
#Some bad passwords
username.bob=password
username.scott=tiger
username.admin=admin
..then you can check like this;
String password = config.getProperty("username." + usr.toString());
if (password != null && password.equals(pwd.toString())) {
new DocMenu();
lgFrame.dispose();
} else {
JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);
}
In your posted code, you have 'username' in the properties, and you are trying to read the 'user' property.
Same goes for the password.
But this will only allow you yo have one pair user/pwd. You should have a more elaborated structure in your properties file. For instance you could have
user1=pwd1
user2=pwd2
...
and then check with something like :
if (password != null && password.equals(config.getProperty(usr)){
// ok ...
}
If you have to use properties, I think there's little option beyond doing
username.1
username.2
username.3
and iterating through until you have an index that you can't find the property for (in this case, username.4).
For more complex configurations, I would investigate frameworks such as Apache Commons Config, which can handle lists of elements.
As promised, here is the HashSet serialise/deserialise code:
import java.util.*;
import java.io.*;
class UserPasswordMap{
private HashMap<String,String> userMap;
private String m_filename;
public UserPasswordMap()
{
userMap = null;
m_filename = null;
userMap = new HashMap<String,String>();
}
public UserPasswordMap(String filename, String credo)
{
try{
m_filename = filename;
File f = new File(m_filename);
userMap = new HashMap<String,String>();
if(f.exists() && (!(f.canRead() && f.canWrite()))){
System.err.println("Oops, Insufficient permissions to read/write for filename: "+m_filename);
}else{
f.createNewFile();
}
}catch(Exception e){
System.err.println(e.getMessage());
}
if(credo.equals("D")){
try{
ReadMap(filename);
}catch(Exception e){ System.err.println(e.getMessage());}
}
}
public void ReadMap(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
userMap = (HashMap<String,String>)ois.readObject();
fis.close();
}
public void WriteMap(String filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userMap);
oos.close();
}
public ArrayList<String> getUsers()
{
ArrayList<String> users = new ArrayList<String>();
if(userMap == null){
return null;/*or return users*/
}else{
for(String s:userMap.keySet()){
users.add(s);
}
}
return users;
}
public ArrayList<String> getPasswords()
{
ArrayList<String> passwords = new ArrayList<String>();
if(userMap == null){
return null;/*or return users*/
}else{
for(String s:userMap.values()){
passwords.add(s);
}
}
return passwords;
}
public String getPassword(String username)
{
return userMap.get(username);
}
public void addUser(String username, String password){
userMap.put(username, password);
try{
WriteMap(m_filename);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
public void saveData(){
if(m_filename == null){
System.err.println("File-Name is not supplied");
}else{
try{
WriteMap(m_filename);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
}
}
And the test code:
public class Main{
private UserPasswordMap map;
public static void main(String[] args){
Main obj = new Main();
obj.init();
Scanner scan = new Scanner(System.in);
System.out.println("0. Init With Serialisation(CAN THROW ERROR)");
while(true){
System.out.println("1. Add New User");
System.out.println("2. Query Permissions");
System.out.println("3. Exit");
int data = scan.nextInt();
switch(data){
case 0: obj.initWithSerialisation();
break;
case 1: obj.addNewUser();
break;
case 2: obj.queryPerms();
break;
case 3: System.exit(0);
}
}
}
public void init()
{
map = new UserPasswordMap("try1.ser","");
}
public void initWithSerialisation()
{
map = new UserPasswordMap("try1.ser","D");
}
private Scanner scan;
public void addNewUser()
{
System.out.print("Enter User:");
scan = new Scanner(System.in);
String username = scan.nextLine();
System.out.print("Enter Pass:");
String password = scan.nextLine();
map.addUser(username, password);
}
public void queryPerms()
{
System.out.print("Enter User:");
if(scan == null){ scan = new Scanner(System.in);}
String username = scan.nextLine();
System.out.print("Enter Pass:");
String pass = scan.nextLine();
if(map.getUsers().contains(username) && map.getPassword(username).equals(pass)){
System.out.println("authenticated!");
}else{
System.out.println("Oops Wrong credentials!");
}
}
}

Categories

Resources