Skip to content

Instantly share code, notes, and snippets.

@wkorando
Last active April 6, 2020 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkorando/b30fd700679fb3decc91b757728c5ef3 to your computer and use it in GitHub Desktop.
Save wkorando/b30fd700679fb3decc91b757728c5ef3 to your computer and use it in GitHub Desktop.
@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