Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This methods creates a User File Data Access Object.
- * @param filename the name of the JSON file to be read and write to
- * @param objectMapper is used to convert a User JSON object to/from a User Java object for serialization and deserialization
- * @throws IOException throws when there is an issue with the JSON file
- */
- public UserFileDAO(@Value("${users.file}") String fileName, ObjectMapper objectMapper) throws IOException{
- this.fileName = fileName;
- this.objectMapper = objectMapper;
- load();
- }
- /**
- * This method loads a User object from the JSON file into the Tree map.
- * @return returns map of User objects
- * @throws IOException throws when there is an issue with the JSON file
- */
- private Map<String, User> load() throws IOException{
- users = new TreeMap<>();
- User[] userList = objectMapper.readValue(new FileReader(fileName), User[].class);
- for(User user: userList){
- users.put(user.getUsername(), user);
- }
- return users;
- }
- /**
- * This method is used to save a User objects from the tree map into the JSON file.
- * @return returns true if the User objects were successfully written into the JSON file.
- * @throws IOException throws when there is an issue with the JSON file
- */
- private boolean save() throws IOException{
- User[] userList = getUsersList();
- objectMapper.writeValue(new File(fileName), userList);
- return true;
- }
- /**
- * This method is used to make a list of user object from the Tree Map for any User object that matches the keyword.
- * If the keyword is null, all the users in the Tree Map will be in the list.
- * @param keyword the string to be looked for in the Tree Map that could be added to the User object list
- * @return a populated or empty list of User objects
- */
- private User[] getUsersList(String keyword){
- ArrayList<User> userList = new ArrayList<>();
- for(User user: users.values()){
- if(keyword == null || user.getUsername().contains(keyword)){
- userList.add(user);
- }
- }
- User[] userListNew = new User[userList.size()];
- userList.toArray(userListNew);
- return userListNew;
- }
- /**
- * This method is used to generate a list of User objects from the tree map.
- * @return a populated or empty list of User objects
- */
- private User[] getUsersList(){
- return getUsersList(null);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement