getting all keys belonging to one object in a hashmap - java

Below is my user Class. I also have a Card class which is the parent class of a Single currency card class and a multi card currency class.
I am fairly new to coding and have trouble understanding some concepts. What I need to do is return the cards that the user owns if the username and password match. This is in the getCards method. After this, i need to add the card to the Hashmap list if the username and password match. Any tips or other sites that would really help as I struggle a lot with the HashMap concept.
public class User {
String username;
String password;
User user;
HashMap<String,Card> userHash = new HashMap <String, Card>(); //key is the cardID
public User(String username, String password)
{
this.username = username;
this.password = password;
}
public String toString()
{
return "User ---------" + "\n" + "Username: " + username + "\n" + "Password: " + password;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public boolean userValidate(String username, String password)
{
if (username.contains(user.getUsername()) && password.contains(user.getPassword()))
{
System.out.println("User accepted");
return true;
}else
System.out.println("Access denied");
return false;
}
public HashMap<String, Card> getCards(String username, String password)
{
for(String value : userHash.keySet())
if (user.userValidate(username, password) == true)
{
//return user's cards
return true;
}else
return null;
return null;
}
public boolean addCard(Card card, String username, String password)
{
if(user.userValidate(username, password) == true)
{
user.getCards(username, password);
}
return false;
}
The card which belongs to the user

Here is my design concept.
In this case, the user class can have many cards and each card has an id.
The validation check must be saved every time when creation user.
The userValidate method can be checked the arguments with its own values then save it to isvalid variable(boolean).
public boolean userValidate(String username, String password)
{
if (username.contains(getUsername()) && password.contains(getPassword()))
{
System.out.println("User accepted");
return isvalid = true;
}else
System.out.println("Access denied");
return isvalid = false;
}
The getCards method is simple because it checks that the isvalid is true or not.
public HashMap<String, Card> getCards() {
if (isvalid) {
// return user's cards
return userHash;
} else
return null;
}
The addCard method, I can just save the card with card id, if user validation is success or nothing...
public boolean addCard(Card card, String username, String password)
{
if(userValidate(username, password))
{
userHash.put(card.getCardId(), card);
return true;
}
return false;
}
So, come together with all these codes.
import java.util.HashMap;
class Card
{
private String cardId;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
}
public class User {
private String username;
private String password;
private boolean isvalid;
HashMap<String, Card> userHash = new HashMap<String, Card>(); // key is the
// cardID
public User(String username, String password) {
this.username = username;
this.password = password;
}
public boolean userValidate(String username, String password)
{
if (username.contains(getUsername()) && password.contains(getPassword()))
{
System.out.println("User accepted");
return isvalid = true;
}else
System.out.println("Access denied");
return isvalid = false;
}
public String toString() {
return "User ---------" + "\n" + "Username: " + username + "\n" + "Password: " + password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public HashMap<String, Card> getCards() {
if (isvalid) {
// return user's cards
return userHash;
} else
return null;
}
public boolean addCard(Card card, String username, String password)
{
if(userValidate(username, password))
{
userHash.put(card.getCardId(), card);
return true;
}
return false;
}
}

You can iterate over the map and add all cards to a list:
List<Card> list = new ArrayList();
for (Map.Entry<String, Card> entry : userHash.entrySet()) {
if(entry.getKey().equals(username)) { list.add(entry.getValue(); }
}
Is that what you were looking for?
Or if you already understood streams:
userHash.entrySet().stream().filter(entry -> username.equals(entry.getValue())
.map(Entry::getKey)
.collect(toList());

Related

How to enable or disable user in Spring Boot Security

I am using spring security for my spring boot app ,this is my user entity
#Document(collection = "users")
public class User {
#Id
private String id;
private String username;
private String isactive;
private String type;
private String date;
private String registrarid;
private String registrartype;
public String getRegistrarid() {
return registrarid;
}
public void setRegistrarid(String registrarid) {
this.registrarid = registrarid;
}
public String getRegistrartype() {
return registrartype;
}
public void setRegistrartype(String registrartype) {
this.registrartype = registrartype;
}
public String getIsactive() {
return isactive;
}
public void setIsactive(String isactive) {
this.isactive = isactive;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(balance);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((isactive == null) ? 0 : isactive.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((registrarid == null) ? 0 : registrarid.hashCode());
result = prime * result + ((registrartype == null) ? 0 : registrartype.hashCode());
result = prime * result + ((roles == null) ? 0 : roles.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
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;
User other = (User) obj;
if (Double.doubleToLongBits(balance) != Double.doubleToLongBits(other.balance))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (enabled != other.enabled)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (isactive == null) {
if (other.isactive != null)
return false;
} else if (!isactive.equals(other.isactive))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (registrarid == null) {
if (other.registrarid != null)
return false;
} else if (!registrarid.equals(other.registrarid))
return false;
if (registrartype == null) {
if (other.registrartype != null)
return false;
} else if (!registrartype.equals(other.registrartype))
return false;
if (roles == null) {
if (other.roles != null)
return false;
} else if (!roles.equals(other.roles))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
private double balance;
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
private boolean enabled=true;
#DBRef
private Set<Role> roles;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
#Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", isactive=" + isactive + ", type=" + type + ", date="
+ date + ", registrarid=" + registrarid + ", registrartype=" + registrartype + ", balance=" + balance
+ ", enabled=" + enabled + ", roles=" + roles + ", password=" + password + "]";
}
}
This is my CustomUser Details Service
#Service
public class CustomUserDetailsService implements UserDetailsService{
#Autowired
private UserServiceImpl userservice;
#Autowired
private RoleServiceImpl roleservice;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user=userservice.getUserByusername(username);
if(user != null) {
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
else {
throw new UsernameNotFoundException("username not found");
}
}
private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
Set<GrantedAuthority> roles = new HashSet<>();
userRoles.forEach((role) -> {
roles.add(new SimpleGrantedAuthority(role.getRole()));
});
List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles);
return grantedAuthorities;
}
private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
}
Currently Custom UserDetails ServiceChecks if username exists or not and then if not found throws exception ,I want to check if the user is enabled or not as well in that ,so that I can set isenabled false as well to deactivate the users.
Just Check for is enabled in loadByUsername method ,Further you can activate and deactivate accordingly.I hope it helps
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user=userservice.getUserByusername(username);
if(user != null && user.isEnabled()) {//here you can check that
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
else {
throw new UsernameNotFoundException("username not found");
}
}
A better approach would be to implement your User entity with org.springframework.security.core.userdetails.UserDetails
and override various methods like
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
if(this.isactive == null) return false;
if(!this.isactive.equals("ACTIVE")) return false;
return true;
}
Override other methods also as required. Spring Security will automatically give org.springframework.security.authentication.DisabledException: User is disabled exception based on isEnabled() result.
If you want to persist the enabled or locked status in the database then you would want to pass the getters for the locked and enabled fields from the User model instance to the UserDetailsImpl constructor.
Firstly,
The authenticate function of the authenticationManager returns these exceptions:
DisabledException, if an account is disabled
LockedException, if an account is locked
BadCredentialsException, if incorrect credentials are presented
You would want to do something along the lines of this:
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authreq.getUsername(), authreq.getPassword()));
} catch (BadCredentialsException ex) {
// do something
} catch (LockedException ex) {
// do something
} catch (DisabledException ex) {
// do something
}
And then in the UserDetailsImpl:
public UserDetailsImpl(Integer id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities, boolean isEnabled) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
this.isEnabled = isEnabled;
}
public static UserDetailsImpl build(User user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList());
return new UserDetailsImpl(user.getId(), user.getUsername(), user.getEmail(), user.getPassword(), authorities,
user.isIsenabled());
}
By the way, in order for this to work you must remove the if statement from the previous answer by #Shubh, instead just have this: return buildUserForAuthentication(user, authorities);
I think this is pretty much what you are looking for.

Authentication code Java

after some research and help from a friend I could make a method (authentificate) that compare the username and password given by the user in the Main and the ones presents in the loginList. The problems is the methode always return false, and I can't find the problem.
Thanks in advance for your help.
Main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String username;
String password;
System.out.println("Enter your username");
username = input.nextLine();
System.out.println("Enter your password");
password = input.nextLine();
UserList test2 = new UserList();
if (test2.authenticate(username, password) == true) {
System.out.println("Hi");
} else {
System.out.println("Username or/and password are wrong.");
}
}
}
User
public class User {
protected String username;
protected String password;
public User(String username, String password) {
this.password = password;
this.username = username;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (o instanceof User) {
return ((User) o).username.equals(username);
}
return false;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + Objects.hashCode(this.username);
return hash;
}
}
UserList
public class UserList {
private HashSet<User> loginList;emphasized text
public UserList() {
Scanner scan;
loginList = new HashSet();
try {
scan = new Scanner(new File("src/boitedejeux/Logins.txt"));
String ligne = scan.nextLine();
while (scan.hasNext()) {
ligne = scan.nextLine();
String[] res = ligne.split(",");
loginList.add(new User(res[0], (res[1])));
}
} catch (FileNotFoundException e) {
System.out.println("Erreur");
}
}
public boolean authenticate(String username, String password) {
if (null == loginList) {
throw new IllegalStateException("The user list isn't initialised");
}
return loginList.stream()
.filter(usern -> usern.getUsername().equals(username))
.filter(passw -> passw.getPassword().equals(password))
.findFirst()
.isPresent();
}
}
Login.txt
Test, Password
Test2, Password2
Remove spaces after commas in your txt, or change the line of String[] res = ligne.split(",") to split with spaces String[] res = ligne.split(", ").

Confused on how to use BufferedReader for reading arraylist of User objects

After the user is registered, they can login which is supposed to read their details from a text file by using a BufferedReader. However, I am unsure of how to use a BufferedReader to read the arraylist of User objects line by line to check the details are in the text file and allow for the user to login.
This is what I have written:
public class LoginJFrame extends javax.swing.JFrame {
ArrayList<User> users = new ArrayList<>();
public LoginJFrame() {
initComponents();
}
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
String nickname = edtNickname.getText();
String loginID = edtLoginID.getText();
String password = String.valueOf(edtPassword.getPassword());
try {
BufferedReader br = new BufferedReader(new FileReader("userinfo.txt"));
String readFile = br.readLine();
while (readFile != null) {
String[] splitString = readFile.split(",");
nickname = splitString[0];
loginID = splitString[1];
password = splitString[2];
User user = new User(nickname, loginID, password);
users.add(user);
readFile = br.readLine();
this.dispose();
ThreadJFrame threadPage = new ThreadJFrame();
threadPage.setVisible(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The only reason why I have another arrayList that is a string is because I cannot figure out a way for the BufferedReader to read my User arrayList line by line. Is there a way for the BufferedReader to read the arraylist class type instead of a string ArrayList?
The User object is a separate class that stores the nickname, login ID and password by using a string.
public class User {
String nickname;
String loginID;
String password;
public User(String nickname, String loginID, String password) {
this.nickname = nickname;
this.loginID = loginID;
this.password = password;
}
public String getNickname() {
return nickname;
}
public String getLoginID() {
return loginID;
}
public String getPassword() {
return password;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setLoginID(String loginID) {
this.loginID = loginID;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User{" + "nickname= " + nickname + ", loginID= " + loginID + ", password= " + password + '}';
}
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
}
Well, that code only reads a single line since you only ever invoke the readline() method once.
The code should be something like:
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
currentLine = br.readLine();
}
And since your data for the User is contained in a single line (since you just save the toString() of your User class) you will need to parse the data into its individual tokens probably by using the String.split(...) method.
Of course your readToFile(...) method won't really do anything because you define the ArrayList locally and don't return any data from the method so the rest of your class can't access the data.

Expected BEGIN_OBJECT but was STRING at line 1 column 1 GSON

I am getting this error when querying a URL and get a json object. My json:
{"status":1,"username":"admin","nombre":"Username","email":"example#example.cl","codigo_usuario":"1","hash":"2938632bfdklsngh","imagen":"05c151584cc1e9aa2985b5bd0a3a4cd2.jpeg"}
Create the User class
public class User {
private int status;
private String username;
private String nombre;
private String email;
private String codigo_usuario;
private String hash;
private String imagen;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
public String getCodigo_usuario() {
return codigo_usuario;
}
public void setCodigo_usuario(String codigo_usuario) {
this.codigo_usuario = codigo_usuario;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User [status=" + status + ", username=" + username
+ ", nombre=" + nombre + ", email=" + email
+ ", codigo_usuario=" + codigo_usuario + ", hash=" + hash
+ ", imagen=" + imagen + "]";
}
}
And in my class, I make the request to the URL I have this code:
public static boolean authenticate(String username, String password){
boolean error = false;
User user = null;
try {
String request = Config.getText("URL_BASE")+Config.getText("URL_AUTHENTICATE")+username+"/"+password;
HttpURLConnection conn = (HttpURLConnection) new URL(request).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new Exception("Failed : HTTP error code : " + conn.getResponseCode());
}
user = new Gson().fromJson(new InputStreamReader(conn.getInputStream()), User.class);
System.out.println(user.toString());
conn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
And I get the exception. I saw other post with this same error and in most the error was the json format or class that did not have the same fields. Now, check well and everything should be OK. But for some reason I receive this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:741)
at controller.WService.authenticate(WService.java:29)
at view.Login._verificarLogin(Login.java:77)
at view.Login$2.actionPerformed(Login.java:44)
I'm new to Java and try to consume a web service for data and use. I think this is my best option but still do not understand the error.

Getting a null pointer exception in object

I can get my data, because i get an error on line 66 which is. but error saying that I get a null value. although I've looked through the code, I think even that, it gets the right value in. I tried using a method that I made just for it. but after that it did not work, I used a method that works, which I use to log in with.
label_KontoId.setText(myPrivate.getAccountName());
My class's looks like this: In my main i got this code
public void SetId(String AccountId, String kode) {
AccountName = AccountId;
Password = kode;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrivatekunderGUI frame = new PrivatekunderGUI();
frame.setVisible(true);
myPrivate = PR.LogindCheck(AccountName, Password);
} catch (Exception e) {
e.printStackTrace();
}
}
});
label_KontoId.setText(myPrivate.getAccountName());
}
This is not all the code, just what's necessary. The other code is generated for the GUI:
public class Private extends Customers {
private String AccountName;
private String Password;
private int Balance;
private int AccountId;
public Private(String Name, int Number, int Zip, String Address, int Phone,
int Balance, int AccountId, String AccountName, String Password) {
super(Name, Number, Zip, Address, Phone);
this.AccountId = AccountId;
this.Balance = Balance;
this.AccountName = AccountName;
this.Password = Password;
}
public String getAccountName() {
return AccountName;
}
public String getPassword() {
return Password;
}
public int getBalance() {
return Balance;
}
public int getAccountId() {
return AccountId;
}
public void setAccountName(String accountName) {
AccountName = accountName;
}
public void setPassword(String password) {
Password = password;
}
public void setBalance(int balance) {
Balance = balance;
}
public void setAccountId(int accountId) {
AccountId = accountId;
}
void account() {
}
#Override
public String toString() {
return "Private [AccountName=" + AccountName + ", Password=" + Password
+ ", Balance=" + Balance + ", AccountId=" + AccountId
+ ", getName()=" + getName() + ", getNumber()=" + getNumber()
+ ", getZip()=" + getZip() + ", getAddress()=" + getAddress()
+ ", getPhone()=" + getPhone() + "]";
}
}
and my PrivateRegistre looks like this:
public class PrivateRegistre {
private ArrayList<Private> privater = new ArrayList<>();
public PrivateRegistre() {
gem("Driton", 32233223, 2400, "Hallovej 54", 32233223, 543442, 1,
"Driton", "1234");
}
public void gem(String Name, int Number, int Zip, String Address,
int Phone, int Balance, int AccountId, String AccountName,
String Password) {
privater.add(new Private(Name, Number, Zip, Address, Phone, Balance,
AccountId, AccountName, Password));
}
public ArrayList<Private> hentalleprivatekunder() {
return privater;
}
public Private findkunde(int AccountId) {
for (Private privat : privater) {
if (privat.getAccountId() == AccountId) {
return privat;
}
}
return null;
}
public Private LogindCheck(String AccountName, String Password) {
for (Private privat : privater) {
if (privat.getAccountName().equals(AccountName)
&& privat.getPassword().equals(Password)) {
return privat;
}
}
return null;
}
public boolean sletprivatekunde(int AccountId) {
Private privat = findkunde(AccountId);
if (privat == null)
return false;
privater.remove(privat);
return true;
}
#Override
public String toString() {
return "PrivateRegistre [Private Kunder=" + privater + "]";
}
public Private HentLogindOplysninger(String AccountName) {
for (Private privat : privater) {
if (privat.getAccountName().equals(AccountName)) {
return privat;
}
}
return null;
}
}
Because you are returning null in your methods
findkunde(...)
HentLogindOplysninger(...)
LogindCheck(...)
You shouldn't be returning null - return something useful and if you have nothing to return better use void in method return type
myPrivate = PR.LogindCheck(AccountName, Password); here you are getting null beacuse you are returning null in method
public Private LogindCheck(String AccountName, String Password)
& also in
public Private findkunde(int AccountId)
just replacereturn null statement with something that would make sense and can be assigned and then used without resulting into NullPointerException;

Categories