Advertisement
Guest User

Untitled

a guest
Mar 17th, 2024
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. /**
  2. * This methods creates a User File Data Access Object.
  3. * @param filename the name of the JSON file to be read and write to
  4. * @param objectMapper is used to convert a User JSON object to/from a User Java object for serialization and deserialization
  5. * @throws IOException throws when there is an issue with the JSON file
  6. */
  7. public UserFileDAO(@Value("${users.file}") String fileName, ObjectMapper objectMapper) throws IOException{
  8. this.fileName = fileName;
  9. this.objectMapper = objectMapper;
  10. load();
  11. }
  12.  
  13. /**
  14. * This method loads a User object from the JSON file into the Tree map.
  15. * @return returns map of User objects
  16. * @throws IOException throws when there is an issue with the JSON file
  17. */
  18. private Map<String, User> load() throws IOException{
  19. users = new TreeMap<>();
  20.  
  21. User[] userList = objectMapper.readValue(new FileReader(fileName), User[].class);
  22.  
  23. for(User user: userList){
  24. users.put(user.getUsername(), user);
  25. }
  26. return users;
  27. }
  28.  
  29. /**
  30. * This method is used to save a User objects from the tree map into the JSON file.
  31. * @return returns true if the User objects were successfully written into the JSON file.
  32. * @throws IOException throws when there is an issue with the JSON file
  33. */
  34. private boolean save() throws IOException{
  35. User[] userList = getUsersList();
  36. objectMapper.writeValue(new File(fileName), userList);
  37. return true;
  38. }
  39.  
  40. /**
  41. * This method is used to make a list of user object from the Tree Map for any User object that matches the keyword.
  42. * If the keyword is null, all the users in the Tree Map will be in the list.
  43. * @param keyword the string to be looked for in the Tree Map that could be added to the User object list
  44. * @return a populated or empty list of User objects
  45. */
  46. private User[] getUsersList(String keyword){
  47. ArrayList<User> userList = new ArrayList<>();
  48.  
  49. for(User user: users.values()){
  50. if(keyword == null || user.getUsername().contains(keyword)){
  51. userList.add(user);
  52. }
  53. }
  54.  
  55. User[] userListNew = new User[userList.size()];
  56. userList.toArray(userListNew);
  57. return userListNew;
  58. }
  59.  
  60. /**
  61. * This method is used to generate a list of User objects from the tree map.
  62. * @return a populated or empty list of User objects
  63. */
  64. private User[] getUsersList(){
  65. return getUsersList(null);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement