Last active
April 6, 2020 19:49
-
-
Save wkorando/b30fd700679fb3decc91b757728c5ef3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
public class UserService { | |
private List<User> users = new ArrayList<>(); | |
private static final Random ID_GENERATOR = new Random(); | |
public User findUser(long userId) { | |
for(User user : users) { | |
if(user.getId().equals(Long.valueOf(userId))) { | |
return user; | |
} | |
} | |
throw new NotFoundException(); | |
//throw new ClientException(String.format("User id: %d not found!", user.getId())); | |
} | |
public User createUser(User user) { | |
user.setId(ID_GENERATOR.nextLong()); | |
users.add(user); | |
return user; | |
} | |
public User updateUser(long userId, User user) { | |
user.setId(userId); | |
// User equals looks only at the id field which is why this works despite | |
// looking weird | |
if (users.contains(user)) { | |
users.remove(user); | |
users.add(user); | |
return user; | |
} | |
throw new ClientException(String.format("User id: %d not found!", user.getId())); | |
} | |
public void deleteUser(long userId) { | |
Optional<User> foundUser = users.stream().filter(u -> u.getId() == userId).findFirst(); | |
if (foundUser.isPresent()) { | |
users.remove(foundUser.get()); | |
return; | |
} | |
throw new ClientException(String.format("User id: %d not found!", userId)); | |
} | |
public List<User> findAll() { | |
return users; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment