I want to create a login method for my spring application. But when I try to call the
getUserByAuthentication
method, I get a null pointer exception. Here is my code:
Function calling the error:
@PostMapping(path = "/online")
public ResponseEntity<?> onlineRequest(@RequestBody OnlineRequest onlineRequest) {
    User user = null;
UserManager userManager = new UserManager();
    user = userManager.getUserByAuthentication(onlineRequest.getUsername(), onlineRequest.getPassword());
    if (user!=null){
        user.setLatestTimeStamp(System.currentTimeMillis());
        return new ResponseEntity<>("You are now online, Enjoy!", HttpStatus.OK);
    } else {
        return new ResponseEntity<>("Invalid login", HttpStatus.valueOf(403));
    }
}
Get User by Authentication class:
public class UserManager {
    @Autowired
    private UserRepository userRepository;
    public User getUserByID(int id){
        return userRepository.findById(id).get();
    }
    public User getUserByAuthentication(String name, String password){
        Iterable<User> userList = userRepository.findAll();
        ArrayList<User> users = new ArrayList<>();
        userList.forEach(users::add);
        User user = null;
        for (User u : users){
            if (u.getUsername().equals(name) && u.getPassword().equals(password)){
                user = u;
            }
        }
        return user;
    }
}
Repository:
@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
User class:
@Entity
@Table
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    //Initialize
    private String username;
    private String password;
    private boolean hasAccess;
    ArrayList<Integer> inChannels;
    long latestTimeStamp;
    public long getLatestTimeStamp() {
        return latestTimeStamp;
    }
    public void setLatestTimeStamp(long latestTimeStamp) {
        this.latestTimeStamp = latestTimeStamp;
    }
    public ArrayList<Integer> getInChannels() {
        return inChannels;
    }
    public void setInChannels(ArrayList<Integer> inChannels) {
        this.inChannels = inChannels;
    }
    public Long getId() {
        return id;
    }
    public User() {
    }
    public boolean hasAccess() {
        return hasAccess;
    }
    public void setAccess(boolean hasAccess) {
        this.hasAccess = hasAccess;
    }
    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;
    }
}
 
    