I'm trying to make a login function in java swing with functional programming style, below is my code
String username = txtUsername.getText();
String passwordStr = String.valueOf(txtPassword.getPassword());
User login = new User(username, passwordStr);
Optional<User> adminUser = Optional.of(new User("a", "a"));
Optional<User> user = Optional.ofNullable(login);
adminUser.filter(u -> u.equals(login))
.ifPresentOrElse(
u -> {
this.setVisible(false);
HomePageAdmin hma = new HomePageAdmin();
hma.setVisible(true);
},
() -> user.filter(u -> u.login(passwordStr))
.ifPresentOrElse(
u -> {
this.setVisible(false);
HomePagePeople hmp = new HomePagePeople(username);
hmp.setVisible(true);
},
() -> JOptionPane.showMessageDialog(null, "Wrong Credential")
)
);
everything is working fine, if I try to login with credentials other than "a" as username and "a" as password, however when I try to log in to the system with those credentials, it gives the "wrong credential" Pane as seen below
I also tried various ways with the filter function above with this alternatives
User login = new User(username, passwordStr);
User loginAdmin = new User("a", "a");
Optional<User> adminUser = Optional.of(loginAdmin);
Optional<User> user = Optional.ofNullable(login);
adminUser.filter(u -> u.equals(login))
the code above give the same error and won't accept the logic. However, if I try to change the adminUser.filter(u -> u.equals(login))
to adminUser.filter(u -> u.equals(loginAdmin))
, it works just fine, however this logic is wrong as the adminUser will always be equal to loginAdmin thus inputting anything into the textbox will allow user to log in to the admin page as seen in example below
any help is greatly Appreciated
I fixed my problem by implementing the same logic with the user.filter(u -> u.login(passwordStr))
code by creating a new method in my User
class called loginAdmin
as seen below
public boolean loginAdmin(String name, String pw) {
//file to be scanned
String Temp = "a";
String Temp2 = "a";
//returns true if there is another line to read
if (Temp.equals(Username) && Temp2.equals(Password)) {
return true;
} else {
return false;
}
}
this fix the problem and is implemented to the login class and here's the updated code
String Username = txtUsername.getText();
String Password = String.valueOf(txtPassword.getPassword());
User login = new User(Username, Password);
Optional<User> adminUser = Optional.of(login);
Optional<User> user = Optional.ofNullable(login);
adminUser.filter(u -> u.loginAdmin(Username, Password))
.ifPresentOrElse(
u -> {
this.setVisible(false);
HomePageAdmin hma = new HomePageAdmin();
hma.setVisible(true);
},
() -> user.filter(u -> u.login(Password))
.ifPresentOrElse(
u -> {
this.setVisible(false);
HomePagePeople hmp = new HomePagePeople(Username);
hmp.setVisible(true);
},
()
-> JOptionPane.showMessageDialog(null, "Wrong Credential")
)
);
Thanks everyone for helping me with this issue