UserMapper.java 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package rocks.zipcode.io.service.mapper;
  2. import rocks.zipcode.io.domain.Authority;
  3. import rocks.zipcode.io.domain.User;
  4. import rocks.zipcode.io.service.dto.UserDTO;
  5. import org.springframework.stereotype.Service;
  6. import java.util.*;
  7. import java.util.stream.Collectors;
  8. /**
  9. * Mapper for the entity User and its DTO called UserDTO.
  10. *
  11. * Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
  12. * support is still in beta, and requires a manual step with an IDE.
  13. */
  14. @Service
  15. public class UserMapper {
  16. public UserDTO userToUserDTO(User user) {
  17. return new UserDTO(user);
  18. }
  19. public List<UserDTO> usersToUserDTOs(List<User> users) {
  20. return users.stream()
  21. .filter(Objects::nonNull)
  22. .map(this::userToUserDTO)
  23. .collect(Collectors.toList());
  24. }
  25. public User userDTOToUser(UserDTO userDTO) {
  26. if (userDTO == null) {
  27. return null;
  28. } else {
  29. User user = new User();
  30. user.setId(userDTO.getId());
  31. user.setLogin(userDTO.getLogin());
  32. user.setFirstName(userDTO.getFirstName());
  33. user.setLastName(userDTO.getLastName());
  34. user.setEmail(userDTO.getEmail());
  35. user.setImageUrl(userDTO.getImageUrl());
  36. user.setActivated(userDTO.isActivated());
  37. user.setLangKey(userDTO.getLangKey());
  38. Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
  39. if (authorities != null) {
  40. user.setAuthorities(authorities);
  41. }
  42. return user;
  43. }
  44. }
  45. public List<User> userDTOsToUsers(List<UserDTO> userDTOs) {
  46. return userDTOs.stream()
  47. .filter(Objects::nonNull)
  48. .map(this::userDTOToUser)
  49. .collect(Collectors.toList());
  50. }
  51. public User userFromId(Long id) {
  52. if (id == null) {
  53. return null;
  54. }
  55. User user = new User();
  56. user.setId(id);
  57. return user;
  58. }
  59. public Set<Authority> authoritiesFromStrings(Set<String> strings) {
  60. return strings.stream().map(string -> {
  61. Authority auth = new Authority();
  62. auth.setName(string);
  63. return auth;
  64. }).collect(Collectors.toSet());
  65. }
  66. }